package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConfig;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.channel.lakala.LaKaLaMerService;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
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 = "/mer")
public class BsMerController {

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

    @Resource
    private SysConfig sysConfig;

    @Resource
    private UserCenter userCenter;

    @Resource
    private BsMerService merService;
    @Resource
    private CommonService commonService;
    @Resource
    private BsIndustryService industryService;
    @Resource
    private BsLklMccService mccService;
    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private BsMerContractRecordMsgService merContractRecordMsgService;
    @Resource
    private BsStoreService storeService;

    @RequestMapping(value = "/moveHomeCount", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "移动端首页统计")
    public ResponseData moveHomeCount() {
        try {
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getMer() == null) {
                log.error("BsSalesmanController --> insertSalesman() error!", "权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            String storeStr = "";
            List<BsStore> storeList = storeService.getStoreByMerId(userModel.getMer().getId(), null);
            for (BsStore store : storeList) {
                if (StringUtils.isBlank(storeStr)) {
                    storeStr += store.getId();
                } else {
                    storeStr += "," + store.getId();
                }
            }

            Map<String, Object> map = new HashMap<>();

            Map<String, Object> param = new HashMap<>();
            Calendar payTimeS = Calendar.getInstance();
            payTimeS.setTime(new Date());
            payTimeS.set(Calendar.HOUR_OF_DAY, 00);
            payTimeS.set(Calendar.MINUTE, 00);
            payTimeS.set(Calendar.SECOND, 00);
            param.put("payTimeS", DateUtil.format(payTimeS.getTime(), "yyyy-MM-dd HH:mm:ss"));

            Calendar payTimeE = Calendar.getInstance();
            payTimeE.setTime(new Date());
            payTimeE.set(Calendar.HOUR_OF_DAY, 23);
            payTimeE.set(Calendar.MINUTE, 59);
            payTimeE.set(Calendar.SECOND, 59);
            param.put("payTimeE", DateUtil.format(payTimeE.getTime(), "yyyy-MM-dd HH:mm:ss"));
            param.put("storeId", storeStr);


            // 今日交易额
            param.put("status", 3);
            Map<String, Object> countTrade = storeService.countStoreTrade(param);

            Map<String, Object> today = new HashMap<>();
            today.put("tradeSum", MapUtils.getString(countTrade, "tradeSum"));
            today.put("tradePrice", MapUtils.getString(countTrade, "tradePrice"));


            // 今日退款
            param.put("status", 6);
            Map<String, Object> countRefundTrade = storeService.countStoreTrade(param);
            today.put("refundTradeSum", MapUtils.getString(countRefundTrade, "tradeSum"));
            today.put("refundTradePrice", MapUtils.getString(countRefundTrade, "tradePrice"));

            // 今日交易信息
            map.put("today", today);

            return ResponseMsgUtil.success(map);

        } catch (Exception e) {
            log.error("BsSalesmanController --> moveHomeCount() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/configMerAccount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置商户账户")
    public ResponseData configMerAccount(@RequestBody MerAccountModel merAccount) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getSalesman() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (StringUtils.isBlank(merAccount.getLoginName())
                 || StringUtils.isBlank(merAccount.getName())
                 || StringUtils.isBlank(merAccount.getPhone())
                 || StringUtils.isBlank(merAccount.getEmail())
/*                 || StringUtils.isBlank(merAccount.getSmsCode())*/
            ) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            merAccount.setSalesmanId(userInfoModel.getSalesman().getId());

            Long merId = merService.configMerAccount(merAccount);
            return ResponseMsgUtil.success(merService.getMerDetail(merId));

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

    @RequestMapping(value="/configMerBasis",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置商户基础信息")
    public ResponseData configMerBasis(@RequestBody MerBasisModel mer) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getSalesman() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (mer.getId() == null
                || StringUtils.isBlank(mer.getOrgNo())
                || mer.getMerType() == null
                || StringUtils.isBlank(mer.getMerName())
                || StringUtils.isBlank(mer.getMerAbbreviate())
                || StringUtils.isBlank(mer.getMerMccCode())
                || mer.getMerOperateType() == null

                || StringUtils.isBlank(mer.getLarName())
                || StringUtils.isBlank(mer.getLarIdCard())
                || StringUtils.isBlank(mer.getLarIdCardPortraitImg())
                || StringUtils.isBlank(mer.getLarIdCardNationalEmblemImg())
                || mer.getLarIdCardPeriodType() == null
                || StringUtils.isBlank(mer.getLarIdCardAddress())
                || StringUtils.isBlank(mer.getLarIdCardPeriodStart())
                || StringUtils.isBlank(mer.getLarIdCardPeriodEnd())
                || mer.getMerIndustry() == null
                || mer.getMerIndustry().getChildId() == null
                || mer.getMerRegion() == null
                || mer.getMerRegion().getAreaCode() == null
                || StringUtils.isBlank(mer.getMerRegion().getAddress())
            ) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 商户类型
            if (MerTypeEnum.getDataByNumber(mer.getMerType()) == null) {
                log.error("configMerBasis error!","未知商户类型");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知商户类型");
            }

            if (!mer.getMerType().equals(MerTypeEnum.status3.getNumber())) {
                if (StringUtils.isBlank(mer.getBlisUrl())
                        || StringUtils.isBlank(mer.getBlisName())
                        || StringUtils.isBlank(mer.getBlisNo())
                        || StringUtils.isBlank(mer.getBlisNo())
                        || StringUtils.isBlank(mer.getBlisRegAddress())
                        || mer.getBlisPeriodType() == null
                        || StringUtils.isBlank(mer.getBlisPeriodStart())
                        || StringUtils.isBlank(mer.getBlisPeriodEnd())) {
                    log.error("configMerBasis error!","需要上传营业执照");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要上传营业执照");
                }
            }

            if (mer.getMerOperateType().equals(MerOperateType.type2.getNumber())) {
                if (mer.getMerOnlineType() == null || StringUtils.isBlank(mer.getMerOnlineName())) {
                    log.error("configMerBasis error!","需要上传线上产品类型和产品名称");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要上传线上产品类型和产品名称");
                }
            }

            // 查询商户详情
            BsMer bsMer = merService.getMer(mer.getId());
            if (bsMer == null) {
                log.error("configMerBasis error!","未知商户类型");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知商户类型");
            }

            // MCC编码
            BsLklMcc mcc = mccService.getMccByCode(mer.getMerMccCode());
            if (mcc == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的MCC编码");
            }
            bsMer.setMerMccCode(mcc.getMaccCode());
            bsMer.setMerMccName(mcc.getName());

            // 行业
            Map<String, BsIndustry> industry = industryService.getChildIndustry(mer.getMerIndustry().getChildId());
            if (industry == null) {
                log.error("configMerBasis error!","未知的行业");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的行业");
            }
            mer.getMerIndustry().setChildId(MapUtils.getObject(industry, "child").getId());
            mer.getMerIndustry().setChildName(MapUtils.getObject(industry, "child").getName());
            mer.getMerIndustry().setParentId(MapUtils.getObject(industry, "parent").getId());
            mer.getMerIndustry().setParentName(MapUtils.getObject(industry, "parent").getName());

            Map<String, SecRegion> regionMap = commonService.getParentInfoByRegionId(mer.getMerRegion().getAreaCode());
            if (regionMap == null) {
                log.error("configMerBasis error!","未知的区域");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的区域");
            }
            mer.getMerRegion().setProvinceCode(MapUtils.getObject(regionMap, "city").getRegionId());
            mer.getMerRegion().setProvinceName(MapUtils.getObject(regionMap, "city").getRegionName());
            mer.getMerRegion().setCityCode(MapUtils.getObject(regionMap, "region").getRegionId());
            mer.getMerRegion().setCityName(MapUtils.getObject(regionMap, "region").getRegionName());
            mer.getMerRegion().setAreaCode(MapUtils.getObject(regionMap, "street").getRegionId());
            mer.getMerRegion().setAreaName(MapUtils.getObject(regionMap, "street").getRegionName());

            bsMer.setOrgNo(mer.getOrgNo());
            bsMer.setOrgName(commonService.getDictionaryCodeName("ORG_NO", mer.getOrgNo()));
            bsMer.setMerType(mer.getMerType());
            bsMer.setMerName(mer.getMerName());
            bsMer.setMerAbbreviate(mer.getMerAbbreviate());
            bsMer.setMerMccCode(mer.getMerMccCode());
            bsMer.setMerOperateType(mer.getMerOperateType());
            bsMer.setMerOnlineType(mer.getMerOnlineType());
            bsMer.setMerOnlineName(mer.getMerOnlineName());

            bsMer.setBlisUrl(mer.getBlisUrl());
            bsMer.setBlisName(mer.getBlisName());
            bsMer.setBlisNo(mer.getBlisNo());
            bsMer.setBlisRegAddress(mer.getBlisRegAddress());
            bsMer.setBlisPeriodType(mer.getBlisPeriodType());
            bsMer.setBlisPeriodStart(mer.getBlisPeriodStart());
            bsMer.setBlisPeriodEnd(mer.getBlisPeriodEnd());

            bsMer.setLarName(mer.getLarName());
            bsMer.setLarIdCard(mer.getLarIdCard());
            bsMer.setLarIdCardAddress(mer.getLarIdCardAddress());
            bsMer.setLarIdCardPortraitImg(mer.getLarIdCardPortraitImg());
            bsMer.setLarIdCardNationalEmblemImg(mer.getLarIdCardNationalEmblemImg());
            bsMer.setLarIdCardPeriodType(mer.getLarIdCardPeriodType());
            bsMer.setLarIdCardPeriodStart(mer.getLarIdCardPeriodStart());
            bsMer.setLarIdCardPeriodEnd(mer.getLarIdCardPeriodEnd());
            bsMer.setCompleteStatus(3);
            merService.configMerBasis(bsMer, mer.getMerIndustry(), mer.getMerRegion());

            return ResponseMsgUtil.success(merService.getMerDetail(bsMer.getId()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/configMerSettlement",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置商户结算信息")
    public ResponseData configMerSettlement(@RequestBody BsMerSettleAcct merSettleAcct) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getSalesman() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (merSettleAcct.getMerId() == null
                || merSettleAcct.getSettleType() == null
                || StringUtils.isBlank(merSettleAcct.getBankCardNo())
                || StringUtils.isBlank(merSettleAcct.getBankCardHolder())
                || merSettleAcct.getOpenningBankAreaCode() == null
                || merSettleAcct.getMerRateList() == null
                || merSettleAcct.getMerRateList().size() == 0
                || (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, "");
            }

            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 (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());
            }

            merService.configMerSettlement(merSettleAcct);

            return ResponseMsgUtil.success(merService.getMerDetail(bsMer.getId()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/configMerStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置商户门店")
    public ResponseData configMerStore(@RequestBody StoreModel storeModel) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getSalesman() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (storeModel == null
                    || storeModel.getMerId() == null
                    || StringUtils.isBlank(storeModel.getName())
                    || StringUtils.isBlank(storeModel.getTelephone())
                    || StringUtils.isBlank(storeModel.getDoorHeadImg())
                    || StringUtils.isBlank(storeModel.getCashRegisterImg())
                    || StringUtils.isBlank(storeModel.getInternalImg())
                    || storeModel.getStoreRegion() == null
                    || StringUtils.isBlank(storeModel.getStoreRegion().getAddress())
                    || storeModel.getStoreRegion().getAreaCode() == null
                    || storeModel.getStoreRegion().getLongitude() == null
                    || storeModel.getStoreRegion().getLatitude() == null
            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询商户
            MerBasisModel mer = merService.getMerDetail(storeModel.getMerId());
            if (mer == null) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            if (storeModel.getId() == null) {
                if (storeService.getStoreByMerId(mer.getId(), StoreCreateTypeEnum.type1).size() < 0) {
                    log.error("configMerBasis error!","已经创建了门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已经创建了门店");
                }
            }

            List<BsStore> store = storeService.getStoreByMerId(mer.getId(), StoreCreateTypeEnum.type1);
            if (store.size() > 0) {
                storeModel.setId(store.get(0).getId());
                storeModel.setStoreNo(store.get(0).getStoreNo());
                storeModel.setStatus(store.get(0).getStatus());
                storeModel.setCreateTime(store.get(0).getCreateTime());
            }

            storeModel.setCompanyId(mer.getCompanyId());
            storeModel.setCompanyName(mer.getCompanyName());
            storeModel.setAgentId(mer.getAgentId());
            storeModel.setAgentName(mer.getAgentName());
            storeModel.setSalesmanId(mer.getSalesmanId());
            storeModel.setSalesmanName(mer.getSalesmanName());
            storeModel.setCreateSalesmanId(mer.getCreateSalesmanId());
            storeModel.setCreateSalesmanName(mer.getCreateSalesmanName());
            storeModel.setMerId(mer.getId());
            storeModel.setMerName(mer.getMerName());
            storeModel.setStoreType(mer.getMerType());
            storeModel.setStatus(StoreStatusEnum.status3.getNumber());
            storeModel.setBlisUrl(mer.getBlisUrl());
            storeModel.setBlisName(mer.getBlisName());
            storeModel.setBlisNo(mer.getBlisNo());
            storeModel.setBlisRegAddress(mer.getBlisRegAddress());
            storeModel.setBlisPeriodType(mer.getBlisPeriodType());
            storeModel.setBlisPeriodStart(mer.getBlisPeriodStart());
            storeModel.setBlisPeriodEnd(mer.getBlisPeriodEnd());

            storeModel.setLarIdCard(mer.getLarIdCard());
            storeModel.setLarName(mer.getLarName());
            storeModel.setLarIdCardPortraitImg(mer.getLarIdCardPortraitImg());
            storeModel.setLarIdCardNationalEmblemImg(mer.getLarIdCardNationalEmblemImg());
            storeModel.setLarIdCardPeriodType(mer.getLarIdCardPeriodType());
            storeModel.setLarIdCardPeriodStart(mer.getLarIdCardPeriodStart());
            storeModel.setLarIdCardPeriodEnd(mer.getLarIdCardPeriodEnd());

            storeModel.setCreateType(StoreCreateTypeEnum.type1.getNumber());
            storeModel.setStoreIndustry(new BsStoreIndustry());
            storeModel.getStoreIndustry().setParentId(mer.getMerIndustry().getParentId());
            storeModel.getStoreIndustry().setParentName(mer.getMerIndustry().getParentName());
            storeModel.getStoreIndustry().setChildId(mer.getMerIndustry().getChildId());
            storeModel.getStoreIndustry().setChildName(mer.getMerIndustry().getChildName());

            // 区域
            Map<String, SecRegion> regionMap = commonService.getParentInfoByRegionId(storeModel.getStoreRegion().getAreaCode());
            if (regionMap == null) {
                log.error("configMerBasis error!","未知的区域");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的区域");
            }
            storeModel.getStoreRegion().setProvinceCode(MapUtils.getObject(regionMap, "city").getRegionId());
            storeModel.getStoreRegion().setProvinceName(MapUtils.getObject(regionMap, "city").getRegionName());
            storeModel.getStoreRegion().setCityCode(MapUtils.getObject(regionMap, "region").getRegionId());
            storeModel.getStoreRegion().setCityName(MapUtils.getObject(regionMap, "region").getRegionName());
            storeModel.getStoreRegion().setAreaCode(MapUtils.getObject(regionMap, "street").getRegionId());
            storeModel.getStoreRegion().setAreaName(MapUtils.getObject(regionMap, "street").getRegionName());

          /*  storeModel.getStoreRegion().setProvinceCode(mer.getMerRegion().getProvinceCode());
            storeModel.getStoreRegion().setProvinceName(mer.getMerRegion().getProvinceName());
            storeModel.getStoreRegion().setCityCode(mer.getMerRegion().getCityCode());
            storeModel.getStoreRegion().setCityName(mer.getMerRegion().getCityName());
            storeModel.getStoreRegion().setAreaCode(mer.getMerRegion().getAreaCode());
            storeModel.getStoreRegion().setAreaName(mer.getMerRegion().getAreaName());
            storeModel.getStoreRegion().setAddress(mer.getMerRegion().getAddress());*/

            merService.configMerStore(storeModel);

            return ResponseMsgUtil.success(merService.getMerDetail(storeModel.getMerId()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/reconsider",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "复议")
    public ResponseData reconsider(@RequestBody JSONObject body) {
        try {

            if (body == null || body.getLong("merId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
            }

            merService.reconsider(body.getLong("merId"));
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/getMerDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户详情")
    public ResponseData getMerDetail(@RequestParam(value = "merId" , required = true) Long merId,
                                     @RequestParam(value = "merPlatformType" , required = false) Integer merPlatformType) {
        try {
            // 查询商户
            MerBasisModel merDetail = merService.getMerDetail(merId);
            if (merDetail == null) {
                log.error("getMerDetail error!","未知的商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }
            // 查询错误消息
            if (merDetail.getMerStatus().equals(MerStatusEnum.status4.getNumber())) {
                Map<String, Object> recordMsg = merContractRecordMsgService.getMerContractRecordMsg(merDetail.getId(), null);
                recordMsg.put("response_msg", recordMsg.get("response_msg"));
                merDetail.setMerContractFailMsg(recordMsg);
                merDetail.setCompleteStatus(MerCompleteStatusEnum.status2.getNumber());
                merDetail.setMerStatus(MerStatusEnum.status4.getNumber());
            }
            if (merPlatformType != null) {
                BsMerPlatformNo platformNo = merPlatformNoService.getPlatformNo(merId, PlatformTypeEnum.getDataByNumber(merPlatformType), MerPlatformNoStatusEnum.status3);
                if (platformNo != null) {
                    Map<String, Object> recordMsg = new HashMap<>();
                    recordMsg.put("response_msg", platformNo.getSuggestionReject());
                    merDetail.setMerContractFailMsg(recordMsg);
                    merDetail.setCompleteStatus(MerCompleteStatusEnum.status2.getNumber());
                    merDetail.setMerStatus(MerStatusEnum.status4.getNumber());
                }
            }
            return ResponseMsgUtil.success(merDetail);

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

    @RequestMapping(value="/getMerListBySalesman",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "业务员查询商户列表")
    public ResponseData getMerListBySalesman(@RequestParam(value = "merName" , required = false) String merName,
                                             @RequestParam(value = "merStatus" , required = false) Integer merStatus,
                                             @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                             @RequestParam(value = "pageSize" , required = true) Integer pageSize
                                             ) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getSalesman() == null) {
                log.error("configAccount error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("salesmanId", userInfoModel.getSalesman().getId());
            map.put("merName", merName);
            map.put("merStatus", merStatus);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(merService.getMerList(map)));

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

    @RequestMapping(value="/getMerList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户列表")
    public ResponseData getMerList(@RequestParam(value = "agentId" , required = false) Long agentId,
                                   @RequestParam(value = "salesmanId" , required = false) Long salesmanId,
                                   @RequestParam(value = "merType" , required = false) Integer merType,
                                   @RequestParam(value = "merNo" , required = false) String merNo,
                                   @RequestParam(value = "merName" , required = false) String merName,
                                   @RequestParam(value = "regName" , required = false) String regName,
                                   @RequestParam(value = "regPhone" , required = false) String regPhone,
                                   @RequestParam(value = "merStatus" , required = false) Integer merStatus,
                                   @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                   @RequestParam(value = "pageSize" , required = true) Integer pageSize
    ) {
        try {
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);

            Map<String,Object> map = new HashMap<>();
            map.put("merType", merType);
            map.put("merNo", merNo);
            map.put("merName", merName);
            map.put("merStatus", merStatus);
            map.put("regName", regName);
            map.put("regPhone", regPhone);

            if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type1.getNumber())) {
                map.put("agentId", agentId);
                map.put("salesmanId", salesmanId);
            }

            if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type2.getNumber())) {
                map.put("agentId", userModel.getAgent().getId());
                map.put("salesmanId", salesmanId);
            }

            if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type3.getNumber())) {
                map.put("salesmanId", userModel.getSalesman().getId());
            }

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(merService.getMerList(map)));

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


    @RequestMapping(value="/uploadfile",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "文件上传")
    public ResponseData uploadFile(@RequestParam(value = "merId" , required = true) Long merId,
                                   @RequestParam(value = "files" , required = false) MultipartFile files,
                                   HttpServletRequest request,HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 判断 request 是否有文件上传,即多部分请求
            List<String> fileNames = new ArrayList<String>();
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iterator = multiRequest.getFileNames();

                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iterator.next());
                    if (file != null) {
                        FileOutputStream out = null;
                        try {
                            String fileType = file.getOriginalFilename()
                                    .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                            String fileName = System.currentTimeMillis() + "." + fileType;
                            String childPath = "merchant";
                            String destDirName = sysConfig.getFileUrl() + File.separator + childPath + File.separator + merId;
                            File dir = new File(destDirName);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            out = new FileOutputStream(destDirName + File.separator + fileName);
                            out.write(file.getBytes());
                            out.flush();

                            Thumbnails.of(destDirName + File.separator + fileName).scale(1f)
                                    .outputQuality(0.01f).toFile(destDirName + File.separator + fileName);

                            fileNames.add(childPath+"/"+merId+"/"+fileName);

                            File filePath = new File(destDirName + "/" + fileName);
                            HuaWeiYunObs.putObject(CommonSysConst.getSysConfig().getObs_bucket_name(),
                                    childPath + "/" + merId + "/" + fileName, filePath);

                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                        }
                    }
                }
            }
            return ResponseMsgUtil.success(fileNames);

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

    @RequestMapping(value="/uploadBase64File",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "文件上传")
    public ResponseData uploadBase64File(@RequestParam(value = "merId" , required = true) Long merId,
                                         @RequestParam(value = "base64File" , required = true) String base64File) {
        try {
            String fileName = System.currentTimeMillis()+"";
            String childPath = "merchant/" + merId;
            String path =  sysConfig.getFileUrl()+"/"+childPath ;
            Map<String, Object> map = ImageUtils.generateImage(base64File, path, fileName);

            File filePath = new File(path +"/"+ map.get("fileName"));
            HuaWeiYunObs.putObject(CommonSysConst.getSysConfig().getObs_bucket_name(), childPath + "/" + map.get("fileName"), filePath);
            return ResponseMsgUtil.success(childPath + "/" + map.get("fileName"));

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


}
