package com.iformall.controller;

import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.po.*;
import com.iformall.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.service.*;
import com.iformall.utils.Constant;
import io.swagger.annotations.Api;
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.util.Date;
import java.util.Map;

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

    @Autowired
    private WxCouponPasswordService couponPasswordService;

    @Autowired
    private WxCouponService couponService;
    @Autowired
    private WxOrderService orderService;


    @ApiOperation(value = "根据卡密领卡", notes = "{\"password\":\"String\",\"formId\":\"String\"}")
    @PostMapping("getCouponOrderByPassword")
    public ResultData getCouponOrderByPassword(@RequestBody Map<String, String> params) {
        logger.info("getCouponOrderByPassword: " + getIpAddr() + params.toString());
        String password = params.get("password");
        String formId = params.get("formId");
        if (StringUtils.isBlank(password) || password.equalsIgnoreCase(Constant.UNDEFINED)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "password不能为空");
        }
        // 1. 根据password获取领取的couponId
        WxCouponPassword couponPasswordQ = new WxCouponPassword();
        couponPasswordQ.setTenantId(getTenantId());
        couponPasswordQ.setPassword(password);
        couponPasswordQ.setExpireDate(new Date());
        WxCouponPassword couponPassword = null;
        try {
            couponPassword = couponPasswordService.getByObj(couponPasswordQ);
        } catch (MallinkException e) {
            logger.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ResultData(500, e.getMessage());
        }

        WxCUser cuUser = getUser();
        WxCoupon coupon = couponService.getById(couponPassword.getCouponId());
        if (coupon == null) {
            return new ResultData(ErrorCode.COUPON_IS_EMPTY);
        }
        if (coupon.getStatus().equals(EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode())) {
            logger.error("此券已作废:" + coupon.getId());
            return new ResultData(ErrorCode.COUPON_IS_TAKE_OFF);
        }

        // 卡密领取卡券
        Integer pwdStatus = couponPassword.getStatus();
        setCouponPasswordStatus(couponPassword, EnumCouponPasswordStatus.USED);
        couponPassword.setStatus(EnumCouponPasswordStatus.USED.getCode());

        // 3. 领取free coupon
        try {
            WxOrder order = orderService.saveFreeOrderForCoupon(cuUser, coupon, null, formId, couponPassword.getId());
        } catch (MallinkException e) {
            setCouponPasswordStatus(couponPassword, EnumCouponPasswordStatus.getEnum(pwdStatus));
            logger.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            setCouponPasswordStatus(couponPassword, EnumCouponPasswordStatus.getEnum(pwdStatus));
            logger.error(e.getMessage());
            return new ResultData(500, e.getMessage());
        }
        return new ResultData();
    }

    private void setCouponPasswordStatus(WxCouponPassword couponPassword, EnumCouponPasswordStatus pwdStatus) {
        WxCouponPassword updateCouponPwd = new WxCouponPassword();
        updateCouponPwd.setId(couponPassword.getId());
        updateCouponPwd.setStatus(pwdStatus.getCode());
        couponPasswordService.saveOrUpdate(updateCouponPwd);
    }

}
