package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.AuthIgnore;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxCUser;
import com.iformall.domain.po.WxCUserBasicInfo;
import com.iformall.domain.po.WxCouponOrder;
import com.iformall.domain.po.WxMerchantBUser;
import com.iformall.domain.vo.WxCouponOrderCVo;
import com.iformall.enums.EnumCreditLockedStatus;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxCUserBasicInfoService;
import com.iformall.service.WxCUserService;
import com.iformall.service.WxCouponOrderService;
import com.iformall.service.WxMerchantBUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/couponOrder")
@Api(description = "卡券相关接口")
public class WxCouponOrderController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponOrderService wxCouponOrderService;

    @Autowired
    private WxMerchantBUserService wxMerchantBUserService;

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @Autowired
    private WxCUserService wxCUserService;


    @ApiOperation("分页列表接口")
    @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(@ModelAttribute WxCouponOrder wxCouponOrder, Integer pageNum, Integer pageSize) {
        if (null == wxCouponOrder) wxCouponOrder = new WxCouponOrder();
        final PageInfo<WxCouponOrder> page = wxCouponOrderService.listAsPage(wxCouponOrder, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("根据id更新接口")
    @PostMapping("update")
    public ResultData update(@RequestBody WxCouponOrder wxCouponOrder) {
        wxCouponOrderService.saveOrUpdate(wxCouponOrder);
        return new ResultData();
    }

    @ApiOperation("交易流水分页列表接口")
    @GetMapping("listUnverified")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期yyyy-MM-dd", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query",required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query",required = true)})
    public ResultData listUnverified(String date, Integer pageNum, Integer pageSize) {
        return wxCouponOrderService.listOnDateAsPage(getUser().getId(), date, pageNum, pageSize, false);
    }

    @ApiOperation("核销流水分页列表接口")
    @GetMapping("listVerified")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期yyyy-MM-dd", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query",required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query",required = true)})
    public ResultData listVerified(String date, Integer pageNum, Integer pageSize) {
        return wxCouponOrderService.listOnDateAsPage(getUser().getId(), date, pageNum, pageSize, true);
    }


    @ApiOperation("某日期交易总流水")
    @GetMapping("getUnverifiedAmountOnDate")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期yyyy-MM-dd", dataType = "string", paramType = "query")})
    public ResultData getUnverifiedAmountOnDate(String date) {
        return wxCouponOrderService.listOnDateAsPage(getUser().getId(), date, null, null, false);
    }

    @ApiOperation("某日期核销总流水")
    @GetMapping("getVerifiedAmountOnDate")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期yyyy-MM-dd", dataType = "string", paramType = "query")})
    public ResultData getVerifiedAmountOnDate(String date) {
        return wxCouponOrderService.listOnDateAsPage(getUser().getId(), date, null, null, true);
    }


    @ApiOperation(value = "卡券详情接口")
    @GetMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponOrderId", value = "券ID", dataType = "string", paramType = "query", required = true)
    })
        public ResultData detail(String couponOrderId) {
        if(couponOrderId == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        return wxCouponOrderService.detailBUserVo(getUser().getId(), couponOrderId);
    }

    @ApiOperation(value = "核销接口", notes = "{\"couponOrderId\":\"string\"}")
    @PostMapping("verify")
    public ResultData verify(@RequestBody Map<String, String> paramMap) {
        logger.info("couponOrderController.verify:"+paramMap.toString());
        String couponOrderIdStr = paramMap.get("couponOrderId");
        if (StringUtils.isBlank(couponOrderIdStr)) {
            logger.error("couponOrderId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        Long couponOrderId = 0L;
        try {
            couponOrderId = Long.valueOf(couponOrderIdStr);
        } catch (NumberFormatException e) {
            couponOrderId = 0L;
            logger.error("couponOrderId参数不正确: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }

        WxCouponOrderCVo wxCouponOrderCVo = wxCouponOrderService.detailCUserVo(couponOrderIdStr);

        if (wxCouponOrderCVo == null)
            return new ResultData(ErrorCode.COUPON_ORDER_IS_NULL);

        WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoService.getById(wxCouponOrderCVo.getcUserId());
        if (wxCUserBasicInfo != null && EnumCreditLockedStatus.CLOSE.getCode().equals(wxCUserBasicInfo.getStatus())) {
            return new ResultData(ErrorCode.MEMBER_IS_LOCKED);
        }

        if (wxCouponOrderCVo.getValidStartDate() != null && wxCouponOrderCVo.getValidEndDate() != null ) {
            Date now = new Date();
            if (wxCouponOrderCVo.getValidStartDate().getTime() > now.getTime()) {
                logger.error("此券有效期未开始:" + couponOrderIdStr);
                return new ResultData(ErrorCode.COUPON_ORDER_IS_EARLIER_THAN_VALIDDATE);
            }
            if (wxCouponOrderCVo.getValidEndDate().getTime() < now.getTime()) {
                logger.error("此券有效期已结束:" + couponOrderIdStr);
                return new ResultData(ErrorCode.COUPON_ORDER_IS_LATER_THAN_VALIDDATE);
            }
        }

        WxCouponOrder wxCouponOrder = wxCouponOrderService.getById(couponOrderId);
        if (wxCouponOrder == null) {
            logger.error("券ID不存在:" + couponOrderId);
            return new ResultData(ErrorCode.COUPON_ORDER_IS_NULL);
        }

        WxMerchantBUser wxMerchantBUser = wxMerchantBUserService.getById(getUser().getId());
        if (wxMerchantBUser == null) {
            logger.error("核销员ID不存在:" + getUser().getId());
            throw new MallinkException(ErrorCode.USER_IS_EMPTY.getCode(), "核销员ID不存在或者无权限");
        }
        wxMerchantBUser.setBuserId(getBuserId());
        WxCouponOrder couponOrder = null;
        try {
            couponOrder = wxCouponOrderService.verify(wxCouponOrder, wxMerchantBUser);
        } catch (MallinkException e) {
            logger.error("核销异常: " + e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("核销异常: " + e.getMessage());
            return new ResultData(ErrorCode.VERIFY_ERROR, e.getMessage());
        }

        if(couponOrder != null) {
            wxCouponOrderService.sendInsideCouponVerifyMsg(couponOrder.getTenantId(), couponOrderId, wxMerchantBUser.getId());
        }

        return new ResultData(couponOrder);
    }

    @ApiOperation(value = "根据couponOrderId查询接口", notes = "{\"couponOrderId\":\"string\"}")
    @PostMapping("/findById")
    public ResultData findById(@RequestBody Map<String, String> paramMap) {
        logger.info(paramMap.toString());
        String couponOrderIdStr = paramMap.get("couponOrderId");
        if (StringUtils.isBlank(couponOrderIdStr)) {
            logger.error("couponOrderId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        Long couponOrderId = 0L;
        try {
            couponOrderId = Long.valueOf(couponOrderIdStr);
        } catch (NumberFormatException e) {
            couponOrderId = 0L;
            logger.error("couponOrderId参数不正确: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        return new ResultData(Result.SUCCESS, "查询成功", wxCouponOrderService.getById(couponOrderId));
    }

    @ApiOperation(value = "核销接口", notes = "{\"couponOrderId\":\"string\"}")
    @PostMapping("verifyForPos")
    public ResultData verifyForPos(@RequestBody Map<String, String> paramMap) {
        // 0. 获取dev信息, tenantId信息
        // 1. check 查询
        // 2. create order
        // 3. 独立核销

        return new ResultData();
    }




}
