package com.openapi.controller;

import com.alibaba.fastjson.JSONObject;
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.DiscountUserModel;
import com.hfkj.model.ReceiveDiscountPkModel;
import com.hfkj.model.ResponseData;
import com.hfkj.openapi.model.UserDiscountModel;
import com.hfkj.openapi.model.request.*;
import com.hfkj.openapi.model.response.*;
import com.hfkj.service.agent.BsAgentApiLogService;
import com.hfkj.service.agent.BsAgentApiParamService;
import com.hfkj.service.agent.BsAgentDiscountService;
import com.hfkj.service.discount.*;
import com.hfkj.sysenum.discount.DiscountPkStatusEnum;
import com.hfkj.sysenum.discount.DiscountPkStockCodeStatusEnum;
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.*;
import java.util.stream.Collectors;

@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 BsDiscountPkService discountPkService;
    @Resource
    private BsDiscountPkStockBatchService discountPkStockBatchService;
    @Resource
    private BsDiscountPkStockCodeService discountPkStockCodeService;
    @Resource
    private BsDiscountStockCodeService discountStockCodeService;
    @Resource
    private BsDiscountPkRelService discountPkRelService;
    @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="/refund",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退回优惠券")
    public ResponseData refund(@Validated @RequestBody RequestRefundDiscountModel 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/refund");
            apiLog.setRequestParam(JSONObject.toJSONString(body));
            // 退回优惠券
            discountStockCodeService.recycle(body.getDiscountStockCode());

            log.info("返回参数：ok");
            apiLog.setResponseParam("ok");
            return ResponseMsgUtil.success("ok");

        } 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<ReceiveDiscountPkModel> codeDataList = discountUserService.receivePk(
                    body.getDiscountPkNo(),
                    body.getNumber(),
                    DiscountStockCodeObtainTypeEnum.type4, body.getPhone(),
                    body.getAppId()
            );

            List<Map<String,Object>> codeMapList = new ArrayList<>();
            for (ReceiveDiscountPkModel receiveDiscountPk : codeDataList) {
                Map<String,Object> discountPkMap = new HashMap<>();
                discountPkMap.put("phone", receiveDiscountPk.getPhone());
                discountPkMap.put("discountPkNo", receiveDiscountPk.getDiscountPkNo());
                discountPkMap.put("discountPkStockCode", receiveDiscountPk.getDiscountPkStockCode());

                List<Map<String,Object>> codeList = new LinkedList<>();
                for (BsDiscountUser discountUser : receiveDiscountPk.getDiscountUserList()) {
                    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));
                    codeList.add(codeMap);
                }
                discountPkMap.put("codeList", codeList);
                codeMapList.add(discountPkMap);
            }
            ResponsePushDiscountPkModel response = new ResponsePushDiscountPkModel();
            response.setReqId(body.getReqId());
            response.setAppId(body.getAppId());
            response.setList(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="/refundPk",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退回优惠券包")
    public ResponseData refundPk(@Validated @RequestBody RequestRefundPkDiscountModel 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/refundPk");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            discountPkStockBatchService.recycle(Long.parseLong(body.getDiscountPkStockCode()));

            log.info("返回参数：ok");
            apiLog.setResponseParam("ok");
            return ResponseMsgUtil.success("ok");

        } 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="/queryPkDetail",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询优惠券包详情")
    public ResponseData queryPkDetail(@Validated @RequestBody RequestQueryPkDiscountModel 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/queryPkDetail");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            // 查询代理商是否拥有优惠券包权限
            if (agentDiscountService.getDetail(apiParam.getAgentId(),2,body.getDiscountPkNo()) ==  null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未配置优惠券包");
            }
            // 查询优惠券包
            BsDiscountPk discountPk = discountPkService.getDetail(body.getDiscountPkNo());
            if (discountPk ==  null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未找到优惠券包");
            }
            if (!discountPk.getStatus().equals(DiscountPkStatusEnum.status2.getCode())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未找到优惠券包");
            }
            ResponseQueryPkDiscountModel response = new ResponseQueryPkDiscountModel();
            response.setAppId(body.getAppId());
            response.setReqId(body.getReqId());
            response.setDiscountPkNo(discountPk.getDiscountPkNo());
            response.setDiscountPkName(discountPk.getDiscountPkName());
            response.setDiscountList(new LinkedList<>());

            // 券包中的优惠券列表
            List<BsDiscountPkRel> discountPkRelList = discountPkRelService.getList(body.getDiscountPkNo());
            for (BsDiscountPkRel discount : discountPkRelList) {
                JSONObject discountObj = new JSONObject();
                discountObj.put("number", discount.getNumber());
                discountObj.put("discountNo", discount.getDiscountNo());
                discountObj.put("discountName", discount.getDiscountName());
                discountObj.put("discountType", discount.getDiscountType());
                discountObj.put("discountCondition", discount.getDiscountCondition());
                discountObj.put("discountPrice", discount.getDiscountPrice());
                discountObj.put("useScope", discount.getUseScope());
                discountObj.put("receiveExpirationDate", discount.getReceiveExpirationDate());
                response.getDiscountList().add(discountObj);
            }
            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="/queryPkDetailByStockCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据库存code查询优惠券包详情")
    public ResponseData queryPkDetailByStockCode(@Validated @RequestBody RequestQueryPkDiscountByStockCodeModel body) {
        log.info("========= Start 根据库存code查询优惠券包详情 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/queryPkDetailByStockCode");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            // 查询库存code
            BsDiscountPkStockCode stockCode = discountPkStockCodeService.getDetail(Long.parseLong(body.getDiscountPkStockCode()));
            if (stockCode == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到code");
            }
            if (stockCode.getStatus().equals(DiscountPkStockCodeStatusEnum.status1.getCode())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到code");
            }
            ResponseQueryPkDiscountByReqIdModel response = new ResponseQueryPkDiscountByReqIdModel();
            response.setAppId(body.getAppId());
            response.setReqId(body.getReqId());
            response.setDiscountPkNo(stockCode.getDiscountPkNo());
            response.setDiscountPkStockCode(stockCode.getId());
            response.setCodeList(new LinkedList<>());

            List<BsDiscountStockCode> codeList = discountStockCodeService.getCodeListByPkStockId(stockCode.getId());
            for (BsDiscountStockCode obj : codeList) {
                JSONObject code = new JSONObject();
                // 查询用户与优惠券信息
                BsDiscountUser discountUser = discountUserService.getDetailByUserCodeId(obj.getReceiveMerUserPhone(), obj.getId());
                code.put("discountNo", discountUser.getDiscountNo());
                code.put("discountType", discountUser.getDiscountType());
                code.put("discountCondition", discountUser.getDiscountCondition());
                code.put("discountPrice", discountUser.getDiscountPrice());
                code.put("overlayDiscount", discountUser.getOverlayDiscount());
                code.put("phone", discountUser.getUserPhone());
                code.put("code", discountUser.getDiscountStockCode());
                code.put("status", discountUser.getStatus());
                code.put("createTime", DateUtil.date2String(discountUser.getCreateTime(), DateUtil.Y_M_D_HMS));
                code.put("expirationDate", DateUtil.date2String(discountUser.getExpirationDate(), DateUtil.Y_M_D_HMS));
                code.put("useDate", DateUtil.date2String(discountUser.getUseDate(), DateUtil.Y_M_D_HMS));
                response.getCodeList().add(code);
            }
            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 根据库存code查询优惠券包详情 END ===========");
        }
    }

    @RequestMapping(value="/queryPkList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询优惠券包列表")
    public ResponseData queryPkList(@Validated @RequestBody RequestQueryPkDiscountListModel 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/queryPkList");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            ResponseQueryPkDiscountListModel response = new ResponseQueryPkDiscountListModel();
            response.setAppId(body.getAppId());
            response.setReqId(body.getReqId());
            response.setDataList(new LinkedList<>());

            // 券包中的优惠券列表
            List<BsAgentDiscount> list = agentDiscountService.getList(apiParam.getAgentId()).stream().filter(o->o.getType().equals(2)).collect(Collectors.toList());
            for (BsAgentDiscount discount : list) {
                JSONObject discountObj = new JSONObject();
                discountObj.put("discountPkNo", discount.getObjectNo());
                discountObj.put("discountPkName", discount.getObjectName());
                response.getDataList().add(discountObj);
            }
            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 ===========");
        }
    }

    @RequestMapping(value="/queryListByPhone",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据手机号查询优惠券列表")
    public ResponseData queryListByPhone(@Validated @RequestBody RequestQueryListByPhoneModel 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/queryListByPhone");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            Map<String,Object> param = new HashMap<>();
            param.put("userPhone", body.getPhone());
            param.put("status", body.getStatus());
            List<DiscountUserModel> userDiscountList = discountUserService.getUserDiscountList(param);

            ResponseUserDiscountModel response = new ResponseUserDiscountModel();
            response.setReqId(body.getReqId());
            response.setUserPhone(body.getPhone());
            response.setDataList(new LinkedList<>());
            for (DiscountUserModel model : userDiscountList) {
                UserDiscountModel userDiscount = new UserDiscountModel();
                userDiscount.setDiscountNo(model.getDiscountNo());
                userDiscount.setDiscountName(model.getDiscountName());
                userDiscount.setDiscountType(model.getDiscountType());
                userDiscount.setDiscountCondition(model.getDiscountCondition());
                userDiscount.setDiscountPrice(model.getDiscountPrice());
                userDiscount.setCode(model.getDiscountStockCode());
                userDiscount.setCreateTime(model.getCreateTime());
                userDiscount.setUseTime(model.getUseDate());
                userDiscount.setExpirationTime(model.getExpirationDate());
                userDiscount.setStatus(model.getStatus());
                response.getDataList().add(userDiscount);
            }
            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 ===========");
        }
    }


}
