package com.gic.haoban.manage.web.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.dict.api.dto.CityDTO;
import com.gic.dict.api.dto.CountyDTO;
import com.gic.dict.api.dto.ProvinceDTO;
import com.gic.dict.api.service.ManagerDictService;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.dto.StorePhotoDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.data.api.dto.HaobanDataDTO;
import com.gic.haoban.data.api.service.HaobanDataApiService;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.enums.StoreFieldEnum;
import com.gic.haoban.manage.api.service.*;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.StaffStoreVO;
import com.gic.haoban.manage.web.vo.StoreDetailVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class StoreController extends WebBaseController {
    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(StoreController.class);

    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StaffDepartmentRelatedApiService staffDepartmentRelatedApiService;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private HaobanDataApiService haobanDataApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private AuditApiService auditApiService;
    @Autowired
    private AuditSettingApiService auditSettingApiService;
    @Autowired
    private ClerkMainStoreRelatedApiService clerkMainStoreRelatedApiService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private ManagerDictService managerDictService;

    /**
     * 好办小程序-绑定的门店列表
     * @param staffId
     * @param wxEnterpriseId
     * @param gicEnterpriseId
     * @return
     */
    @IgnoreLogin
    @RequestMapping("/store-list")
    public HaobanResponse storeList(String staffId, String wxEnterpriseId, String gicEnterpriseId) {
        if (StringUtils.isAnyBlank(staffId, wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<StaffStoreVO> list = new ArrayList<>();
        List<EnterpriseDetailDTO> enterpriseList = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isEmpty(enterpriseList)) {
            logger.info("没有关联任何商户：{}", wxEnterpriseId);
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        List<String> enterpriseIdList = enterpriseList.stream().filter(dto -> {
            String enterpriseId = dto.getEnterpriseId();
            return !this.wxEnterpriseApiService.haobanIsStop(enterpriseId);
        }).map(EnterpriseDetailDTO::getEnterpriseId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(enterpriseIdList)) {
            logger.info("没有关联任何商户或商户都已停用：{}", wxEnterpriseId);
            return resultResponse(HaoBanErrCode.ERR_1);
        }

        Map<String, EnterpriseDetailDTO> enterpriseTypeMap = enterpriseList.stream().collect(Collectors.toMap(dto -> dto.getEnterpriseId(), dto -> dto));
        List<StaffClerkRelationDTO> bindRelationList = staffClerkRelationApiService.listBindCodeByStaffId(enterpriseIdList, staffId);
        if (CollectionUtils.isEmpty(bindRelationList)) {
            logger.info("没有关联任何商户导购：{}", wxEnterpriseId);
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        logger.info("成员绑定导购数据={}", JSON.toJSONString(bindRelationList));
        for (StaffClerkRelationDTO staffClerkRelationDTO : bindRelationList) {
            String storeId = staffClerkRelationDTO.getStoreId();
            StoreDTO store = storeService.getStore(storeId);
            if (store == null) {
                continue;
            }
            String enterpriseId = store.getEnterpriseId();
            if (StringUtils.isNotBlank(gicEnterpriseId) && !gicEnterpriseId.equals(enterpriseId)) {
                logger.info("非当前商户,直接跳过={},{}", gicEnterpriseId, enterpriseId);
                continue;
            }
            //统一根据导购id查询
            ClerkDTO clerk = clerkService.getClerkByClerkId(staffClerkRelationDTO.getClerkId());
            if (clerk == null) {
                continue;
            }
            StaffDTO staffDTO = staffApiService.selectById(staffId);
            if (staffDTO == null) {
                continue;
            }
            WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
            if (wxEnterpriseDTO == null) {
                continue;
            }
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
            if (enterpriseDTO == null) {
                continue;
            }
            //主门店标志
            int mainStoreFlag = 0;
            EnterpriseDetailDTO enterpriseDetailDTO = enterpriseTypeMap.get(enterpriseId);
            staffDepartmentRelatedApiService.listByStaffId(staffId);
            StaffStoreVO vo = new StaffStoreVO();
            vo.setClerkCode(clerk.getClerkCode());
            vo.setWxEnterpriseType(enterpriseDetailDTO != null ? enterpriseDetailDTO.getWxEnterpriseType() : null);
            vo.setMemberOpenCardFlag(enterpriseDetailDTO != null ? enterpriseDetailDTO.getMemberOpenCardFlag() : null);
            vo.setClerkId(clerk.getClerkId());
            vo.setClerkType(clerk.getClerkType());
            vo.setEnterpriseId(enterpriseId);
            vo.setMainStoreFlag(mainStoreFlag);
            vo.setPhoneNumber(clerk.getPhoneNumber());
            vo.setStaffId(staffId);
            vo.setStoreId(clerk.getStoreId());
            vo.setStoreImg(store.getStoreImage());
            vo.setStoreName(store.getStoreName());
            vo.setWxEnterpriseId(wxEnterpriseId);
            vo.setClerkName(clerk.getClerkName());
            vo.setHeadImg(staffDTO.getHeadImg());
            vo.setBindFlag(1);
            vo.setEnterpriseName(enterpriseDTO.getBrandName());
            vo.setCorpName(wxEnterpriseDTO.getCorpName());
            vo.setEnableHaoban(clerk.getEnableHaoban());
            list.add(vo);
        }
        if (CollectionUtils.isEmpty(list)) {
            return resultResponse(HaoBanErrCode.ERR_1, list);
        }
        List<String> storeIdList = list.stream().map(dto -> dto.getStoreId()).collect(Collectors.toList());
        // 处理主门店
        if(StringUtils.isBlank(gicEnterpriseId)) {
            ClerkMainStoreRelatedDTO mainDTO = clerkMainStoreRelatedApiService.getWxEnterpriseIdAndStaffId(wxEnterpriseId, staffId, storeIdList);
            String mainStoreId = mainDTO == null ? "" : mainDTO.getStoreId();
            if (null != mainStoreId) {
                list.forEach(item -> {
                    if (item.getStoreId().equals(mainStoreId)) {
                        item.setMainStoreFlag(1);
                    }
                });
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, list);
    }

    //获取首页销售数据
    @RequestMapping("/sale-date")
    public HaobanResponse saleDate(String storeId, Integer clerkType, String clerkId, String enterpriseId,String wxEnterpriseId) {
        if (StringUtils.isAnyBlank(clerkId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<String> storeIds = new ArrayList<>();
        if (clerkType == 2) {
            List<String> haobanStoreIds = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
            if (!haobanStoreIds.contains("-1")) {
                storeIds.addAll(haobanStoreIds);
            }
        }else {
            storeIds.add(storeId);
        }
        String date = DateUtil.format(new Date(), "yyyy-MM-dd");
        if (clerkType == 0) {
            HaobanDataDTO HaobanDataDTO = haobanDataApiService.getSaleDataByDateByClerkId(enterpriseId, storeIds, clerkId, date);
            return resultResponse(HaoBanErrCode.ERR_1, HaobanDataDTO);
        }
        HaobanDataDTO HaobanDataDTO = haobanDataApiService.getSaleDataByDate(enterpriseId, storeIds, date);
        return resultResponse(HaoBanErrCode.ERR_1, HaobanDataDTO);
    }

    //获取省市区
    @IgnoreLogin
    @RequestMapping("/get-area-list")
    public HaobanResponse getArea(Integer type, String id) {
        if (type == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<ProvinceDTO> provinceList = new ArrayList<ProvinceDTO>();
        List<CityDTO> cityList = new ArrayList<CityDTO>();
        List<CountyDTO> countyList = new ArrayList<CountyDTO>();
        Map<String, ProvinceDTO> provinceMap = managerDictService.getProvincesMap();
        switch (type) {
            // 省
            case 1:
                for (String key : provinceMap.keySet()) {
                    provinceList.add(provinceMap.get(key));
                }
                return resultResponse(HaoBanErrCode.ERR_1, provinceList);
            // 市
            case 2:
                Map<String, CityDTO> tabCityMap = managerDictService.getCitysMap();
                Map<String, CityDTO> cityMap = new HashMap<String, CityDTO>();
                Set<Map.Entry<String, CityDTO>> citySet = tabCityMap.entrySet();
                for (Map.Entry<String, CityDTO> entry : citySet) {
                    if (entry.getValue().getProvinceId().equals(id)) {
                        cityMap.put(entry.getKey(), entry.getValue());
                    }
                }
                for (String key : cityMap.keySet()) {
                    cityList.add(cityMap.get(key));
                }
                return resultResponse(HaoBanErrCode.ERR_1, cityList);
            case 3:
                Map<String, CountyDTO> tabCountyMap = managerDictService.getCountysMap();
                Map<String, CountyDTO> countyMap = new HashMap<String, CountyDTO>();
                Set<Map.Entry<String, CountyDTO>> tabSet = tabCountyMap.entrySet();
                for (Map.Entry<String, CountyDTO> entry : tabSet) {
                    if (entry.getValue().getCityId().equals(id)) {
                        countyMap.put(entry.getKey(), entry.getValue());
                    }
                }
                for (String key : countyMap.keySet()) {
                    countyList.add(countyMap.get(key));
                }
                return resultResponse(HaoBanErrCode.ERR_1, countyList);
            default:
                return resultResponse(HaoBanErrCode.ERR_8);
        }
    }

    //修改门店数据
    @RequestMapping("/change-store-detail")
    public HaobanResponse changeStoreDetail(String wxEnterpriseId, String storeId, String staffId, String changeField, String oldValue, String newValue) {
        if (StringUtils.isAnyBlank(wxEnterpriseId, storeId, changeField)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        if (StringUtils.isBlank(oldValue)) {
            oldValue = "";
        }
        if (StringUtils.isBlank(newValue)) {
            newValue = "";
        }
        //增加判断是否是门店面积数字合法
        if (StoreFieldEnum.STORE_AREA.getValue().equals(changeField)) {
            try {
                Double.parseDouble(newValue);
            } catch (Exception e) {
                return resultResponse(HaoBanErrCode.ERR_400019);
            }
        }
        //门店图片修改判断
        if (StoreFieldEnum.STORE_IMAG.getValue().equals(changeField)) {
            //修改门店图片，不能为空
            if (StringUtils.isBlank(newValue)) {
                return resultResponse(HaoBanErrCode.ERR_400020);
            }
        }


        StoreDTO store = storeService.getStore(storeId);
        String enterpriseId = store.getEnterpriseId();
        logger.info("==================aaaa");
        AuditSettingDTO auditSettingDTO = auditSettingApiService.findSettingByWxEnterpriseId(wxEnterpriseId);
        logger.info("==================bbb");
        //默认开启审核
        int auditFlag = 1;
        if (auditSettingDTO != null) {
            auditFlag = auditSettingDTO.getAuditFlag();
        }
        logger.info("==================auditFlag={}", auditFlag);
        if (auditFlag == 1) {
            //要审核
            logger.info("==================11111");
            AuditDTO auditDTO = auditApiService.findByStoreIdAndChangeField(storeId, changeField);
            if (auditDTO == null) {
                //为空，可继续提交审核
                auditApiService.save(1, wxEnterpriseId, enterpriseId, staffId, storeId, changeField, oldValue, newValue);
            } else {
                return resultResponse(HaoBanErrCode.ERR_400018);
            }
        } else {
            logger.info("==================22222");
            auditApiService.editStoreInfo(storeId, changeField, oldValue, newValue);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    //获取门店详情
    @RequestMapping("/store-detail")
    public HaobanResponse storeDetail(String enterpriseId, String storeId, String wxEnterpriseId, String staffId) {
        if (StringUtils.isAnyBlank(storeId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }


        List<AuditDTO> list = auditApiService.listByStoreId(storeId);
        List<StorePhotoDTO> imgDTOList = storeService.getStoreImages(storeId);
        StoreDTO store = storeService.getStore(storeId);
        StoreDetailVO vo = EntityUtil.changeEntity(StoreDetailVO.class, store);
        if (CollectionUtil.isNotEmpty(imgDTOList)) {
            List<String> imgList = imgDTOList.stream().map(s -> s.getQcloudImageUrl()).collect(Collectors.toList());
            vo.setImgList(imgList);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        if (vo.getOpenTime() != null) {
            vo.setOpenTimeStr(sdf.format(vo.getOpenTime()));
        }
        if (vo.getCloseTime() != null) {
            vo.setCloseTimeStr(sdf.format(vo.getCloseTime()));
        }
        vo.setAreaId(store.getAreaId());
        vo.setStoreAddress(store.getFullArea() + " " + store.getStoreAddress());
        vo.setAuditDetail(list);

        AuditSettingDTO auditSettingDTO = auditSettingApiService.findSettingByWxEnterpriseId(wxEnterpriseId);
        vo.setAuditFlag(auditSettingDTO == null ? 0 : auditSettingDTO.getAuditFlag());
        if (vo.getStoreArea() == null || vo.getStoreArea() == -1) {
            vo.setStoreArea(-1d);
        }

        ClerkMainStoreRelatedDTO mainStore = clerkMainStoreRelatedApiService.getWxEnterpriseIdAndStaffId(wxEnterpriseId, staffId);
        if (mainStore != null && mainStore.getStoreId().equals(storeId)) {
            vo.setMainStoreFlag(1);
        } else {
            vo.setMainStoreFlag(0);
        }
        WxEnterpriseRelationDetailDTO enterpriseBindInfo = wxEnterpriseRelatedApiService.getEnterpriseBindInfo(wxEnterpriseId, enterpriseId);
        if (null != enterpriseBindInfo) {
            vo.setMemberOpenCardFlag(enterpriseBindInfo.getMemberOpenCardFlag());
        }
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }
}
