package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.bweb.excelListener.ImportStoreListener;
import com.bweb.model.ImportStoreModel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConst;
import com.hai.entity.BsCompany;
import com.hai.entity.HighMerchant;
import com.hai.entity.HighMerchantStore;
import com.hai.entity.SecRegion;
import com.hai.enum_type.MerchantStoreSourceType;
import com.hai.model.*;
import com.hai.service.*;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/9 20:58
 */
@Controller
@RequestMapping(value = "/highMerchantStore")
@Api(value = "商户门店接口")
public class HighMerchantStoreController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private CommonService commonService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private HighMerchantService highMerchantService;

    @Resource
    private SecUserService secUserService;

    @RequestMapping(value="/insertMerchantStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加商户门店")
    public ResponseData insertMerchantStore(@RequestBody HighMerchantStoreModel highMerchantStore, HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getMerchant() == null) {
                log.error("HighMerchantController -> insertMerchantStore() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            if (highMerchantStore.getRegionId() == null
                    || StringUtils.isBlank(highMerchantStore.getStoreName())
                    || StringUtils.isBlank(highMerchantStore.getContactName())
                    || StringUtils.isBlank(highMerchantStore.getTelephone())
                    || StringUtils.isBlank(highMerchantStore.getAddress())
                    || StringUtils.isBlank(highMerchantStore.getLatitude())
                    || StringUtils.isBlank(highMerchantStore.getLongitude())
                    || highMerchantStore.getPrestoreType() == null
            ) {
                log.error("HighMerchantStoreController -> insertMerchantStore() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 校验商户
            HighMerchant merchant = highMerchantService.getMerchantById(userInfoModel.getMerchant().getId());
            if (merchant == null) {
                log.error("HighMerchantStoreController -> insertMerchantStore() error!","未找到商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }
            BsCompany company = bsCompanyService.getCompanyById(merchant.getCompanyId());
            if (company == null) {
                log.error("HighMerchantStoreController -> insertMerchantStore() error!","未找到分公司");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }

            Map<String, SecRegion> regionMap = commonService.getParentInfoByRegionId(highMerchantStore.getRegionId());

            if (highMerchantStore.getType() != null && highMerchantStore.getType().equals(1)) {
                highMerchantStore.setRegionId(Long.parseLong(company.getRegionId()));
                highMerchantStore.setRegionName(commonService.getRegionName(Long.parseLong(company.getRegionId())));
            } else {
                // 如果是重庆市的区县，使用重庆市的区域代码
                if (regionMap.get("region").getRegionId().intValue() == 500100) {
                    highMerchantStore.setRegionId(regionMap.get("region").getParentId());
                    highMerchantStore.setRegionName(regionMap.get("region").getRegionName());
                } else {
                    highMerchantStore.setRegionId(regionMap.get("region").getRegionId());
                    highMerchantStore.setRegionName(regionMap.get("region").getRegionName());
                }
            }

            if (highMerchantStore.getBrandId() != null) {
                highMerchantStore.setBrandName(commonService.getDictionaryCodeName("MERCHANT_STORE_BRANCH", highMerchantStore.getBrandId().toString()));
            }

            // 加油站没有设置图片的情况，默认设置
            if (highMerchantStore.getType().equals(1) && StringUtils.isBlank(highMerchantStore.getStoreLogo())) {
                highMerchantStore.setStoreLogo(CommonSysConst.getSysConfig().getGasDefaultOilStationImg());
            }
            highMerchantStore.setCreateTime(new Date());
            highMerchantStore.setUpdateTime(new Date());
            highMerchantStore.setStatus(1); // 状态：0：删除，1：正常
            highMerchantStore.setCompanyId(merchant.getCompanyId());
            highMerchantStore.setMerchantId(merchant.getId());
            highMerchantStore.setOperatorId(userInfoModel.getSecUser().getId());
            highMerchantStore.setOperatorName(userInfoModel.getSecUser().getUserName());
            highMerchantStore.setSourceType(MerchantStoreSourceType.type1.getNumber());
            highMerchantStoreService.insertMerchantStore(highMerchantStore);

            return ResponseMsgUtil.success(highMerchantStore);
        } catch (Exception e) {
            log.error("HighMerchantStoreController -> insertMerchantStore() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/importMerchantStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导入商户门店")
    public ResponseData importMerchantStore( @RequestParam(value = "file" , required = true) MultipartFile files,
                                            HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getMerchant() == null) {
                log.error("HighMerchantController -> insertMerchantStore() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            // 查找商户
            HighMerchantModel merchant = highMerchantService.getMerchantById(userInfoModel.getMerchant().getId());
            if(merchant == null) {
                log.error("HighMerchantStoreController -> importMerchantStore() error!","未找到卡卷信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }

            ImportStoreListener importStoreListener = new ImportStoreListener();
            importStoreListener.initData(merchant,userInfoModel, highMerchantStoreService, commonService);
            EasyExcel.read(files.getInputStream(), ImportStoreModel.class, importStoreListener).sheet().doRead();

            Map<String, Object> map = new HashMap<>();
            map.put("errorData", importStoreListener.getErrorData());
            map.put("errorTotal", importStoreListener.getErrorData().size());

            return ResponseMsgUtil.success(map);
        } catch (Exception e) {
            log.error("HighMerchantStoreController -> insertMerchantStore() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/updateMerchantStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改商户门店")
    public ResponseData updateMerchantStore(@RequestBody HighMerchantStoreModel highMerchantStore, HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getMerchant() == null) {
                log.error("HighMerchantController -> insertMerchantStore() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            if (highMerchantStore.getRegionId() == null
                    || highMerchantStore.getId() == null
                    || StringUtils.isBlank(highMerchantStore.getStoreName())
                    || StringUtils.isBlank(highMerchantStore.getContactName())
                    || StringUtils.isBlank(highMerchantStore.getTelephone())
                    || StringUtils.isBlank(highMerchantStore.getAddress())
                    || StringUtils.isBlank(highMerchantStore.getLatitude())
                    || StringUtils.isBlank(highMerchantStore.getLongitude())
            ) {
                log.error("HighMerchantStoreController -> insertMerchantStore() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询门店
            HighMerchantStoreModel store = highMerchantStoreService.getMerchantStoreById(highMerchantStore.getId());
            if (store == null) {
                log.error("BsStudentController --> addStudent() error!", "未找到门店信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店信息");
            }
            BsCompany company = bsCompanyService.getCompanyById(store.getCompanyId());
            if (company == null) {
                log.error("HighMerchantStoreController -> insertMerchantStore() error!","未找到分公司");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }

            Map<String, SecRegion> regionMap = commonService.getParentInfoByRegionId(highMerchantStore.getRegionId());
            if (highMerchantStore.getType() != null && highMerchantStore.getType().equals(1)) {
                highMerchantStore.setRegionId(Long.parseLong(company.getRegionId()));
                highMerchantStore.setRegionName(commonService.getRegionName(Long.parseLong(company.getRegionId())));
            } else {
                // 如果是重庆市的区县，使用重庆市的区域代码
                if (regionMap.get("region").getRegionId().intValue() == 500100) {
                    highMerchantStore.setRegionId(regionMap.get("region").getParentId());
                    highMerchantStore.setRegionName(regionMap.get("region").getRegionName());
                } else {
                    highMerchantStore.setRegionId(regionMap.get("region").getRegionId());
                    highMerchantStore.setRegionName(regionMap.get("region").getRegionName());
                }
            }

            if (highMerchantStore.getBrandId() != null) {
                store.setBrandId(highMerchantStore.getBrandId());
                store.setBrandName(commonService.getDictionaryCodeName("MERCHANT_STORE_BRANCH", highMerchantStore.getBrandId().toString()));
            }
            // 加油站没有设置图片的情况，默认设置
            if (highMerchantStore.getType().equals(1) && StringUtils.isBlank(highMerchantStore.getStoreLogo())) {
                store.setStoreLogo(CommonSysConst.getSysConfig().getGasDefaultOilStationImg());
            }
            store.setType(highMerchantStore.getType());
            store.setStoreLogo(highMerchantStore.getStoreLogo());
            store.setStoreName(highMerchantStore.getStoreName());
            store.setContactName(highMerchantStore.getContactName());
            store.setTelephone(highMerchantStore.getTelephone());
            store.setAddress(highMerchantStore.getAddress());
            store.setLatitude(highMerchantStore.getLatitude());
            store.setLongitude(highMerchantStore.getLongitude());
            store.setDeviceSn(highMerchantStore.getDeviceSn());
            store.setDeviceKey(highMerchantStore.getDeviceKey());
            store.setDeviceName(highMerchantStore.getDeviceName());

            store.setUpdateTime(new Date());
            store.setOperatorId(userInfoModel.getSecUser().getId());
            store.setOperatorName(userInfoModel.getSecUser().getUserName());
            highMerchantStoreService.updateMerchantStore(store);

            return ResponseMsgUtil.success(store);
        } catch (Exception e) {
            log.error("HighMerchantStoreController -> editMerchantStore() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/deleteMerchantStore",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除商户门店")
    public ResponseData deleteMerchantStore(@RequestParam(name = "id", required = true) Long id) {
        try {
            // 商户门店
            HighMerchantStore merchantStore = highMerchantStoreService.getMerchantStoreById(id);
            if(merchantStore == null) {
                log.error("HighMerchantStoreController -> deleteMerchantStore() error!","未找到商户门店");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_STORE_NOF_FOUND, "");
            }
            highMerchantStoreService.deleteMerchantStore(id);

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

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

    @RequestMapping(value="/getMerchantStoreById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询商户门店")
    public ResponseData getMerchantStoreById(@RequestParam(name = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(highMerchantStoreService.getMerchantStoreById(id));

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

    @RequestMapping(value="/getStoreListByCompany",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据公司 查询商户门店列表")
    public ResponseData getStoreListByCompany(@RequestParam(name = "merchantId", required = false) Long merchantId,
                                              @RequestParam(name = "telephone", required = false) String telephone,
                                              @RequestParam(name = "storeName", required = false) String storeName,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                             HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighMerchantStoreController -> getStoreListByCompany() error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("companyId", userInfoModel.getBsCompany().getId());
            map.put("merchantId", merchantId);
            map.put("telephone", telephone);
            map.put("storeName", storeName);

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

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

    @RequestMapping(value="/getStoreListByMerchant",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据商户 查询门店列表")
    public ResponseData getStoreListByMerchant(@RequestParam(name = "telephone", required = false) String telephone,
                                               @RequestParam(name = "storeName", required = false) String storeName,
                                               @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                               @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                               HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getMerchant() == null) {
                log.error("HighMerchantStoreController -> getStoreListByMerchant() error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("merchantId", userInfoModel.getMerchant().getId());
            map.put("telephone", telephone);
            map.put("storeName", storeName);

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

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


}
