package com.bweb.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.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.service.*;
import com.hfkj.service.agent.BsAgentMerService;
import com.hfkj.service.gas.BsGasOilGunNoService;
import com.hfkj.service.gas.BsGasOilPriceService;
import com.hfkj.service.merchant.BsMerchantChainBrandService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.merchant.MerchantStatusEnum;
import com.hfkj.sysenum.merchant.MerchantChainBrandSettleTypeEnum;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/merchant")
@Api(value = "商户管理")
public class BsMerchantController {
    private static Logger log = LoggerFactory.getLogger(BsMerchantController.class);

    @Resource
    private BsMerchantService merchantService;
    @Resource
    private BsGasOilPriceService gasOilPriceService;
    @Resource
    private BsAgentMerService agentMerService;
    @Resource
    private BsGasOilGunNoService gasOilGunNoService;
    @Resource
    private BsMerchantChainBrandService merchantChainBrandService;
    @Resource
    private CommonService commonService;

    @RequestMapping(value = "/editMerchant", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑商户")
    public ResponseData editMerchant(@RequestBody BsMerchant body) {
        try {
            if (body == null
                    || body.getAreaCode() == null
                    || StringUtils.isBlank(body.getMerLogo())
                    || StringUtils.isBlank(body.getMerName())
                    || StringUtils.isBlank(body.getContactsName())
                    || StringUtils.isBlank(body.getContactsTel())
                    || StringUtils.isBlank(body.getCustomerServiceTel())
                    || StringUtils.isBlank(body.getAddress())
                    || StringUtils.isBlank(body.getLongitude())
                    || StringUtils.isBlank(body.getLatitude())
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsMerchant merchant = null;
            if (StringUtils.isNotBlank(body.getMerNo())) {
                // 查询商户
                merchant = merchantService.getMerchant(body.getMerNo());
                if (merchant == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "未知商户");
                }
            } else {
                merchant = new BsMerchant();
                merchant.setStatus(MerchantStatusEnum.status1.getNumber());
            }

            if (body.getOilPriceZoneId() != null) {
                // 查询价区
                SecDictionary oilPriceZone = commonService.mappingSysCode("OIL_PRICE_ZONE", body.getOilPriceZoneId().toString());
                if (oilPriceZone == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的价区");
                }
                merchant.setOilPriceZoneId(Integer.valueOf(oilPriceZone.getCodeValue()));
                merchant.setOilPriceZoneName(oilPriceZone.getCodeName());
            }
            // 查询区域
            SecRegion areaRegion = commonService.getRegionsById(body.getAreaCode());
            if (areaRegion == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知地区");
            }
            // 查询市
            SecRegion cityRegion = commonService.getRegionsById(areaRegion.getParentId());
            if (cityRegion == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的市级");
            }
            // 查询省
            SecRegion provinceRegion = commonService.getRegionsById(cityRegion.getParentId());
            if (provinceRegion == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的省级");
            }
            // 连锁品牌
            if (body.getChainBrandId() != null) {
                // 查询连锁品牌
                BsMerchantChainBrand chainBrand = merchantChainBrandService.getDetail(body.getChainBrandId());
                if (chainBrand == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "连锁品牌未配置");
                }
                merchant.setChainBrandId(chainBrand.getId());
                merchant.setChainBrandName(chainBrand.getName());
                // 连锁品牌结算类型
                MerchantChainBrandSettleTypeEnum data = MerchantChainBrandSettleTypeEnum.getDataByType(body.getChainBrandSettleType());
                if (data == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知连锁结算类型");
                }
                merchant.setChainBrandSettleType(data.getNumber());
            }

            merchant.setProvinceCode(provinceRegion.getRegionId());
            merchant.setProvinceName(provinceRegion.getRegionName());
            merchant.setCityCode(cityRegion.getRegionId());
            merchant.setCityName(cityRegion.getRegionName());
            merchant.setAreaCode(areaRegion.getRegionId());
            merchant.setAreaName(areaRegion.getRegionName());
            merchant.setMerLogo(body.getMerLogo());
            merchant.setMerName(body.getMerName());
            merchant.setContactsName(body.getContactsName());
            merchant.setContactsTel(body.getContactsTel());
            merchant.setCustomerServiceTel(body.getCustomerServiceTel());
            merchant.setAddress(body.getAddress());
            merchant.setLatitude(body.getLatitude());
            merchant.setLongitude(body.getLongitude());
            merchant.setMerLabel(body.getMerLabel());

            if (merchant.getMerNo() == null) {
                merchant.setSourceType(MerchantSourceTypeEnum.type1.getNumber());
                merchantService.createMerchant(merchant);
            } else {
                merchantService.updateMerchant(merchant);
                // 通知代理
                agentMerService.agentNotify(null, merchant.getMerNo());
            }

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

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

    @RequestMapping(value = "/restoreMer", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "恢复商户")
    public ResponseData restoreMer(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("merNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            merchantService.updateMerStatus(body.getString("merNo"), MerchantStatusEnum.status1);

            // 通知代理
            agentMerService.agentNotify(null, body.getString("merNo"));

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsMerchantController --> restoreMer() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/listShow", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "列表展示")
    public ResponseData listShow(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("merNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(body.getString("merNo"));
            if (merchant == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }
            merchant.setListShow(!merchant.getListShow());
            merchantService.updateMerchant(merchant);

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

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

    @RequestMapping(value = "/disableMer", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用商户")
    public ResponseData disableMer(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("merNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            merchantService.updateMerStatus(body.getString("merNo"), MerchantStatusEnum.status2);

            // 通知代理
            agentMerService.agentNotify(null,body.getString("merNo"));

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsMerchantController --> disableMer() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/resetMerPwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "重置商户密码")
    public ResponseData resetMerPwd(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("merNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            merchantService.resetMerPwd(body.getString("merNo"));

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsMerchantController --> resetMerPwd() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/queryMerDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户详情")
    public ResponseData queryMerDetail(@RequestParam(value = "merNo", required = true) String merNo) {
        try {
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(merNo);
            if (merchant == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户号");
            }

            Map<String,Object> param = new HashMap<>();
            param.put("merNo", merNo);
            // 查询油品
            List<BsGasOilPrice> priceList = gasOilPriceService.getGasOilPriceList(param);
            // 查询枪号
            List<BsGasOilGunNo> oilGunNoList = gasOilGunNoService.getOilGunNoList(merNo);

            // 获取枪号
            List<Object> oilsList = new ArrayList<>();
            for (BsGasOilPrice oilPrice : priceList) {
                JSONObject oil = JSONObject.parseObject(JSONObject.toJSONString(oilPrice));
                // 获取枪号
                oil.put("gunNoList", oilGunNoList.stream().filter(o -> o.getOilNo().equals(oilPrice.getOilNo())).collect(Collectors.toList()));
                oilsList.add(oil);
            }

            Map<String,Object> map = new HashMap<>();
            map.put("merchant", merchant);
            map.put("oils", oilsList);
            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/queryMerList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户列表")
    public ResponseData queryMerList(@RequestParam(value = "sourceType", required = false) Integer sourceType,
                                     @RequestParam(value = "merNo", required = false) String merNo,
                                     @RequestParam(value = "merName", required = false) String merName,
                                     @RequestParam(value = "provinceCode", required = false) String provinceCode,
                                     @RequestParam(value = "chainBrandId", required = false) Long chainBrandId,
                                     @RequestParam(value = "cityCode", required = false) String cityCode,
                                     @RequestParam(value = "areaCode", required = false) String areaCode,
                                     @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> map = new HashMap<>();
            map.put("sourceType", sourceType);
            map.put("merNo", merNo);
            map.put("merName", merName);
            map.put("provinceCode", provinceCode);
            map.put("chainBrandId", chainBrandId);
            map.put("cityCode", cityCode);
            map.put("areaCode", areaCode);
            map.put("status", status);

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

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


}
