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.BsIndustry;
import com.hfkj.entity.BsStore;
import com.hfkj.entity.SecRegion;
import com.hfkj.model.ResponseData;
import com.hfkj.model.StoreModel;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.*;
import com.hfkj.sysenum.SecUserTypeEnum;
import com.hfkj.sysenum.StoreStatusEnum;
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.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private BsStoreService storeService;

    @Resource
    private BsStoreIndustryService storeIndustryService;

    @Resource
    private BsStoreRegionService storeRegionService;

    @Resource
    private BsIndustryService industryService;

    @Resource
    private CommonService commonService;

    @RequestMapping(value="/configStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置门店")
    public ResponseData configStore(@RequestBody StoreModel storeModel) {
        try {

            if (storeModel == null
                || storeModel.getAccount() == null
                || StringUtils.isBlank(storeModel.getAccount().getLoginName())
                || storeModel.getMerId() == null
                || StringUtils.isBlank(storeModel.getName())
                || StringUtils.isBlank(storeModel.getTelephone())
                || StringUtils.isBlank(storeModel.getDoorHeadImg())
                || StringUtils.isBlank(storeModel.getCashRegisterImg())
                || StringUtils.isBlank(storeModel.getInternalImg())
                || 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())
                || storeModel.getStoreIndustry() == null
                || storeModel.getStoreIndustry().getChildId() == null
                || storeModel.getStoreRegion() == null
                || StringUtils.isBlank(storeModel.getStoreRegion().getAddress())
                || storeModel.getStoreRegion().getAreaCode() == null
            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 行业
            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());

            storeService.configStore(storeModel);

            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);
            return ResponseMsgUtil.success(new PageInfo<>(storeService.getStoreList(param)));

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

    @RequestMapping(value="/getStoreList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询门店列表")
    public ResponseData getStoreList(@RequestParam(value = "companyId" , required = false) Long companyId,
                                     @RequestParam(value = "agentId" , required = false) Long agentId,
                                     @RequestParam(value = "merId" , required = false) Long merId,
                                     @RequestParam(value = "salesmanId" , required = false) Long salesmanId,
                                     @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 {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {

            }
            Map<String, Object> param = new HashMap<>();
            if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type0.getNumber())) {
                param.put("companyId", companyId);
                param.put("agentId", agentId);
                param.put("merId", merId);
                param.put("salesmanId", salesmanId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type1.getNumber())) {
                param.put("companyId", userInfoModel.getBsCompany().getId());
                param.put("agentId", agentId);
                param.put("merId", merId);
                param.put("salesmanId", salesmanId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type2.getNumber())) {
                param.put("agentId", userInfoModel.getAgent().getId());
                param.put("merId", merId);
                param.put("salesmanId", salesmanId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type3.getNumber())) {
                param.put("salesmanId", userInfoModel.getSalesman().getId());
                param.put("merId", merId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type4.getNumber())) {
                param.put("merId", userInfoModel.getMer().getId());

            } else {
                log.error("getStoreList error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            param.put("name", name);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<StoreModel> pageInfo = new PageInfo<>(storeService.getStoreList(param));
            for (StoreModel store : pageInfo.getList()) {
                store.setStoreIndustry(storeIndustryService.getIndustryByStoreId(store.getId()));
                store.setStoreRegion(storeRegionService.getRegionByStoreId(store.getId()));
            }
            return ResponseMsgUtil.success(pageInfo);

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

}
