package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxMerchant;
import com.iformall.domain.po.WxMerchantBUser;
import com.iformall.domain.po.WxMerchantTradeDaily;
import com.iformall.service.WxMerchantBUserService;
import com.iformall.service.WxMerchantService;
import com.iformall.service.WxMerchantTradeDailyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/wxMerchantTradeDaily")
@Api(description = "解单相关接口")
public class WxMerchantTradeDailyController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxMerchantTradeDailyService wxMerchantTradeDailyService;
    @Autowired
    private WxMerchantBUserService wxMerchantBUserService;
    @Autowired
    private WxMerchantService wxMerchantService;

    @ApiOperation("获得指定日期的解单，默认不传reportDate为当天")
    @GetMapping("/getVolume")
    public ResultData getVolume(WxMerchantTradeDaily wxMerchantTradeDaily) {
        wxMerchantTradeDaily.setTenantId(getTenantId());
        return wxMerchantTradeDailyService.getVolume(wxMerchantTradeDaily,getUser().getId());
    }

    @ApiOperation("获得近7日解单")
    @GetMapping("/getVolumeOfWeek")
    public ResultData getVolumeOfWeek() {
        return wxMerchantTradeDailyService.getVolumeOfWeek(getUser().getId());
    }

    @ApiOperation("上报每日解单")
    @GetMapping("/reportDailyVolume")
    @ApiImplicitParam(name = "volume", value = "总金额（分）", dataType = "Integer", paramType = "query", required = true)
    public ResultData saveDailyTradingVolume(Integer volume) {
        return wxMerchantTradeDailyService.saveDailyTradingVolume(getUser().getId(), volume);
    }

    /**
     * 详情
     * @param wxMerchantTradeDaily
     * @return
     */
    @ApiOperation("详情")
    @GetMapping("findById")
    public ResultData findById(WxMerchantTradeDaily wxMerchantTradeDaily) {
        logger.debug("[" + getIpAddr() + "] wxMerchantTradeDaily::findById");
        String tenantId = getTenantId();
        wxMerchantTradeDaily.setTenantId(tenantId);
        return new ResultData(wxMerchantTradeDailyService.getById(wxMerchantTradeDaily.getId()));
    }

    /**
     * 保存或编辑
     * @param wxMerchantTradeDaily
     * @return
     */
    @ApiOperation("保存或编辑")
    @PostMapping("saveOrUpdate")
    public ResultData saveOrUpdate(@RequestBody WxMerchantTradeDaily wxMerchantTradeDaily) {
        logger.debug("[" + getIpAddr() + "] wxMerchantTradeDaily::saveOrUpdate");
        wxMerchantTradeDaily.setTenantId(super.getTenantId());
        if(wxMerchantTradeDaily.getTradeAmt()!= null){
            wxMerchantTradeDaily.setTradeAmt(Double.parseDouble(wxMerchantTradeDaily.getTradeAmt())*100 +"");
        }

        WxMerchantBUser user = wxMerchantBUserService.getById(getUser().getId());
        if (user==null)
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        WxMerchant merchant = wxMerchantService.getById(user.getMerchantId());
        if (merchant==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        wxMerchantTradeDaily.setMerchantId(merchant.getId());

        // 不能设置未来时间
        if(wxMerchantTradeDaily.getReportDate() !=null){
            try {
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
                if(sd.parse(wxMerchantTradeDaily.getReportDate()).after(new Date())){
                    return new ResultData(ErrorCode.MERCHANT_REPORT_DATE_NOT_VALID);
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("format date error",e);
            }

        }
        wxMerchantTradeDaily.setbUserId(getUser().getId());
        logger.info("1------------------------------------" + wxMerchantTradeDaily.getbUserId());
        wxMerchantTradeDaily.setBUserId(getUser().getId());
        logger.info("2------------------------------------" + wxMerchantTradeDaily.getBUserId());
        wxMerchantTradeDailyService.saveOrUpdate(wxMerchantTradeDaily);
        return new ResultData();
    }

    /**
     * 列表
     *
     * @param wxMerchantTradeDaily
     * @return
     */
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)
    })
    public ResultData list(WxMerchantTradeDaily wxMerchantTradeDaily, Integer pageNum,Integer pageSize) throws Exception{
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");

        //根据userid查询merchantId
        WxMerchantBUser user = wxMerchantBUserService.getById(getUser().getId());
        if (user==null)
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        WxMerchant merchant = wxMerchantService.getById(user.getMerchantId());
        if (merchant==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        wxMerchantTradeDaily.setMerchantId(merchant.getId());

        PageInfo<WxMerchantTradeDaily> pageInfo = wxMerchantTradeDailyService.listAsPage(wxMerchantTradeDaily, pageNum,pageSize);

        List<WxMerchantTradeDaily> resultList = pageInfo.getList();
        // 判断第1条是否是当天
        if(CollectionUtils.isNotEmpty(resultList)){
            if(resultList.get(0).getReportDate().equals(sd.format(new Date()))){
                resultList.get(0).setIsToday(1);
            }
        }
        pageInfo.setList(resultList);
        return new ResultData(pageInfo);
    }

}
