package com.cweb.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.utils.ResponseMsgUtil;
import com.hfkj.entity.BsMer;
import com.hfkj.entity.BsMerRateApply;
import com.hfkj.entity.BsMerRateApplyDetail;
import com.hfkj.entity.SecDictionary;
import com.hfkj.model.ResponseData;
import com.hfkj.service.BsMerRateApplyService;
import com.hfkj.service.BsMerRateService;
import com.hfkj.service.BsMerService;
import com.hfkj.service.CommonService;
import com.hfkj.sysenum.MerRateApplyStatusEnum;
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.stereotype.Controller;
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;

/**
 * @className: BsMerRateController
 * @author: HuRui
 * @date: 2023/7/25
 **/@Controller
@Api(value = "商户费率信息")
@RequestMapping(value = "/merRate")
public class BsMerRateController {

    private static Logger log = LoggerFactory.getLogger(BsMerRateController.class);

    @Resource
    private BsMerService merService;
    @Resource
    private BsMerRateApplyService merRateApplyService;
    @Resource
    private BsMerRateService merRateService;
    @Resource
    private CommonService commonService;

    @RequestMapping(value="/getRateByMer",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据商户查询费率")
    public ResponseData getRateByMer(@RequestParam(value = "merId" , required = true) Long merId) {
        try {

            return ResponseMsgUtil.success(merRateService.getRateListByMerId(merId));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/editRateApply",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑费率申请")
    public ResponseData editRateApply(@RequestBody JSONObject body) {
        try {

            if (body == null
                    || body.getLong("merId") == null
                    || body.getJSONArray("rate") == null
                    || body.getJSONArray("rate").size() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 商户
            BsMer mer = merService.getMer(body.getLong("merId"));
            if (mer == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsMerRateApply rateApply;

            if (body.getLong("rateApplyId") != null) {
                // 查询申请详情
                rateApply = merRateApplyService.getRateApplyById(body.getLong("rateApplyId"));
                if (rateApply == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的申请");
                }
                if (rateApply.getStatus().equals(MerRateApplyStatusEnum.status2.getNumber())
                        || rateApply.getStatus().equals(MerRateApplyStatusEnum.status3.getNumber())
                        || rateApply.getStatus().equals(MerRateApplyStatusEnum.status5)) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态暂时无法修改");
                }
            } else {
                rateApply = new BsMerRateApply();
            }

            rateApply.setMerNo(mer.getMerNo());
            rateApply.setMerId(mer.getId());
            rateApply.setMerName(mer.getMerName());
            rateApply.setStatus(MerRateApplyStatusEnum.status2.getNumber());

            BsMerRateApplyDetail rateApplyDetail = null;
            List<BsMerRateApplyDetail> rateApplyDetailList = new ArrayList<>();
            for (Object obj : body.getJSONArray("rate")) {
                JSONObject rateObject = (JSONObject) obj;
                if (StringUtils.isBlank(rateObject.getString("rateTypeCode"))
                        || rateObject.getBigDecimal("ratePct") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                // 费率代码
                SecDictionary platformNoRate = commonService.mappingSysCode("MER_PLATFORM_NO_RATE", rateObject.getString("rateTypeCode"));
                if (platformNoRate == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "费率代码错误");
                }
                if (body.getLong("rateApplyId") != null) {
                    rateApplyDetail = merRateApplyService.getRateApplyDetail(body.getLong("rateApplyId"), Integer.parseInt(platformNoRate.getCodeValue()));
                    if (rateApplyDetail == null) {
                        rateApplyDetail = new BsMerRateApplyDetail();
                    }
                } else {
                    rateApplyDetail = new BsMerRateApplyDetail();
                }
                rateApplyDetail.setRateTypeCode(Integer.parseInt(platformNoRate.getCodeValue()));
                rateApplyDetail.setRateSaasTypeCode(platformNoRate.getExt2());
                rateApplyDetail.setRateTypeName(platformNoRate.getCodeName());
                rateApplyDetail.setRatePct(rateObject.getBigDecimal("ratePct"));
                rateApplyDetailList.add(rateApplyDetail);
            }
            merRateApplyService.rateApply(rateApply,rateApplyDetailList);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getRateApplyDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询费率申请详情")
    public ResponseData getRateApplyDetail(@RequestParam(value = "rateApplyId" , required = true) Long rateApplyId) {
        try {
            BsMerRateApply rateApply = merRateApplyService.getRateApplyById(rateApplyId);
            if (rateApply == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的费率申请");
            }
            rateApply.setMerRateApplyDetailList(merRateApplyService.getRateApplyDetailListByApply(rateApply.getId()));

            Map<String,Object> param = new HashMap<>();
            param.put("mer", merService.getMer(rateApply.getMerId()));
            param.put("rateApply", rateApply);
            return ResponseMsgUtil.success(param);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getNewRateApplyDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询最新费率申请")
    public ResponseData getNewRateApplyDetail(@RequestParam(value = "merId" , required = true) Long merId) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("merId", merId);
            List<BsMerRateApply> applyList = merRateApplyService.getRateApplyList(param);
            if (applyList.size() > 0) {
                BsMerRateApply rateApply = applyList.get(0);
                rateApply.setMerRateApplyDetailList(merRateApplyService.getRateApplyDetailListByApply(rateApply.getId()));
                return ResponseMsgUtil.success(rateApply);
            }
            return ResponseMsgUtil.success(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
