package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.StoreModel;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsIndustryService;
import com.hfkj.service.BsStoreService;
import com.hfkj.service.BsStoreSettleAcctService;
import com.hfkj.service.CommonService;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.*;

@Controller
@Api(value = "门店管理")
@RequestMapping(value = "/store")
public class BsStoreController {

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

    @Resource
    private BsStoreService storeService;

    @Resource
    private BsStoreSettleAcctService storeSettleAcctService;

    @Resource
    private BsIndustryService industryService;

    @Resource
    private CommonService commonService;

    @Resource
    private UserCenter userCenter;

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

            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", userModel.getStore().getId());

            // 今日交易额
            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="/configStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置门店")
    public ResponseData configStore(@RequestBody StoreModel storeModel) {
        try {
            if (storeModel == null
                || storeModel.getMerId() == null
                || StringUtils.isBlank(storeModel.getDutyPeopleName())
                || StringUtils.isBlank(storeModel.getDutyPeoplePhone())
                || StringUtils.isBlank(storeModel.getDutyPeopleEmail())
                || StringUtils.isBlank(storeModel.getName())
                || StringUtils.isBlank(storeModel.getTelephone())
                || StringUtils.isBlank(storeModel.getDoorHeadImg())
                || StringUtils.isBlank(storeModel.getCashRegisterImg())
                || StringUtils.isBlank(storeModel.getInternalImg())
                || storeModel.getAloneSettle() == null
                || storeModel.getStoreIndustry() == null
                || storeModel.getStoreIndustry().getChildId() == null
                || 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, "");
            }

            if (storeModel.getId() != null) {
                // 查询门店
                BsStore store = storeService.getStoreById(storeModel.getId());
                if (store == null) {
                    log.error("configStore error!","未找到门店");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店");
                }
                storeModel.setId(store.getId());
                storeModel.setStoreNo(store.getStoreNo());
                storeModel.setStatus(store.getStatus());
                storeModel.setCreateTime(store.getCreateTime());
            }

            // 是否单独结算，单独结算需要上传营业执照、法人身份证、结算资料
            if (storeModel.getAloneSettle().equals(true)) {
                if (StringUtils.isBlank(storeModel.getBlisUrl())
                    || StringUtils.isBlank(storeModel.getBlisName())
                    || StringUtils.isBlank(storeModel.getBlisNo())
                    || StringUtils.isBlank(storeModel.getBlisRegAddress())
                    || storeModel.getBlisPeriodType() == null
                    || StringUtils.isBlank(storeModel.getBlisPeriodStart())
                    || StringUtils.isBlank(storeModel.getBlisPeriodEnd())
                    || StringUtils.isBlank(storeModel.getLarName())
                    || StringUtils.isBlank(storeModel.getLarIdCard())
                    || StringUtils.isBlank(storeModel.getLarIdCardPortraitImg())
                    || StringUtils.isBlank(storeModel.getLarIdCardNationalEmblemImg())
                    || storeModel.getLarIdCardPeriodType() == null
                    || StringUtils.isBlank(storeModel.getLarIdCardAddress())
                    || StringUtils.isBlank(storeModel.getLarIdCardPeriodStart())
                    || StringUtils.isBlank(storeModel.getLarIdCardPeriodEnd())

                    || storeModel.getStoreSettleAcct() == null
                    || storeModel.getStoreSettleAcct().getSettleType() == null
                    || StringUtils.isBlank(storeModel.getStoreSettleAcct().getBankCardNo())
                    || StringUtils.isBlank(storeModel.getStoreSettleAcct().getBankCardHolder())
                    || storeModel.getStoreSettleAcct().getOpenningBankAreaCode() == null
                ) {
                    log.error("configStore error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }

                SecRegion openningBankArea = commonService.getRegionsById(storeModel.getStoreSettleAcct().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, "未知的的开户地区");
                }
                storeModel.getStoreSettleAcct().setOpenningBankAreaName(openningBankArea.getRegionName());
                storeModel.getStoreSettleAcct().setOpenningBankCityCode(openningBankCity.getRegionId());
                storeModel.getStoreSettleAcct().setOpenningBankCityName(openningBankCity.getRegionName());
                storeModel.getStoreSettleAcct().setOpenningBankProvinceCode(openningBankProvince.getRegionId());
                storeModel.getStoreSettleAcct().setOpenningBankProvinceName(openningBankProvince.getRegionName());

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

                // 查询开户行
                JSONObject cardBin = LaKaLaConfig.queryCardBin(storeModel.getStoreSettleAcct().getBankCardNo());
                if (cardBin == null) {
                    log.error("configMerBasis error!","未找到银行卡bin信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到银行卡bin信息");
                }
                if (StringUtils.isBlank(cardBin.getString("bankCode"))
                        || StringUtils.isBlank(cardBin.getString("clearingBankCode"))) {
                    log.error("configMerBasis error!","未找到银行卡bin信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请填写正确银行卡卡号");
                }

                storeModel.getStoreSettleAcct().setOpenningBankName(cardBin.getString("bankName"));
                storeModel.getStoreSettleAcct().setOpenningBankCode(cardBin.getString("bankCode"));
                storeModel.getStoreSettleAcct().setClearingBankCode(cardBin.getString("clearingBankCode"));
                storeModel.setStatus(StoreStatusEnum.status3.getNumber());
            } else {
                storeModel.setStatus(StoreStatusEnum.status2.getNumber());
            }
            // 行业
            Map<String, BsIndustry> industry = industryService.getChildIndustry(storeModel.getStoreIndustry().getChildId());
            if (industry == null) {
                log.error("configMerBasis error!","未知的行业");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的行业");
            }
            storeModel.getStoreIndustry().setChildId(MapUtils.getObject(industry, "child").getId());
            storeModel.getStoreIndustry().setChildName(MapUtils.getObject(industry, "child").getName());
            storeModel.getStoreIndustry().setParentId(MapUtils.getObject(industry, "parent").getId());
            storeModel.getStoreIndustry().setParentName(MapUtils.getObject(industry, "parent").getName());

            // 区域
            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.setCreateType(StoreCreateTypeEnum.type2.getNumber());
            storeModel.setStoreType(storeModel.getBlisName().indexOf("公司") != -1? MerTypeEnum.status2.getNumber(): MerTypeEnum.status1.getNumber());
            storeService.configStore(storeModel);

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

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

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

            if (storeSettleAcct.getStoreId() == null
                    || storeSettleAcct.getSettleType() == null
                    || StringUtils.isBlank(storeSettleAcct.getBankCardNo())
                    || StringUtils.isBlank(storeSettleAcct.getBankCardHolder())
                    // || StringUtils.isBlank(merSettleAcct.getOpenningBankCode())
                    // || StringUtils.isBlank(merSettleAcct.getOpenningBankName())
                    // || StringUtils.isBlank(merSettleAcct.getElectronicPact())
                    || storeSettleAcct.getOpenningBankAreaCode() == null
                    // || StringUtils.isBlank(merSettleAcct.getClearingBankCode())
/*                    || storeSettleAcct.getMerRateList() == null
                    || storeSettleAcct.getMerRateList().size() == 0*/
            ) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 对公结算,需要上传开户证明
/*            if (merSettleAcct.getSettleType().equals(MerSettleType.status1.getNumber())
                    && StringUtils.isBlank(merSettleAcct.getOpenningBankLicenseUrl())) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }*/
/*
            if ((storeSettleAcct.getSettleType().equals(MerSettleType.status2.getNumber())
                    || merSettleAcct.getSettleType().equals(MerSettleType.status3.getNumber()))
                    && StringUtils.isBlank(merSettleAcct.getBankCardImg())) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要上传银行卡照片");
            }*/

            SecRegion openningBankArea = commonService.getRegionsById(storeSettleAcct.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, "未知的的开户地区");
            }
            storeSettleAcct.setOpenningBankAreaName(openningBankArea.getRegionName());
            storeSettleAcct.setOpenningBankCityCode(openningBankCity.getRegionId());
            storeSettleAcct.setOpenningBankCityName(openningBankCity.getRegionName());
            storeSettleAcct.setOpenningBankProvinceCode(openningBankProvince.getRegionId());
            storeSettleAcct.setOpenningBankProvinceName(openningBankProvince.getRegionName());

            // 查询商户详情
            BsStore store = storeService.getStoreById(storeSettleAcct.getStoreId());
            if (store == null) {
                log.error("configMerBasis error!","未知门店");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知门店");
            }
            if ((!store.getStatus().equals(StoreStatusEnum.status2.getNumber()))) {
                log.error("configMerBasis error!","状态错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }
            // 对私非法人结算
            if (storeSettleAcct.getSettleType().equals(MerSettleType.status3.getNumber()) &&
                    (StringUtils.isBlank(storeSettleAcct.getSettleIdCardPortraitImg())
                            || StringUtils.isBlank(storeSettleAcct.getCommissionImg())
                            || StringUtils.isBlank(storeSettleAcct.getSettleIdCardNationalEmblemImg())
                            || StringUtils.isBlank(storeSettleAcct.getSettleIdCardName())
                            || StringUtils.isBlank(storeSettleAcct.getSettleIdCardNo())
                            || StringUtils.isBlank(storeSettleAcct.getSettleIdCardPeriodStart())
                            || StringUtils.isBlank(storeSettleAcct.getSettleIdCardPeriodEnd())
                            || storeSettleAcct.getSettleIdPeriodType() == null)) {
                log.error("configMerBasis error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要结算人身份证信息");
            } else {

                // 对公结算、对私法人结算
                storeSettleAcct.setSettleIdCardName(store.getLarName());
                storeSettleAcct.setSettleIdCardNo(store.getLarIdCard());
                storeSettleAcct.setSettleIdCardPortraitImg(store.getLarIdCardPortraitImg());
                storeSettleAcct.setSettleIdCardNationalEmblemImg(store.getLarIdCardNationalEmblemImg());
                storeSettleAcct.setSettleIdPeriodType(store.getBlisPeriodType());
                storeSettleAcct.setSettleIdCardPeriodStart(store.getLarIdCardPeriodStart());
                storeSettleAcct.setSettleIdCardPeriodEnd(store.getLarIdCardPeriodEnd());
            }

            // 查询开户行
            JSONObject cardBin = LaKaLaConfig.queryCardBin(storeSettleAcct.getBankCardNo());
            if (cardBin == null) {
                log.error("configMerBasis error!","未找到银行卡bin信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到银行卡bin信息");
            }
            if (StringUtils.isBlank(cardBin.getString("bankCode"))
                    || StringUtils.isBlank(cardBin.getString("clearingBankCode"))) {
                log.error("configMerBasis error!","未找到银行卡bin信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请填写正确银行卡卡号");
            }

            storeSettleAcct.setOpenningBankName(cardBin.getString("bankName"));
            storeSettleAcct.setOpenningBankCode(cardBin.getString("bankCode"));
            storeSettleAcct.setClearingBankCode(cardBin.getString("clearingBankCode"));

            return ResponseMsgUtil.success("已提交审核");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/disabledStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用门店")
    public ResponseData disabledStore(@RequestBody JSONObject body) {
        try {

            if (body == null
                    || body.getLong("storeId") == null
                    || body.getBoolean("disable") == null
            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询门店
            BsStore store = storeService.getStoreById(body.getLong("storeId"));
            if (store == null) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            store.setStatus(body.getBoolean("disable") == true ? StoreStatusEnum.status2.getNumber() : StoreStatusEnum.status1.getNumber());
            storeService.editStore(store);

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

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

    @RequestMapping(value="/getStoreDetailById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询门店详情")
    public ResponseData getStoreDetailById(@RequestParam(value = "storeId" , required = true) Long storeId) {
        try {
            return ResponseMsgUtil.success(storeService.getStoreDetail(storeId));

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

    @RequestMapping(value="/getStoreListByMer",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "商户查询门店列表")
    public ResponseData getStoreListByMer(@RequestParam(value = "merId" , required = true) Long merId,
                                          @RequestParam(value = "name" , required = false) String name,
                                          @RequestParam(value = "status" , required = false) Integer status,
                                          @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                          @RequestParam(value = "pageSize" , required = true) Integer pageSize
    ) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("merId", merId);
            param.put("name", name);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<StoreModel> pageInfo = new PageInfo<>(storeService.getStoreList(param));
            for (int i = 0; i < pageInfo.getList().size(); i++) {
                pageInfo.getList().set(i,storeService.getStoreDetail(pageInfo.getList().get(i).getId()));
            }
            return ResponseMsgUtil.success(pageInfo);

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

}
