package com.bweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.weixin.utils.WxOrderConfig;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.IDGenerator;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.*;
import com.hfkj.sysenum.PlatformTypeEnum;
import com.hfkj.sysenum.ProfitSharingReceiverRoleEnum;
import com.hfkj.sysenum.TradeOrderRefundStatusEnum;
import com.hfkj.sysenum.TradeOrderStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.collections4.MapUtils;
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.*;

/**
 * @className: BsTradeTakeConfigController
 * @author: HuRui
 * @date: 2023/2/27
 **/
@Controller
@Api(value = "交易订单退款")
@RequestMapping(value = "/tradeTakeConfig")
public class BsTradeTakeConfigController {

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

    @Resource
    private BsCompanyService companyService;
    @Resource
    private BsTradeTakeConfigService tradeTakeConfigService;
    @Resource
    private BsAgentService agentService;
    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/editParentCompanyConfig",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑母公司抽成配置")
    public ResponseData editParentCompanyConfig(@RequestBody JSONObject body) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getBsCompany() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (body == null
                || body.getLong("companyId") == null
                || body.getInteger("platformType") == null
                || StringUtils.isBlank(body.getString("receiverAccount"))
                || StringUtils.isBlank(body.getString("receiverName"))
                || body.getBigDecimal("receiverRatio") == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 公司
            BsCompany company = companyService.getCompanyById(body.getLong("companyId"));
            if (company == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知公司");
            }
            // 平台类型
            PlatformTypeEnum platformType = PlatformTypeEnum.getDataByNumber(body.getInteger("platformType"));
            if (platformType == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的平台");
            }
            // 接收方角色
            ProfitSharingReceiverRoleEnum receiverRoleEnum = ProfitSharingReceiverRoleEnum.role1;

            // 查询配置
            BsTradeTakeConfig tradeTakeConfig = tradeTakeConfigService.getTradeTakeConfig(
                                                                            company.getId(),
                                                                            platformType,
                                                                            receiverRoleEnum,
                                                                            userInfoModel.getBsCompany().getId(),
                                                                            null);
            if (tradeTakeConfig == null) {
                tradeTakeConfig = new BsTradeTakeConfig();
            }
            tradeTakeConfig.setCompanyId(company.getId());
            tradeTakeConfig.setCompanyName(company.getName());
            tradeTakeConfig.setPlatformType(platformType.getNumber());
            tradeTakeConfig.setPlatformTypeName(platformType.getName());
            tradeTakeConfig.setReceiverRole(receiverRoleEnum.getNumber());
            tradeTakeConfig.setReceiverRoleName(receiverRoleEnum.getName());
            tradeTakeConfig.setReceiverAccount(body.getString("receiverAccount"));
            tradeTakeConfig.setReceiverName(body.getString("receiverName"));
            tradeTakeConfig.setReceiverRatio(body.getBigDecimal("receiverRatio"));
            tradeTakeConfig.setReceiverObjectId(userInfoModel.getBsCompany().getId());
            tradeTakeConfig.setReceiverObjectName(userInfoModel.getBsCompany().getName());
            tradeTakeConfig.setOpUserId(userInfoModel.getSecUser().getId());
            tradeTakeConfig.setOpUserName(userInfoModel.getSecUser().getUserName());
            tradeTakeConfigService.editData(tradeTakeConfig);


            BsTradeTakeConfig finalTradeTakeConfig = tradeTakeConfig;
            new Thread(() -> {
                Map<String,Object> param = new HashMap<>();
                param.put("platformType", PlatformTypeEnum.type4.getNumber());
                List<BsMerPlatformNo> merPlatformNoList = merPlatformNoService.getMerPlatformNoList(param);
                for (BsMerPlatformNo platformNo : merPlatformNoList) {
                    try {
                        TreeMap<String, String> response = WxOrderConfig.profitsharingAddReceiver(platformNo.getPlatformNo(), finalTradeTakeConfig.getReceiverName(), finalTradeTakeConfig.getReceiverAccount());
                        if(!"SUCCESS".equals(MapUtils.getString(response, "return_code")) || !"SUCCESS".equals(MapUtils.getString(response, "result_code"))) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "与商户号："+platformNo.getPlatformNo()+"创建分账关系失败！原因:" + MapUtils.getString(response,"err_code_des"));
                        }
                    } catch (Exception e) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "与商户号："+platformNo.getPlatformNo()+"创建分账关系失败！原因：" + e);
                    }

                }
            });

            return ResponseMsgUtil.success("配置成功");

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

    @RequestMapping(value="/editAgentConfig",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑代理商抽成配置")
    public ResponseData editAgentConfig(@RequestBody JSONObject body) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getBsCompany() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            if (body == null
                    || body.getInteger("platformType") == null

                    || StringUtils.isBlank(body.getString("receiverName"))
                    || StringUtils.isBlank(body.getString("receiverAccount"))
                    || body.getBigDecimal("receiverRatio") == null

                    || StringUtils.isBlank(body.getString("subReceiverName"))
                    || StringUtils.isBlank(body.getString("subReceiverAccount"))
                    || body.getBigDecimal("subReceiverRatio") == null
                    || body.getLong("subReceiverObjectId") == null
            ) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 平台类型
            PlatformTypeEnum platformType = PlatformTypeEnum.getDataByNumber(body.getInteger("platformType"));
            if (platformType == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的平台");
            }
            // 公司
            BsCompany company = companyService.getCompanyById(userInfoModel.getBsCompany().getId());
            if (company == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知公司");
            }
            // 代理商
            BsAgent agent = agentService.getAgent(body.getLong("subReceiverObjectId"));
            if (agent == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知代理商");
            }
            // 公司角色
            ProfitSharingReceiverRoleEnum receiverRoleEnum = ProfitSharingReceiverRoleEnum.role2;
            // 代理商角色
            ProfitSharingReceiverRoleEnum subReceiverRoleEnum = ProfitSharingReceiverRoleEnum.role3;
            // 查询配置
            BsTradeTakeConfig tradeTakeConfig = tradeTakeConfigService.getTradeTakeConfig(
                    company.getId(),
                    platformType,
                    receiverRoleEnum,
                    company.getId(),
                    body.getLong("subReceiverObjectId"));

            if (tradeTakeConfig == null) {
                tradeTakeConfig = new BsTradeTakeConfig();
            }
            tradeTakeConfig.setCompanyId(company.getId());
            tradeTakeConfig.setCompanyName(company.getName());
            tradeTakeConfig.setPlatformType(platformType.getNumber());
            tradeTakeConfig.setPlatformTypeName(platformType.getName());
            tradeTakeConfig.setReceiverRole(receiverRoleEnum.getNumber());
            tradeTakeConfig.setReceiverRoleName(receiverRoleEnum.getName());
            tradeTakeConfig.setReceiverAccount(body.getString("receiverAccount"));
            tradeTakeConfig.setReceiverName(body.getString("receiverName"));
            tradeTakeConfig.setReceiverRatio(body.getBigDecimal("receiverRatio"));
            tradeTakeConfig.setReceiverObjectId(company.getId());
            tradeTakeConfig.setReceiverObjectName(company.getName());

            tradeTakeConfig.setSubReceiverRole(subReceiverRoleEnum.getNumber());
            tradeTakeConfig.setSubReceiverRoleName(subReceiverRoleEnum.getName());
            tradeTakeConfig.setSubReceiverName(body.getString("subReceiverName"));
            tradeTakeConfig.setSubReceiverAccount(body.getString("subReceiverAccount"));
            tradeTakeConfig.setSubReceiverRatio(body.getBigDecimal("subReceiverRatio"));
            tradeTakeConfig.setSubReceiverObjectId(agent.getId());
            tradeTakeConfig.setSubReceiverObjectName(agent.getName());
            tradeTakeConfig.setOpUserId(agent.getId());
            tradeTakeConfig.setOpUserName(agent.getName());
            tradeTakeConfigService.editData(tradeTakeConfig);

            BsTradeTakeConfig finalTradeTakeConfig = tradeTakeConfig;
            new Thread(() -> {
                Map<String,Object> param = new HashMap<>();
                param.put("companyId", finalTradeTakeConfig.getReceiverObjectId());
                param.put("agentId", finalTradeTakeConfig.getSubReceiverObjectId());
                param.put("platformType", PlatformTypeEnum.type4.getNumber());
                List<BsMerPlatformNo> merPlatformNoList = merPlatformNoService.getMerPlatformNoList(param);
                for (BsMerPlatformNo platformNo : merPlatformNoList) {
                    try {
                        TreeMap<String, String> response = WxOrderConfig.profitsharingAddReceiver(platformNo.getPlatformNo(), finalTradeTakeConfig.getReceiverName(), finalTradeTakeConfig.getReceiverAccount());
                        if(!"SUCCESS".equals(MapUtils.getString(response, "return_code")) || !"SUCCESS".equals(MapUtils.getString(response, "result_code"))) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "分公司与商户号："+platformNo.getPlatformNo()+"创建分账关系失败！原因:" + MapUtils.getString(response,"err_code_des"));
                        }

                        TreeMap<String, String> subResponse = WxOrderConfig.profitsharingAddReceiver(platformNo.getPlatformNo(), finalTradeTakeConfig.getSubReceiverName(), finalTradeTakeConfig.getSubReceiverAccount());
                        if(!"SUCCESS".equals(MapUtils.getString(subResponse, "return_code")) || !"SUCCESS".equals(MapUtils.getString(subResponse, "result_code"))) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理商与商户号："+platformNo.getPlatformNo()+"创建分账关系失败！原因:" + MapUtils.getString(subResponse,"err_code_des"));
                        }
                    } catch (Exception e) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "与商户号："+platformNo.getPlatformNo()+"创建分账关系失败！原因：" + e);
                    }
                }
            });

            return ResponseMsgUtil.success("配置成功");

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

    @RequestMapping(value="/getTradeTakeConfig",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询交易配置")
    public ResponseData getTradeTakeConfig(@RequestParam(value = "companyId", required = true) Long companyId,
                                           @RequestParam(value = "platformType", required = true) Integer platformType,
                                           @RequestParam(value = "profitSharingReceiverRole", required = true) Integer profitSharingReceiverRole,
                                           @RequestParam(value = "receiverObjectId", required = false) Long receiverObjectId,
                                           @RequestParam(value = "subReceiverObjectId", required = false) Long subReceiverObjectId) {
        try {

            // 平台类型
            PlatformTypeEnum platform = PlatformTypeEnum.getDataByNumber(platformType);
            if (platformType == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的平台");
            }

            ProfitSharingReceiverRoleEnum receiverRoleEnum = ProfitSharingReceiverRoleEnum.getDataByNumber(profitSharingReceiverRole);
            if (receiverRoleEnum == null) {
                log.error("getTradeTakeConfig error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            return ResponseMsgUtil.success(tradeTakeConfigService.getTradeTakeConfig(companyId, platform, receiverRoleEnum, receiverObjectId, subReceiverObjectId));

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

    @RequestMapping(value="/getAgentTradeTakeConfig",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查代理商交易配置")
    public ResponseData getAgentTradeTakeConfig(@RequestParam(value = "platformType", required = true) Integer platformType,
                                                @RequestParam(value = "agentId", required = true) Long agentId) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getBsCompany() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            // 代理商
            BsAgent agent = agentService.getAgent(agentId);
            if (agent == null) {
                log.error("BsTradeTakeConfigController --> getAgentTradeTakeConfig() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 平台类型
            PlatformTypeEnum platform = PlatformTypeEnum.getDataByNumber(platformType);
            if (platformType == null) {
                log.error("configStore error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的平台");
            }

            return ResponseMsgUtil.success(tradeTakeConfigService.getTradeTakeConfig(agent.getCompanyId(), platform, ProfitSharingReceiverRoleEnum.role2, null, agent.getId()));

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

}
