package com.api.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.ccb.wlpt.util.StringUtil;
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.config.CommonSysConst;
import com.hfkj.entity.BsMer;
import com.hfkj.entity.BsMerLedger;
import com.hfkj.entity.BsTradeOrder;
import com.hfkj.entity.BsTradeOrderRefund;
import com.hfkj.model.ResponseData;
import com.hfkj.openapi.v1.model.TradeBillsModel;
import com.hfkj.openapi.v1.model.request.*;
import com.hfkj.openapi.v1.model.response.*;
import com.hfkj.openapi.v1.service.OpenApiTradeOrderProfitSharingService;
import com.hfkj.openapi.v1.service.OpenApiTradeOrderService;
import com.hfkj.openapi.v1.utils.SignatureUtil;
import com.hfkj.service.BsMerKeyService;
import com.hfkj.service.BsMerLedgerService;
import com.hfkj.service.BsMerService;
import com.hfkj.service.BsTradeOrderProfitSharingService;
import com.hfkj.sysenum.*;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@Api(value = "交易订单")
@RequestMapping(value = "/v1/profitSharing")
public class TradeProfitSharingController {
    private static Logger log = LoggerFactory.getLogger(TradeProfitSharingController.class);

    @Resource
    private BsMerKeyService merKeyService;
    @Resource
    private OpenApiTradeOrderService openApiTradeOrderService;
    @Resource
    private OpenApiTradeOrderProfitSharingService openApiTradeOrderProfitSharingService;
    @Resource
    private BsTradeOrderProfitSharingService tradeOrderProfitSharingService;
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerService merService;

    @RequestMapping(value="/separate",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分账发起")
    public ResponseData separate(@Validated @RequestBody RequestSeparateModel body) {
        log.info("========= Start 分账发起接口 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        try {
            // 验证签名
            if (!SignatureUtil.checkSign(body.getSign(), body, merKeyService.getKeyByMerNo(body.getMerchantNo()))) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            if (body.getRecvDatas() == null || body.getRecvDatas().size() == 0) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未填写分账接收方");
            }
            // 分账流水号重复校验
            if (tradeOrderProfitSharingService.getDetailByProfitSharingOrderNo(body.getOutSeparateNo()) != null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "分账流水号重复");
            }
            // 查询交易订单
            BsTradeOrder tradeOrder = openApiTradeOrderService.getOrderByOutTradeNo(body.getOutTradeNo());
            if (tradeOrder == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未知的交易单号");
            }
            if (!tradeOrder.getStatus().equals(TradeOrderStatusEnum.status3.getNumber())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "交易订单不处于已支付");
            }
            if (tradeOrder.getProfitSharingStatus().equals(false)) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "交易订单不支持分账");
            }
            // 查询商户分账权限
            BsMerLedger merLedger = merLedgerService.getMerLedger(tradeOrder.getMerId(), PlatformTypeEnum.getDataByNumber(tradeOrder.getPlatformType()));
            if (merLedger == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "商户分账权限未开通");
            }
            if (!merLedger.getStatus().equals(MerLedgerStatusEnum.status1.getNumber())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "商户分账权限未开通");
            }
            for (RequestSeparateModel.RequestSeparateRecvDataModel recvData : body.getRecvDatas()) {
                // 校验接收方
                if (recvData.getRecvMerchantNo().equals(body.getMerchantNo())) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "接收方不能与分账方主体相同");
                }
                // 查询接收方信息
                BsMer recvMer = merService.getMer(recvData.getRecvMerchantNo());
                if (recvMer == null) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未知的接收方");
                }
                if (!recvMer.getMerStatus().equals(MerStatusEnum.status1.getNumber())) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "接收方状态异常");
                }
                // 接收方分账信息
                BsMerLedger ledger = merLedgerService.getMerLedger(recvMer.getId(), PlatformTypeEnum.type1);
                if (ledger == null) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "接收方状态异常");
                }
                if (StringUtils.isBlank(ledger.getReceiverNo())) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "接收方状态异常");
                }
            }

            ResponseSeparateModel responseSeparateModel = openApiTradeOrderProfitSharingService.separate(body);
            log.info("返回参数：" + JSONObject.toJSONString(responseSeparateModel));
            return ResponseMsgUtil.success(responseSeparateModel);

        } catch (Exception e) {
            log.info("出现异常：", e);
            return ResponseMsgUtil.exception(e);
        } finally {
            log.info("========= END 分账发起接口 END ===========");
        }
    }

    @RequestMapping(value="/cancel",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分账撤销")
    public ResponseData cancel(@Validated @RequestBody RequestSeparateCancelModel body) {
        log.info("========= Start 分账撤销接口 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        try {
            // 验证签名
            if (!SignatureUtil.checkSign(body.getSign(), body, merKeyService.getKeyByMerNo(body.getMerchantNo()))) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            ResponseSeparateCancelModel responseSeparateCancelModel = openApiTradeOrderProfitSharingService.cancel(body);
            log.info("返回参数：" + JSONObject.toJSONString(responseSeparateCancelModel));
            return ResponseMsgUtil.success(responseSeparateCancelModel);

        } catch (Exception e) {
            log.info("出现异常：", e);
            return ResponseMsgUtil.exception(e);
        } finally {
            log.info("========= END 分账撤销接口 END ===========");
        }
    }

    @RequestMapping(value="/query",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分账结果查询")
    public ResponseData query(@Validated @RequestBody RequestSeparateQueryModel body) {
        log.info("========= Start 分账结果查询接口 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        try {
            // 验证签名
            if (!SignatureUtil.checkSign(body.getSign(), body, merKeyService.getKeyByMerNo(body.getMerchantNo()))) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }

            ResponseSeparateQueryModel query = openApiTradeOrderProfitSharingService.query(body);
            log.info("返回参数：" + JSONObject.toJSONString(query));
            return ResponseMsgUtil.success(query);

        } catch (Exception e) {
            log.info("出现异常：", e);
            return ResponseMsgUtil.exception(e);
        } finally {
            log.info("========= END 分账结果查询接口 END ===========");
        }
    }

    @RequestMapping(value="/queryAmt",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "可分账金额查询")
    public ResponseData queryAmt(@Validated @RequestBody RequestSeparateQueryAmtModel body) {
        log.info("========= Start 可分账金额查询接口 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        try {
            // 验证签名
            if (!SignatureUtil.checkSign(body.getSign(), body, merKeyService.getKeyByMerNo(body.getMerchantNo()))) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            ResponseSeparateQueryAmtModel responseSeparateQueryAmt = openApiTradeOrderProfitSharingService.queryAmt(body);
            log.info("返回参数：" + JSONObject.toJSONString(responseSeparateQueryAmt));
            return ResponseMsgUtil.success(responseSeparateQueryAmt);

        } catch (Exception e) {
            log.info("出现异常：", e);
            return ResponseMsgUtil.exception(e);
        } finally {
            log.info("========= END 可分账金额查询接口 END ===========");
        }
    }



}
