package com.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.SignatureUtil;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.openapi.model.request.RequestPushDiscountModel;
import com.hfkj.openapi.model.request.RequestPushPkDiscountModel;
import com.hfkj.openapi.model.request.RequestQueryCodeModel;
import com.hfkj.openapi.model.request.RequestQueryDiscountListModel;
import com.hfkj.openapi.model.response.ResponsePushDiscountModel;
import com.hfkj.openapi.model.response.ResponsePushDiscountPkModel;
import com.hfkj.openapi.model.response.ResponseQueryCodeModel;
import com.hfkj.service.agent.BsAgentApiLogService;
import com.hfkj.service.agent.BsAgentApiParamService;
import com.hfkj.service.agent.BsAgentDiscountService;
import com.hfkj.service.discount.BsDiscountPkRelService;
import com.hfkj.service.discount.BsDiscountUserService;
import com.hfkj.sysenum.discount.DiscountStockCodeObtainTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/discount")
@Api(value = "优惠券管理")
public class BsDiscountController {
    private static Logger log = LoggerFactory.getLogger(BsDiscountController.class);
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private BsAgentDiscountService agentDiscountService;
    @Resource
    private BsAgentApiLogService agentApiLogService;
    @Resource
    private BsDiscountUserService discountUserService;

    @RequestMapping(value="/push",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "推送优惠券")
    public ResponseData push(@Validated @RequestBody RequestPushDiscountModel body) {
        log.info("========= Start 推送优惠券 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        BsAgentApiLogWithBLOBs apiLog = new BsAgentApiLogWithBLOBs();
        try {
            // 验证签名
            BsAgentApiParam apiParam = agentApiParamService.getParamByAppId(body.getAppId());
            if (!SignatureUtil.checkSign(body.getSign(), body, apiParam.getAppSecret())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            // 验证请求id
            if (agentApiLogService.isExist(body.getAppId(), body.getReqId())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_REQ_ID_ERR, "");
            }
            apiLog.setAppId(body.getAppId());
            apiLog.setRequestId(body.getReqId());
            apiLog.setRequestUrl("discount/push");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            // 查询代理商是否拥有优惠券权限
            if (agentDiscountService.getDetail(apiParam.getAgentId(),1,body.getDiscountNo()) ==  null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未配置优惠券");
            }
            // 领取优惠券
            List<BsDiscountUser> codeDataList = discountUserService.receive(
                    body.getDiscountNo(),
                    body.getNumber(),
                    DiscountStockCodeObtainTypeEnum.type4, body.getPhone(),
                    body.getAppId()
            );

            List<Map<String,Object>> codeMapList = new ArrayList<>();
            for (BsDiscountUser discountUser : codeDataList) {
                Map<String,Object> codeMap = new HashMap<>();
                codeMap.put("discountNo", discountUser.getDiscountNo());
                codeMap.put("phone", discountUser.getUserPhone());
                codeMap.put("code", discountUser.getDiscountStockCode());
                codeMap.put("status", discountUser.getStatus());
                codeMap.put("createTime", DateUtil.date2String(discountUser.getCreateTime(), DateUtil.Y_M_D_HMS));
                codeMap.put("expirationDate", DateUtil.date2String(discountUser.getExpirationDate(), DateUtil.Y_M_D_HMS));
                codeMapList.add(codeMap);
            }
            ResponsePushDiscountModel response = new ResponsePushDiscountModel();
            response.setReqId(body.getReqId());
            response.setAppId(body.getAppId());
            response.setCodeList(codeMapList);
            response.setSign(SignatureUtil.createSign(response, agentApiParamService.getParamByAppId(body.getAppId()).getAppSecret()));
            log.info("返回参数：" + JSONObject.toJSONString(response));
            apiLog.setResponseParam(JSONObject.toJSONString(response));

            return ResponseMsgUtil.success(response);

        }  catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            apiLog.setErrorContent(JSONObject.toJSONString(exception));
            return exception;
        } finally {
            // 记录日志
            if (apiLog.getAppId() != null) {
                agentApiLogService.edit(apiLog);
            }
            log.info("========= END 推送优惠券 END ===========");
        }
    }

    @RequestMapping(value="/pushPk",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "推送优惠券包")
    public ResponseData pushPk(@Validated @RequestBody RequestPushPkDiscountModel body) {
        log.info("========= Start 推送优惠券包 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        BsAgentApiLogWithBLOBs apiLog = new BsAgentApiLogWithBLOBs();
        try {
            // 验证签名
            BsAgentApiParam apiParam = agentApiParamService.getParamByAppId(body.getAppId());
            if (!SignatureUtil.checkSign(body.getSign(), body, apiParam.getAppSecret())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            // 验证请求id
            if (agentApiLogService.isExist(body.getAppId(), body.getReqId())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_REQ_ID_ERR, "");
            }
            apiLog.setAppId(body.getAppId());
            apiLog.setRequestId(body.getReqId());
            apiLog.setRequestUrl("discount/pushPk");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            // 查询代理商是否拥有优惠券包权限
            if (agentDiscountService.getDetail(apiParam.getAgentId(),2,body.getDiscountPkNo()) ==  null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未配置优惠券包");
            }
            // 领取优惠券
            List<BsDiscountUser> codeDataList = discountUserService.receivePk(
                    body.getDiscountPkNo(),
                    body.getNumber(),
                    DiscountStockCodeObtainTypeEnum.type4, body.getPhone(),
                    body.getAppId()
            );

            List<Map<String,Object>> codeMapList = new ArrayList<>();
            for (BsDiscountUser discountUser : codeDataList) {
                Map<String,Object> codeMap = new HashMap<>();
                codeMap.put("discountNo", discountUser.getDiscountNo());
                codeMap.put("phone", discountUser.getUserPhone());
                codeMap.put("code", discountUser.getDiscountStockCode());
                codeMap.put("status", discountUser.getStatus());
                codeMap.put("createTime", DateUtil.date2String(discountUser.getCreateTime(), DateUtil.Y_M_D_HMS));
                codeMap.put("expirationDate", DateUtil.date2String(discountUser.getExpirationDate(), DateUtil.Y_M_D_HMS));
                codeMapList.add(codeMap);
            }
            ResponsePushDiscountPkModel response = new ResponsePushDiscountPkModel();
            response.setReqId(body.getReqId());
            response.setAppId(body.getAppId());
            response.setDiscountPkNo(body.getDiscountPkNo());
            response.setCodeList(codeMapList);
            response.setSign(SignatureUtil.createSign(response, agentApiParamService.getParamByAppId(body.getAppId()).getAppSecret()));
            log.info("返回参数：" + JSONObject.toJSONString(response));
            apiLog.setResponseParam(JSONObject.toJSONString(response));

            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            apiLog.setErrorContent(JSONObject.toJSONString(exception));
            return exception;
        } finally {
            // 记录日志
            if (apiLog.getAppId() != null) {
                agentApiLogService.edit(apiLog);
            }
            log.info("========= END 推送优惠券包 END ===========");
        }
    }

    @RequestMapping(value="/queryCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询优惠券编码")
    public ResponseData queryCode(@Validated @RequestBody RequestQueryCodeModel body)  {
        log.info("========= Start 查询优惠券编码 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));

        BsAgentApiLogWithBLOBs apiLog = new BsAgentApiLogWithBLOBs();

        try {
            // 验证签名
            BsAgentApiParam apiParam = agentApiParamService.getParamByAppId(body.getAppId());
            if (!SignatureUtil.checkSign(body.getSign(), body, apiParam.getAppSecret())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            // 验证请求id
            if (agentApiLogService.isExist(body.getAppId(), body.getReqId())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_REQ_ID_ERR, "");
            }
            apiLog.setAppId(body.getAppId());
            apiLog.setRequestId(body.getReqId());
            apiLog.setRequestUrl("discount/queryCode");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            // 查询优惠券编码
            BsDiscountUser discountUser = discountUserService.getDetailByCodeId(body.getCode());
            if (discountUser == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到数据");
            }
            ResponseQueryCodeModel response = new ResponseQueryCodeModel();
            response.setReqId(body.getReqId());
            response.setAppId(body.getAppId());
            response.setDiscountNo(discountUser.getDiscountNo());
            response.setPhone(discountUser.getUserPhone());
            response.setCode(discountUser.getDiscountStockCode());
            response.setStatus(discountUser.getStatus());
            response.setCreateTime(DateUtil.date2String(discountUser.getCreateTime(), DateUtil.Y_M_D_HMS));
            response.setExpirationDate(DateUtil.date2String(discountUser.getExpirationDate(), DateUtil.Y_M_D_HMS));
            response.setSign(SignatureUtil.createSign(response, agentApiParamService.getParamByAppId(body.getAppId()).getAppSecret()));
            log.info("返回参数：" + JSONObject.toJSONString(response));
            apiLog.setResponseParam(JSONObject.toJSONString(response));
            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            apiLog.setErrorContent(JSONObject.toJSONString(exception));
            return exception;
        } finally {
            // 记录日志
            if (apiLog.getAppId() != null) {
                agentApiLogService.edit(apiLog);
            }
            log.info("========= END 查询优惠券编码 END ===========");
        }
    }


}
