package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.*;
import com.hfkj.model.ResponseData;
import com.hfkj.service.BsMerLedgerReceiverService;
import com.hfkj.service.BsMerLedgerService;
import com.hfkj.service.BsMerPlatformNoService;
import com.hfkj.service.BsMerService;
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.web.bind.annotation.*;

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

/**
 * @className: BsMerLedgerController
 * @author: HuRui
 * @date: 2023/4/21
 **/
@Controller
@Api(value = "商户分账功能")
@RequestMapping(value = "/merLedger")
public class BsMerLedgerController {

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

    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerService merService;
    @Resource
    private BsMerLedgerReceiverService merLedgerReceiverService;

    @RequestMapping(value="/merLedgerApply",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户分账功能申请")
    public ResponseData merLedgerApply(@RequestBody BsMerLedger body) {
        try {
            System.out.println("请求参数：" + JSONObject.toJSONString(body));
            if (body.getMerId() == null || body.getPlatformType() == null) {
                log.error("BsDeviceOrderPayController -> payOrder error!","参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            if (body.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
                if (body.getSplitLowestRatio() == null || StringUtils.isBlank(body.getSplitEntrustFilePath())) {
                    log.error("BsDeviceOrderPayController -> payOrder error!","参数校验失败");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            }
            // 商户平台
            BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNo(body.getMerId(), PlatformTypeEnum.getDataByNumber(body.getPlatformType()));
            if (merPlatform == null) {
                log.error("BsDeviceOrderPayController -> payOrder error!","参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前平台未进件");
            }
            BsMer mer = merService.getMer(body.getMerId());

            // 设备订单
            BsMerLedger merLedger = merLedgerService.getMerLedger(body.getMerId(), PlatformTypeEnum.getDataByNumber(body.getPlatformType()));
            if (merLedger == null) {
                merLedger = new BsMerLedger();
                merLedger.setMerId(merPlatform.getMerId());
                merLedger.setMerName(mer.getMerName());
                merLedger.setPlatformType(merPlatform.getPlatformType());
                merLedger.setPlatformNo(merPlatform.getPlatformNo());
                merLedger.setCupNo(merPlatform.getCupNo());
                merLedger.setSplitLowestRatio(body.getSplitLowestRatio());
                merLedger.setSplitEntrustFileName(body.getSplitEntrustFilePath().substring(body.getSplitEntrustFilePath().lastIndexOf("/")+1));
                merLedger.setSplitEntrustFilePath(body.getSplitEntrustFilePath());
                if (PlatformTypeEnum.type1.getNumber().equals(merPlatform.getPlatformType())) {
                    merLedger.setStatus(MerLedgerStatusEnum.status2.getNumber());
                } else {
                    merLedger.setStatus(MerLedgerStatusEnum.status1.getNumber());
                }
                merLedger.setReceiverStatus(false);
            } else {
                if (merLedger.getStatus().equals(MerLedgerStatusEnum.status1.getNumber())
                    || merLedger.getStatus().equals(MerLedgerStatusEnum.status2.getNumber())) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法修改");
                }
                merLedger.setMerId(merPlatform.getMerId());
                merLedger.setMerName(mer.getMerName());
                merLedger.setPlatformType(merPlatform.getPlatformType());
                merLedger.setPlatformNo(merPlatform.getPlatformNo());
                merLedger.setCupNo(merPlatform.getCupNo());
                merLedger.setSplitLowestRatio(body.getSplitLowestRatio());
                merLedger.setSplitEntrustFileName(body.getSplitEntrustFilePath().substring(body.getSplitEntrustFilePath().lastIndexOf("/")+1));
                merLedger.setSplitEntrustFilePath(body.getSplitEntrustFilePath());
            }
            merLedgerService.merLedgerApply(merLedger);

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

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

    @RequestMapping(value="/getMerLedgerApply",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户分账功能")
    public ResponseData getMerLedgerApply(@RequestParam(name = "merId", required = true) Long merId,
                                          @RequestParam(name = "platformType", required = true) Integer platformType) {
        try {

            return ResponseMsgUtil.success(merLedgerService.getMerLedger(merId, PlatformTypeEnum.getDataByNumber(platformType)));

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

    @RequestMapping(value="/merLedgerReceiverApply",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户分账绑定接受方申请")
    public ResponseData merLedgerReceiverApply(@RequestBody BsMerLedgerReceiver body) {
        try {

            if (body == null
                    || body.getMerLedgerId() == null
                    || StringUtils.isBlank(body.getReceiverNo())
                    || StringUtils.isBlank(body.getReceiverName())
                    || StringUtils.isBlank(body.getEntrustFilePath())
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠类型");
            }

            // 查询分账开通信息
            BsMerLedger merLedger = merLedgerService.getMerLedgerById(body.getMerLedgerId());
            if (merLedger == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户分账功能未开通");
            }

            // 查询接收方数据
            BsMerLedgerReceiver receiver = merLedgerReceiverService.getMerLedgerReceiver(merLedger.getMerId(), body.getReceiverNo());
            if (receiver == null) {
                receiver = new BsMerLedgerReceiver();
                receiver.setMerId(merLedger.getMerId());
                receiver.setMerLedgerId(merLedger.getId());
                receiver.setPlatformType(merLedger.getPlatformType());
                receiver.setPlatformNo(merLedger.getPlatformNo());
                receiver.setCupNo(merLedger.getCupNo());
                receiver.setReceiverNo(body.getReceiverNo());
                receiver.setReceiverName(body.getReceiverName());
                receiver.setEntrustFileName(body.getEntrustFilePath().substring(body.getEntrustFilePath().lastIndexOf("/")+1));
                receiver.setEntrustFilePath(body.getEntrustFilePath());
            } else {
                receiver.setReceiverNo(body.getReceiverNo());
                receiver.setReceiverName(body.getReceiverName());
                receiver.setEntrustFileName(body.getEntrustFilePath().substring(body.getEntrustFilePath().lastIndexOf("/")+1));
                receiver.setEntrustFilePath(body.getEntrustFilePath());
            }
            merLedgerReceiverService.merLedgerReceiverApply(receiver);

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

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

    @RequestMapping(value="/merLedgerReceiverDelApply",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户分账解绑接受方申请")
    public ResponseData merLedgerReceiverDelApply(@RequestBody BsMerLedgerReceiver body) {
        try {
            if (body == null
                    || body.getMerLedgerId() == null
                    || StringUtils.isBlank(body.getReceiverNo())
                    || StringUtils.isBlank(body.getReceiverName())
                    || StringUtils.isBlank(body.getRelieveEntrustFilePath())
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠类型");
            }

            // 查询分账开通信息
            BsMerLedger merLedger = merLedgerService.getMerLedgerById(body.getMerLedgerId());
            if (merLedger == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户分账功能未开通");
            }

            // 查询接收方数据
            BsMerLedgerReceiver receiver = merLedgerReceiverService.getMerLedgerReceiver(merLedger.getMerId(), body.getReceiverNo());
            if (receiver == null) {
                receiver = new BsMerLedgerReceiver();
                receiver.setMerId(merLedger.getMerId());
                receiver.setMerLedgerId(merLedger.getId());
                receiver.setPlatformType(merLedger.getPlatformType());
                receiver.setPlatformNo(merLedger.getPlatformNo());
                receiver.setCupNo(merLedger.getCupNo());
                receiver.setReceiverNo(body.getReceiverNo());
                receiver.setReceiverName(body.getReceiverName());
                receiver.setRelieveEntrustFileName(body.getRelieveEntrustFilePath().substring(body.getRelieveEntrustFilePath().lastIndexOf("/")+1));
                receiver.setRelieveEntrustFilePath(body.getRelieveEntrustFilePath());
            } else {
                receiver.setReceiverNo(body.getReceiverNo());
                receiver.setReceiverName(body.getReceiverName());
                receiver.setRelieveEntrustFileName(body.getRelieveEntrustFilePath().substring(body.getRelieveEntrustFilePath().lastIndexOf("/")+1));
                receiver.setRelieveEntrustFilePath(body.getRelieveEntrustFilePath());
            }
            merLedgerReceiverService.merLedgerReceiverDel(receiver);

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

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

    @RequestMapping(value="/getLedgerReceiverListByMer",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询接收方列表")
    public ResponseData getLedgerReceiverListByMer(@RequestParam(name = "merId", required = true) Long merId,
                                                   @RequestParam(name = "platformType", required = true) Integer platformType) {
        try {

            return ResponseMsgUtil.success(merLedgerReceiverService.getMerLedgerReceiverByMer(merId, PlatformTypeEnum.getDataByNumber(platformType)));

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

    @RequestMapping(value="/getLedgerReceiverById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询接收方详情")
    public ResponseData getLedgerReceiverById(@RequestParam(name = "ledgerReceiverId", required = true) Long ledgerReceiverId) {
        try {

            return ResponseMsgUtil.success(merLedgerReceiverService.getMerLedgerReceiverById(ledgerReceiverId));

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

    @RequestMapping(value="/getLedgerReceiverList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询接收方列表")
    public ResponseData getLedgerReceiverList(@RequestParam(name = "platformType", required = true) Integer platformType,
                                              @RequestParam(name = "merNme", required = true) String merNme,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("merNme", merNme);
            param.put("platformType", platformType);
            param.put("receiverNoNotNull", "true");

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(merLedgerService.getMerLedgerList(param)));

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

}
