package com.cweb.controller;

import com.cweb.config.SysConfig;
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.security.UserCenter;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.ImageUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.model.*;
import com.hfkj.obs.HuaWeiYunObs;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

@Controller
@Api(value = "商户结算信息")
@RequestMapping(value = "/merSettleAcct")
public class BsMerSettleAcctController {

    private static Logger log = LoggerFactory.getLogger(BsMerSettleAcctController.class);
    @Resource
    private BsMerSettleAcctApplyService merSettleAcctApplyService;
    @Resource
    private BsMerSettleAcctService merSettleAcctService;
    @Resource
    private BsMerService merService;
    @Resource
    private CommonService commonService;

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

            Map<String, Object> param = new HashMap<>();
            param.put("mer", merService.getMerDetail(merId));
            param.put("merSettleAcct", merSettleAcctService.getMerSettleByMerId(merId));
            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value="/createApplyUpdateSettle",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建申请修改结算")
    public ResponseData createApplyUpdateSettle(@RequestBody BsMerSettleAcctApply merSettleAcct) {
        try {
            if (merSettleAcct.getMerId() == null
                || merSettleAcct.getApplyType() == null
                || merSettleAcct.getSettleType() == null
                || StringUtils.isBlank(merSettleAcct.getBankCardNo())
                || StringUtils.isBlank(merSettleAcct.getBankCardHolder())
                || merSettleAcct.getOpenningBankAreaCode() == null
                || (merSettleAcct.getSettleType().equals(MerSettleType.status1.getNumber()) && StringUtils.isBlank(merSettleAcct.getOpenningBankLicenseUrl()))
                || (merSettleAcct.getSettleType().equals(MerSettleType.status2.getNumber()) && StringUtils.isBlank(merSettleAcct.getBankCardImg()))
                || (merSettleAcct.getSettleType().equals(MerSettleType.status3.getNumber()) && StringUtils.isBlank(merSettleAcct.getBankCardImg()))
            ) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (StringUtils.isBlank(merSettleAcct.getOpenningBankName())
                || StringUtils.isBlank(merSettleAcct.getOpenningBankCode())
                || StringUtils.isBlank(merSettleAcct.getClearingBankCode())) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询申请
            BsMerSettleAcctApply apply = merSettleAcctApplyService.getLastApplyByMer(merSettleAcct.getMerId());
            if (apply != null && apply.getStatus().equals(MerSettleAcctApplyStatus.status2.getNumber())) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "已有修改结算申请，请勿重复提交");
            }

            SecRegion openningBankArea = commonService.getRegionsById(merSettleAcct.getOpenningBankAreaCode());
            if (openningBankArea == null) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的的开户地区");
            }

            SecRegion openningBankCity = commonService.getRegionsById(openningBankArea.getParentId());
            if (openningBankCity == null) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的的开户地区");
            }

            SecRegion openningBankProvince = commonService.getRegionsById(openningBankCity.getParentId());
            if (openningBankProvince == null) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的的开户地区");
            }
            merSettleAcct.setOpenningBankAreaName(openningBankArea.getRegionName());
            merSettleAcct.setOpenningBankCityCode(openningBankCity.getRegionId());
            merSettleAcct.setOpenningBankCityName(openningBankCity.getRegionName());
            merSettleAcct.setOpenningBankProvinceCode(openningBankProvince.getRegionId());
            merSettleAcct.setOpenningBankProvinceName(openningBankProvince.getRegionName());

            // 查询商户详情
            BsMer bsMer = merService.getMer(merSettleAcct.getMerId());
            if (bsMer == null) {
                log.error("configMerBasis error!","未知商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知商户");
            }
            if (!bsMer.getMerStatus().equals(MerStatusEnum.status1.getNumber())) {
                log.error("configMerBasis error!","状态错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            // 对私非法人结算
            if (merSettleAcct.getSettleType().equals(MerSettleType.status3.getNumber())) {
                if (StringUtils.isBlank(merSettleAcct.getSettleIdCardPortraitImg())
                        || StringUtils.isBlank(merSettleAcct.getCommissionImg())
                        || StringUtils.isBlank(merSettleAcct.getSettleIdCardNationalEmblemImg())
                        || StringUtils.isBlank(merSettleAcct.getSettleIdCardName())
                        || StringUtils.isBlank(merSettleAcct.getSettleIdCardNo())
                        || StringUtils.isBlank(merSettleAcct.getSettleIdCardPeriodStart())
                        || StringUtils.isBlank(merSettleAcct.getSettleIdCardPeriodEnd())
                        || merSettleAcct.getSettleIdPeriodType() == null) {
                    log.error("configMerBasis error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要填写结算人身份证信息");
                }
            } else {
                // 对公结算、对私法人结算
                merSettleAcct.setSettleIdCardName(bsMer.getLarName());
                merSettleAcct.setSettleIdCardNo(bsMer.getLarIdCard());
                merSettleAcct.setSettleIdCardPortraitImg(bsMer.getLarIdCardPortraitImg());
                merSettleAcct.setSettleIdCardNationalEmblemImg(bsMer.getLarIdCardNationalEmblemImg());
                merSettleAcct.setSettleIdPeriodType(bsMer.getLarIdCardPeriodType());
                merSettleAcct.setSettleIdCardPeriodStart(bsMer.getLarIdCardPeriodStart());
                merSettleAcct.setSettleIdCardPeriodEnd(bsMer.getLarIdCardPeriodEnd());
            }

            merSettleAcct.setMerName(bsMer.getMerName());
            merSettleAcct.setStatus(MerSettleAcctApplyStatus.status1.getNumber());
            merSettleAcctApplyService.createApply(merSettleAcct);

            return ResponseMsgUtil.success("申请成功");

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

    @RequestMapping(value="/getApplyList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户结算申请列表")
    public ResponseData getApplyList(@RequestParam(value = "merId" , required = true) Long merId) {
        try {

            return ResponseMsgUtil.success(merSettleAcctApplyService.getApplyListByMer(merId));

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

    @RequestMapping(value="/getApplyDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户结算申请详情")
    public ResponseData getApplyDetail(@RequestParam(value = "applyId" , required = true) Long applyId) {
        try {

            return ResponseMsgUtil.success(merSettleAcctApplyService.getApplyById(applyId));

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

    @RequestMapping(value="/getLastApplyByMer",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户最新申请修改")
    public ResponseData getLastApplyByMer(@RequestParam(value = "merId" , required = true) Long merId) {
        try {

            return ResponseMsgUtil.success(merSettleAcctApplyService.getLastApplyByMer(merId));

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

}
