package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dao.order.StoreOrderDAO;
import com.cool.store.dao.store.StoreTypeDAO;
import com.cool.store.dto.OpenInfoDTO;
import com.cool.store.dto.Preparation.PreparationDTO;
import com.cool.store.dto.Preparation.ScheduleDTO;
import com.cool.store.dto.ShopNameAndCodeDTO;
import com.cool.store.dto.UserDTO;
import com.cool.store.entity.*;
import com.cool.store.entity.order.StoreOrderDO;
import com.cool.store.entity.store.StoreTypeDO;
import com.cool.store.enums.*;
import com.cool.store.enums.point.*;
import com.cool.store.enums.point.ShopStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.EnterpriseUserRoleMapper;
import com.cool.store.mapper.RegionMapper;
import com.cool.store.mapper.StoreMapper;
import com.cool.store.request.*;
import com.cool.store.response.BranchShopDetailResponse;
import com.cool.store.response.BranchShopResponse;
import com.cool.store.response.MiniShopsResponse;
import com.cool.store.response.ShopResponse;
import com.cool.store.service.*;
import com.cool.store.utils.NumberConverter;
import com.cool.store.utils.RandomEightCharCodeUtils;
import com.cool.store.utils.poi.DateUtils;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.vo.shop.MiniShopPageVO;
import com.cool.store.vo.shop.ShopStageInfoVO;
import com.cool.store.vo.shop.StageShopCountVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.cool.store.enums.ErrorCodeEnum.*;
import static com.cool.store.enums.UserRoleEnum.*;
import static com.cool.store.enums.WorkflowSubStageStatusEnum.*;
import static com.cool.store.enums.point.ShopSubStageEnum.SHOP_STAGE_15;
import static com.cool.store.enums.point.ShopSubStageEnum.SHOP_STAGE_8;

/**
 * @author zhangchenbiao
 * @FileName: ShopServiceImpl
 * @Description:
 * @date 2024-04-11 10:26
 */
@Service
@Slf4j
public class ShopServiceImpl implements ShopService {

    @Resource
    private DecorationMeasureDAO decorationMeasureDAO;
    @Resource
    private LinePayDAO linePayDAO;
    @Resource
    private OldShopDAO oldShopDAO;
    @Value("${mybatis.configuration.variables.enterpriseId}")
    private String eid;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    private ShopAuditInfoDAO shopAuditInfoDAO;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Resource
    private PointInfoDAO pointInfoDAO;
    @Resource
    private PointRecommendDAO pointRecommendDAO;
    @Resource
    private CommonService commonService;
    @Resource
    UserAuthMappingService userAuthMappingService;
    @Autowired
    private RegionDao regionDao;
    @Autowired
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private HyOpenAreaInfoDAO hyOpenAreaInfoDAO;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private TransferLogService transferLogService;
    @Resource
    private RegionService regionService;
    @Resource
    PreparationService preparationService;
    @Resource
    ShopAccountDAO shopAccountDAO;
    @Resource
    HyPartnerUserInfoDAO hyPartnerUserInfoDAO;
    @Resource
    StoreDao storeDao;
    @Resource
    DecorationDesignInfoDAO decorationDesignInfoDAO;
    @Resource
    StoreService storeService;
    @Resource
    EnterpriseService enterpriseService;
    @Resource
    EnterpriseUserRoleMapper enterpriseUserRoleMapper;
    @Resource
    ShopAccountService shopAccountService;
    @Resource
    PushService pushService;
    @Autowired
    private StoreOrderDAO storeOrderDAO;
    private StoreTypeDAO storeTypeDAO;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer initShop(LineInfoDO lineInfo) {
        if (Objects.isNull(lineInfo)) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        Integer wantShopNum = lineInfo.getWantShopNum();
        List<ShopInfoDO> shopList = shopInfoDAO.getShopList(lineInfo.getId());
        int shopSize = shopList.size();
        if (shopSize >= wantShopNum) {
            return 0;
        }
        List<ShopInfoDO> addShopList = new ArrayList<>();
        for (int i = shopSize; i < wantShopNum; i++) {
            ShopInfoDO shopInfo = new ShopInfoDO();
            shopInfo.setRegionId(lineInfo.getRegionId());
            shopInfo.setLineId(lineInfo.getId());
            shopInfo.setPartnerId(lineInfo.getPartnerId());
            //初始化
            shopInfo.setWantShopAreaId(lineInfo.getWantShopAreaId());
            shopInfo.setDevelopmentManager(lineInfo.getDevelopmentManager());
            shopInfo.setFranchiseBrand(lineInfo.getFranchiseBrand());
            shopInfo.setJoinMode(lineInfo.getJoinMode());
            shopInfo.setStoreNum(RandomEightCharCodeUtils.getCode());
            shopInfo.setSupervisorUserId(lineInfo.getInvestmentManager());
            shopInfo.setShopName("店铺" + NumberConverter.convertArabicToChinese(i + 1));
            shopInfo.setCreateTime(new Date());
            shopInfo.setUseStandardStore(lineInfo.getUseStandardStore());
            shopInfo.setInvestmentManager(lineInfo.getInvestmentManager());
            shopInfo.setInvestRegionId(lineInfo.getInvestRegionId());
            addShopList.add(shopInfo);
        }
        shopInfoDAO.batchAddShop(addShopList);
        List<Long> shopIds = addShopList.stream().map(ShopInfoDO::getId).collect(Collectors.toList());
        Integer result = shopStageInfoDAO.initShopStageInfo(lineInfo, addShopList, true);
        //初始化平台账号
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(lineInfo.getPartnerId());
        shopAccountDAO.initShopAccount(hyPartnerUserInfoDO, shopIds);
        HashMap<String, String> map = new HashMap<>();
        map.put("partnerUsername", lineInfo.getUsername());
        map.put("partnerMobile", lineInfo.getMobile());
        commonService.sendQWMessage(Collections.singletonList(lineInfo.getInvestmentManager()),
                MessageEnum.MESSAGE_14,
                map);
        commonService.sendQWMessage(Collections.singletonList(lineInfo.getInvestmentManager()),
                MessageEnum.MESSAGE_21,
                map);
        return result;
    }

    @Override
    public Long initAiShop(LineInfoDO lineInfo) {
        if (Objects.isNull(lineInfo)) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        List<ShopInfoDO> shopList = shopInfoDAO.getShopList(lineInfo.getId());
        int shopSize = shopList.size();
        List<ShopInfoDO> addShopList = new ArrayList<>();
        ShopInfoDO shopInfo = new ShopInfoDO();
        shopInfo.setRegionId(lineInfo.getRegionId());
        shopInfo.setLineId(lineInfo.getId());
        shopInfo.setPartnerId(lineInfo.getPartnerId());
        //初始化
        shopInfo.setWantShopAreaId(lineInfo.getWantShopAreaId());
        shopInfo.setDevelopmentManager(lineInfo.getDevelopmentManager());
        shopInfo.setFranchiseBrand(lineInfo.getFranchiseBrand());
        shopInfo.setJoinMode(lineInfo.getJoinMode());
        shopInfo.setStoreNum(RandomEightCharCodeUtils.getCode());
        shopInfo.setSupervisorUserId(lineInfo.getInvestmentManager());
        shopInfo.setShopName("AI店铺" + NumberConverter.convertArabicToChinese(shopSize + 1));
        shopInfo.setCreateTime(new Date());
        shopInfo.setUseStandardStore(lineInfo.getUseStandardStore());
        shopInfo.setInvestmentManager(lineInfo.getInvestmentManager());
        shopInfo.setInvestRegionId(lineInfo.getInvestRegionId());
        addShopList.add(shopInfo);
        shopInfoDAO.batchAddShop(addShopList);
        List<Long> shopIds = addShopList.stream().map(ShopInfoDO::getId).collect(Collectors.toList());
        Integer result = shopStageInfoDAO.initShopStageInfo(lineInfo, addShopList, true);
        //初始化平台账号
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(lineInfo.getPartnerId());
        shopAccountDAO.initShopAccount(hyPartnerUserInfoDO, shopIds);
        HashMap<String, String> map = new HashMap<>();
        map.put("partnerUsername", lineInfo.getUsername());
        map.put("partnerMobile", lineInfo.getMobile());
        commonService.sendQWMessage(Collections.singletonList(lineInfo.getInvestmentManager()),
                MessageEnum.MESSAGE_21,
                map);
        return shopInfo.getId();
    }

    /**
     * @Auther: wangshuo
     * @Date: 2025/1/13
     * @description: 当userId为空时，表示为mini，查看所有门店，否则为pc，查询的门店跟进管辖区域进行展示 二者都不关注门店状态
     */
    @Override
    public List<MiniShopPageVO> getShopList(Long lineId, String userId) {
        List<Long> authRegions = new ArrayList<>();
        if (StringUtils.isNotBlank(userId) && !sysRoleService.checkIsAdmin(userId)) {
            for (String region : userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(userId)) {
                authRegions.add(Long.valueOf(region));
            }
        }
        List<ShopInfoDO> shopList = shopInfoDAO.getShopListByRegion(lineId, authRegions, userId);
        List<Long> shopIds = shopList.stream().map(ShopInfoDO::getId).collect(Collectors.toList());
        List<Long> wantShopAreaIds = shopList.stream().map(ShopInfoDO::getWantShopAreaId).collect(Collectors.toList());
        Map<Long, String> wantRegionMap = hyOpenAreaInfoDAO.selectNameMapByIds(wantShopAreaIds);
        List<ScheduleDTO> scheduleList = shopStageInfoDAO.getScheduleList(shopIds);
        Map<Long, ScheduleDTO> scheduleMap = scheduleList.stream().collect(Collectors.toMap(ScheduleDTO::getShopId, x -> x));
        List<ShopStageInfoDO> subStageList = shopStageInfoDAO.getSubStageList(shopIds, SHOP_STAGE_8.getShopSubStage());
        Map<Long, ShopStageInfoDO> stageMap = subStageList.stream().collect(Collectors.toMap(ShopStageInfoDO::getShopId, Function.identity()));
        List<Long> regionIds = shopList.stream().flatMap(v -> Stream.of(v.getRegionId(), v.getInvestRegionId())).collect(Collectors.toList());
        regionIds.addAll(Optional.of(shopList).orElse(Collections.emptyList()).stream().map(ShopInfoDO::getManagerRegionId).collect(Collectors.toList()));
        Map<Long, String> regionNameMap = regionDao.getRegionNameMap(regionIds);
        List<String> investmentManagerIds = shopList.stream().map(ShopInfoDO::getInvestmentManager).collect(Collectors.toList());
        Map<String, EnterpriseUserDO> userInfoMap = enterpriseUserDAO.getUserInfoMap(investmentManagerIds);
        return MiniShopPageVO.convertList(shopList, stageMap, regionNameMap, scheduleMap, wantRegionMap, userInfoMap);
    }

    @Override
    public List<ShopStageInfoVO> getShopStageInfo(Long shopId, Integer shopStage) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.SHOP_ID_NOT_EXIST);
        }
        if (Objects.nonNull(shopStage)) {
            ShopStageEnum shopStageEnum = ShopStageEnum.getShopStageEnum(shopStage);
            if (Objects.isNull(shopStageEnum)) {
                throw new ServiceException(ErrorCodeEnum.SHOP_STAGE_ERROR);
            }
        }
        List<ShopStageInfoDO> shopStageInfo = shopStageInfoDAO.getShopStageInfo(shopId, shopStage);
        List<Long> auditIds = shopStageInfo.stream().filter(o -> Objects.nonNull(o.getAuditId())).map(ShopStageInfoDO::getAuditId).distinct().collect(Collectors.toList());
        List<ShopAuditInfoDO> auditList = shopAuditInfoDAO.getAuditInfoList(auditIds);
        return ShopStageInfoVO.convertList(shopStageInfo, auditList);
    }

    @Override
    public StageShopCountVO getStageShopCount(Long lineId) {
        return shopInfoDAO.getStageShopCount(lineId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteShop(DeleteShopRequest request) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        if (shopInfo == null) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
//        if (Objects.nonNull(shopInfo)) {
//            //进入选址不允许删除操作
//            throw new ServiceException(ErrorCodeEnum.NOT_ALLOW_OPERATE);
//        }
        if (shopInfo.getUseStandardStore()==0){
            ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(shopInfo.getId(), ShopSubStageEnum.SHOP_STAGE_7);
            if (ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_73.getShopSubStageStatus().equals(shopSubStageInfo.getShopSubStageStatus())) {
                throw new ServiceException(ErrorCodeEnum.IS_EXIST_CLAIM);
            }
        }
        List<LinePayDO> franchiseFeePayInfoByShopId = linePayDAO.getFranchiseFeePayInfoByShopId(request.getShopId());
        if (ListUtils.emptyIfNull(franchiseFeePayInfoByShopId)
                .stream()
                .anyMatch(lineInfoDO -> lineInfoDO.getXgjClaimStatus().equals(ClaimStatusEnum.CLAIMED.getCode()))) {
            throw new ServiceException(ErrorCodeEnum.IS_EXIST_CLAIM);
        }
//        if (Objects.nonNull(shopInfo.getPointId())) {
//            PointInfoDO pointInfo = pointInfoDAO.getPointInfoById(shopInfo.getPointId());
//            if (Objects.nonNull(pointInfo) && SelectStatusEnum.SELECT_STATUS_1.getCode().equals(pointInfo.getSelectStatus())) {
//                pointInfoDAO.recyclePoint(pointInfo.getId());
//            }
//            pointRecommendDAO.updateRecommendStatus(shopInfo.getPointId(), PointRecommendStatusEnum.POINT_RECOMMEND_STATUS_1, Arrays.asList(PointRecommendStatusEnum.POINT_RECOMMEND_STATUS_5));
//        }
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        if (lineInfoDO.getWantShopNum() > 1) {
            lineInfoDO.setWantShopNum(lineInfoDO.getWantShopNum() - 1);
        }
        lineInfoDO.setUpdateTime(new Date());
        lineInfoDO.setUpdateUserId(request.getUserId());
        lineInfoDAO.updateLineInfo(lineInfoDO);
        ShopInfoDO updateShop = new ShopInfoDO();
        updateShop.setId(request.getShopId());
        updateShop.setDeleted(true);
        updateShop.setUpdateTime(new Date());
        updateShop.setUpdateUserId(request.getUserId());
        return shopInfoDAO.updateShopInfo(updateShop);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addShop(AddShopRequest request) {
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(request.getLineId());
        if (Objects.isNull(lineInfo)) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        List<String> shopNameList = request.getShopNameList();
        List<ShopInfoDO> shopList = shopInfoDAO.getShopList(request.getLineId());
        LineInfoDO updateLine = new LineInfoDO();
        updateLine.setId(request.getLineId());
        updateLine.setWantShopNum(shopList.size() + shopNameList.size());
        lineInfoDAO.updateLineInfo(updateLine);
        List<ShopInfoDO> addShopList = new ArrayList<>();
        for (String shopName : shopNameList) {
            ShopInfoDO addShop = new ShopInfoDO();
            addShop.setRegionId(lineInfo.getRegionId());
            addShop.setLineId(request.getLineId());
            addShop.setPartnerId(lineInfo.getPartnerId());
            addShop.setShopName(shopName);
            addShop.setSupervisorUserId(lineInfo.getInvestmentManager());
            addShop.setInvestmentManager(lineInfo.getInvestmentManager());
            addShop.setDevelopmentManager(lineInfo.getInvestmentManager());
            addShop.setUseStandardStore(lineInfo.getUseStandardStore());
            addShopList.add(addShop);
        }
        shopInfoDAO.batchAddShop(addShopList);
        List<Long> shopIds = addShopList.stream().map(ShopInfoDO::getId).collect(Collectors.toList());
        shopStageInfoDAO.initShopStageInfo(lineInfo, addShopList, true);
        return 1L;
    }

    @Override
    public ShopInfoDO getShopInfo(Long shopId) {

        return shopInfoDAO.getShopInfo(shopId);
    }

    @Override
    public Integer updateShopCode(UpdateShopCodeRequest request, String userId) {
        //检验门店编码是否重复
       if(this.checkShopCodeRepeat(request.getShopCode(), request.getShopId())){
           throw new ServiceException(ErrorCodeEnum.SHOP_CODE_EXIST);
       }
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.POINT_NOT_EXIST);
        }
        shopInfo.setShopCode(request.getShopCode().trim());
        shopInfo.setShopName(request.getShopName());
        shopInfo.setUpdateTime(new Date());
        shopInfo.setUpdateUserId(userId);
        shopInfo.setRegionId(request.getRegionId());
        return shopInfoDAO.updateShopInfo(shopInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addBranchShop(AddBranchShopRequest request, String userId) {
        if (StringUtils.isBlank(request.getInvestmentManagerUserId())) {
            request.setInvestmentManagerUserId(userId);
        }
        enterpriseService.checkUser(userId, request.getJoinMode());
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(request.getLineId());
        if (lineInfo.getWorkflowSubStageStatus() < WorkflowSubStageStatusEnum.PAY_DEPOSIT_45.getCode()) {
            throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
        }
        ShopInfoDO shopInfoDO = request.toDO(request, lineInfo);
        List<ShopInfoDO> shopList = shopInfoDAO.getShopList(lineInfo.getId());
        if (StringUtils.isBlank(request.getShopName())) {
            if (CollectionUtils.isNotEmpty(shopList)) {
                shopInfoDO.setShopName("店铺" + NumberConverter.convertArabicToChinese(lineInfo.getWantShopNum() + 1));
            } else {
                shopInfoDO.setShopName("店铺" + NumberConverter.convertArabicToChinese(lineInfo.getWantShopNum()));
            }
        } else {
            shopInfoDO.setShopName(request.getShopName());
        }

        if (CollectionUtils.isNotEmpty(shopList)) {
            lineInfo.setWantShopNum(lineInfo.getWantShopNum() + 1);
            lineInfoDAO.updateLineInfo(lineInfo);
        }
        shopInfoDO.setCreateUserId(userId);
        Long shopId = shopInfoDAO.addShopInfo(shopInfoDO);
        //只赋值 不更新
        lineInfo.setUseStandardStore(request.getUseStandardStore());
        if (lineInfo.getWorkflowSubStageStatus().equals(WorkflowSubStageStatusEnum.SIGN_INTENT_AGREEMENT_125.getCode())) {
            shopStageInfoDAO.initShopStageInfo(lineInfo, Collections.singletonList(shopInfoDO), true);
            HashMap<String, String> map = new HashMap<>();
            map.put("partnerUsername", lineInfo.getUsername());
            map.put("partnerMobile", lineInfo.getMobile());
            Set<String> publishFranchiseFeeUsers = new HashSet<>();
            List<EnterpriseUserDO> joinUser = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.JOIN_OFFICE, request.getRegionId());
            if (Objects.nonNull(joinUser)) {
                Set<String> joinUserIds = joinUser.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toSet());
                publishFranchiseFeeUsers.addAll(joinUserIds);
            }
            List<EnterpriseUserDO> regionUser = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.REGION_OFFICE, request.getRegionId());
            if (Objects.nonNull(regionUser)) {
                Set<String> regionUserIds = regionUser.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toSet());
                publishFranchiseFeeUsers.addAll(regionUserIds);
            }
            commonService.sendQWMessage(Collections.singletonList(request.getInvestmentManagerUserId()),
                    MessageEnum.MESSAGE_14,
                    map);
            commonService.sendQWMessage(Collections.singletonList(request.getInvestmentManagerUserId()),
                    MessageEnum.MESSAGE_21,
                    map);
        } else {
            shopStageInfoDAO.initShopStageInfo(lineInfo, Collections.singletonList(shopInfoDO), false);
        }
        //初始化平台账号
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(lineInfo.getPartnerId());
        shopAccountDAO.initShopAccount(hyPartnerUserInfoDO, Collections.singletonList(shopId));
        return shopId;
    }

    @Override
    public BranchShopDetailResponse getBranchShopDetail(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        if (Objects.isNull(lineInfo)) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        Map<String, String> userNameMap = enterpriseUserDAO.getUserNameMap(Arrays.asList(shopInfo.getInvestmentManager(), shopInfo.getOperationsConsultant()));
        List<ScheduleDTO> shopContractActualCompletionTime = shopStageInfoDAO.getScheduleList(Collections.singletonList(shopId));
        List<RegionDO> allRegionByRegionIds = regionDao.getAllRegionByRegionIds(Arrays.asList(shopInfo.getRegionId(), shopInfo.getManagerRegionId(), shopInfo.getInvestRegionId()));
        Map<Long, RegionDO> regionMap = allRegionByRegionIds.stream().collect(Collectors.toMap(RegionDO::getId, data -> data));
        HyOpenAreaInfoDO hyOpenAreaInfoDO = hyOpenAreaInfoDAO.selectById(shopInfo.getWantShopAreaId());
        BranchShopDetailResponse response = new BranchShopDetailResponse();
        response.setManagerRegionId(shopInfo.getManagerRegionId());
        if (shopInfo.getManagerRegionId()!=null) {
            response.setManagerRegionName(regionMap.getOrDefault(shopInfo.getManagerRegionId(),new RegionDO()).getName());
        }
        response.setUseStandardStore(shopInfo.getUseStandardStore());
        response.setUsername(lineInfo.getUsername());
        response.setMobile(lineInfo.getMobile());
        response.setShopId(shopId);
        response.setLineId(lineInfo.getId());
        response.setShopName(shopInfo.getShopName());
        response.setJoinMode(shopInfo.getJoinMode());
        response.setShopCode(shopInfo.getShopCode());
        response.setStoreType(shopInfo.getStoreType());
        response.setShopStatus(shopInfo.getShopStatus());
        response.setFranchiseBrand(shopInfo.getFranchiseBrand());
        if (CollectionUtils.isNotEmpty(shopContractActualCompletionTime)) {
            ScheduleDTO scheduleDTO = shopContractActualCompletionTime.get(CommonConstants.ZERO);
            response.setCompletionColumn(scheduleDTO.getCompletionColumn());
            response.setTotalColumn(scheduleDTO.getTotalColumn());
            response.setPlanCompletionTime(scheduleDTO.getPlanCompleteTime());
        }
        response.setInvestmentManagerId(shopInfo.getInvestmentManager());
        response.setInvestmentManagerName(userNameMap.get(shopInfo.getInvestmentManager()));
        response.setOperationsConsultant(shopInfo.getOperationsConsultant());
        response.setOperationsConsultantName(userNameMap.get(shopInfo.getOperationsConsultant()));
        response.setInvestRegionId(Long.valueOf(0).equals(shopInfo.getInvestRegionId()) ? null : shopInfo.getInvestRegionId());
        if (shopInfo.getInvestRegionId() != null) {
            response.setInvestRegionName(regionMap.getOrDefault(shopInfo.getInvestRegionId(),new RegionDO()).getName());
        }
        response.setRegionId(shopInfo.getRegionId());
        if (shopInfo.getRegionId()!=null){
            response.setRegionName(regionMap.getOrDefault(shopInfo.getRegionId(),new RegionDO()).getName());
        }
        response.setWantRegionId(shopInfo.getWantShopAreaId());
        if (hyOpenAreaInfoDO != null) {
            response.setWantRegionName(hyOpenAreaInfoDO.getAreaName());
            response.setWantRegionParentId(hyOpenAreaInfoDO.getParentId());
        }
        response.setPointId(shopInfo.getPointId());
        return response;
    }

    @Override
    public Integer updateBranchShopDetail(BranchShopDetailRequest request, String userId) {
        //检验门店编码是否重复
        if(StringUtils.isNotEmpty(request.getShopCode())&&this.checkShopCodeRepeat(request.getShopCode(), request.getShopId())){
            throw new ServiceException(ErrorCodeEnum.SHOP_CODE_EXIST);
        }
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        String oldShopCode = shopInfo.getShopCode();
        //0-不是使用标准店型
        if (shopInfo.getUseStandardStore()==0){
            //新增校验 缴费阶段之后 不能修改加盟模式
            ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(request.getShopId(), ShopSubStageEnum.SHOP_STAGE_7);
            //缴费阶段之后 加盟模式不能切换为直营店 直营店也不能切换为其他店
            if (shopSubStageInfo.getShopSubStageStatus()>ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_70.getShopSubStageStatus()){
                if (request.getJoinMode()!=shopInfo.getJoinMode()&&
                        (request.getJoinMode()==JoinModeEnum.FLAGSHIP_STORE.getCode()||shopInfo.getJoinMode()==JoinModeEnum.FLAGSHIP_STORE.getCode())){
                    throw new ServiceException(ErrorCodeEnum.NOT_FLAGSHIP_STORE_NOT_EXIST);
                }
            }
        }
        shopInfo.setUpdateUserId(userId);
        shopInfo.setUpdateTime(new Date());
        if (StringUtils.isNotEmpty(request.getShopCode())){
            shopInfo.setShopCode(request.getShopCode().trim());
        }
        shopInfo.setShopName(request.getShopName());
        shopInfo.setWantShopAreaId(request.getWantShopAreaId());
        shopInfo.setRegionId(request.getRegionId());
        shopInfo.setJoinMode(request.getJoinMode());
        shopInfo.setFranchiseBrand(request.getFranchiseBrand());
        shopInfo.setStoreType(request.getStoreType());
        shopInfo.setManagerRegionId(request.getManagerRegionId());
        shopInfo.setInvestRegionId(request.getInvestRegionId());
        Integer f = shopInfoDAO.updateShopInfo(shopInfo);
        if (StringUtils.isNotBlank(request.getShopCode()) && StringUtils.compare(request.getShopCode().trim(), oldShopCode) != 0) {
            // 完成合同签约后推送新管家
            ShopStageInfoDO contractStage = shopStageInfoDAO.getShopSubStageInfo(request.getShopId(), SHOP_STAGE_8);
            if (contractStage.getShopSubStageStatus().equals(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_84.getShopSubStageStatus())) {
                try {
                    log.info("门店编码发生修改，推送新管家");
                    ZxjpApiRequest data = shopAccountService.getData(request.getShopId(), DownSystemTypeEnum.XGJ);
                    pushService.pushDataToXGJ(data);
                } catch (Exception e) {
                    log.error("推送新管家失败", e);
                }
            }
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateShopInvestment(Long shopId, String updateUserId, String userId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (updateUserId.equals(shopInfo.getInvestmentManager())) {
            throw new ServiceException(UPDATE_INVESTMENT_MANAGER_FAIL);
        }
        transferLogService.addLog(shopInfo.getId(), shopInfo.getPartnerId(), shopInfo.getInvestmentManager(), updateUserId, OperationLogTypeEnum.TRANSFER_INVESTMENT_MANAGER_4);
        shopInfo.setUpdateTime(new Date());
        shopInfo.setUpdateUserId(userId);
        shopInfo.setInvestmentManager(updateUserId);
        shopInfo.setDevelopmentManager(updateUserId);
        shopInfo.setSupervisorUserId(updateUserId);
        return shopInfoDAO.updateShopInfo(shopInfo);
    }

    @Override
    public Boolean updateOperationsConsultant(Long shopId, String operationsConsultant) {
        if (StringUtils.isEmpty(operationsConsultant)||Objects.isNull(shopId)){
            throw new ServiceException(PARAMS_VALIDATE_ERROR);
        }
        log.info("updateOperationsConsultant shopId:{},operationsConsultant:{}",shopId,operationsConsultant);
        ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(shopId, SHOP_STAGE_15);
        //分配运营顾问之后 可以修改 也就是阶段是建店开始之后就可以修改
        if (ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_00.getShopSubStageStatus().equals(shopSubStageInfo.getShopSubStageStatus())){
            throw new ServiceException(CONTRACT_STAGE_NO_COMPLETE);
        }
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        shopInfo.setOperationsConsultant(operationsConsultant);
        shopInfoDAO.updateShopInfo(shopInfo);
        return Boolean.TRUE;
    }

    @Resource
    PointService pointService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean shopClose(Long shopId) {
        log.info("shopClose shopId:{}", shopId);
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        //只有跟进中才能结束跟进
        if (ShopStatusEnum.ING.getCode() != shopInfo.getShopStatus()) {
            throw new ServiceException(ErrorCodeEnum.SHOP_STATUS_NOT_SUPPORT_HANDLER, ShopStatusEnum.getDesc(shopInfo.getShopStatus()));
        }
        shopInfo.setShopStatus(ShopStatusEnum.ABANDON.getCode());
        shopInfoDAO.updateShopInfo(shopInfo);
        //放弃之后解绑铺位
        if (shopInfo.getPointId()!=null){
            //解绑铺位
            pointService.pointUnbind(shopInfo.getPointId(),Boolean.TRUE);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateShopStatue(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        Integer completionCount = shopStageInfoDAO.getCompletionCount(shopId);
        if (completionCount.equals(ShopSubStageEnum.getTotalStageIsLocationAndPreparation(shopInfo.getUseStandardStore()))) {
            shopInfo.setShopStatus(ShopStatusEnum.DONE.getCode());
        } else {
            shopInfo.setShopStatus(ShopStatusEnum.ING.getCode());
        }
        shopInfoDAO.updateShopInfo(shopInfo);
        return Boolean.TRUE;
    }

    @Override
    public PageInfo<BranchShopResponse> getBranchShopList(BranchShopRequest request, String userId) {
        // 2为我管辖的
        if (request.getFlag().equals(CommonConstants.TWO)) {
            if (!sysRoleService.checkIsAdmin(userId)) {
                List<String> authRegionIds = userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(userId);
                if (CollectionUtils.isEmpty(authRegionIds)) {
                    return new PageInfo<>();
                }
                List<Long> userRoleIds = enterpriseUserRoleMapper.getUserRoleIds(userId);
                // 招商经理查询招商区域invest_region_id，否则查询运营区域region_id
                request.setAuthRegionIds(authRegionIds);
            }
        }
        if (CollectionUtils.isNotEmpty(request.getRegionIds())) {
            if (request.getRegionIds().contains(CommonConstants.ROOT_DEPT_ID_STR)) {
                request.setRegionIds(null);
            } else {
                request.setRegionIds(regionService.getSubRegionIdsByRegionIds(request.getRegionIds()));
            }
        }
        if (CollectionUtils.isNotEmpty(request.getWantShopAreaId())) {
            List<Long> childrenListByParentIds = hyOpenAreaInfoDAO.getChildrenListByParentIds(request.getWantShopAreaId());
            childrenListByParentIds.addAll(request.getWantShopAreaId());
            request.setWantShopAreaAllIds(childrenListByParentIds);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<BranchShopResponse> responses = new ArrayList<>();
        List<PreparationDTO> preparations = shopInfoDAO.ListByBranchShopRequest(request, userId);
        PageInfo pageInfo = new PageInfo<>(preparations);
        if (CollectionUtils.isEmpty(preparations)) {
            return new PageInfo<>();
        }
        List<Long> regionIds = preparations.stream()
                .flatMap(v -> Stream.of(v.getRegionId(), v.getInvestRegionId()))
                .collect(Collectors.toList());
        regionIds.addAll(Optional.of(preparations).orElse(Collections.emptyList()).stream().map(PreparationDTO::getManagerRegionId).collect(Collectors.toList()));
        List<Long> wantShopAreaIds = preparations.stream().map(PreparationDTO::getWantShopAreaId).collect(Collectors.toList());
        List<String> investmentManagerIds = preparations.stream().map(PreparationDTO::getInvestmentManager).collect(Collectors.toList());
        List<Long> shopIds = preparations.stream().map(PreparationDTO::getId).collect(Collectors.toList());
        List<ScheduleDTO> scheduleList = shopStageInfoDAO.getScheduleList(shopIds);
        Map<Long, ScheduleDTO> scheduleMap = scheduleList.stream().collect(Collectors.toMap(ScheduleDTO::getShopId, x -> x));
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIds);
        Map<String, EnterpriseUserDO> userInfoMap = enterpriseUserDAO.getUserInfoMap(investmentManagerIds);
        Map<Long, String> wantRegionMap = hyOpenAreaInfoDAO.selectNameMapByIds(wantShopAreaIds);
        List<ShopStageInfoDO> openActivityActualCompletionTime = shopStageInfoDAO.getOpenActivityActualCompletionTime(shopIds);
        Map<Long, ShopStageInfoDO> openActivityStageMap = openActivityActualCompletionTime.stream().collect(Collectors.toMap(ShopStageInfoDO::getShopId, x -> x));
        for (PreparationDTO dto : preparations) {
            BranchShopResponse response = new BranchShopResponse();
            response.setShopAddress(dto.getShopAddress());
            response.setStoreType(dto.getStoreType());
            response.setShopId(dto.getId());
            response.setPointId(dto.getPointId());
            response.setLineId(dto.getLineId());
            response.setUsername(dto.getUsername());
            response.setMobile(dto.getMobile());
            response.setStoreId(dto.getStoreId());
            response.setUseStandardStore(dto.getUseStandardStore());
            response.setShopName(dto.getShopName());
            response.setShopCode(dto.getShopCode());
            response.setRegionName(regionNameMap.getOrDefault(dto.getRegionId(), ""));
            response.setFranchiseBrand(dto.getFranchiseBrand());
            response.setJoinMode(dto.getJoinMode());
            response.setWantRegionName(wantRegionMap.getOrDefault(dto.getWantShopAreaId(), ""));
            response.setPlanOpenTime(dto.getPlanOpenTime());
            ScheduleDTO scheduleDTO = scheduleMap.getOrDefault(dto.getId(), new ScheduleDTO());
            response.setTotalColumn(scheduleDTO.getTotalColumn());
            response.setCompletionColumn(scheduleDTO.getCompletionColumn());
            response.setOpeningActivityEndTime(DateUtils.strToDate(openActivityStageMap.getOrDefault(dto.getId(), new ShopStageInfoDO()).getActualCompleteTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            response.setInvestmentManagerName(userInfoMap.getOrDefault(dto.getInvestmentManager(), new EnterpriseUserDO()).getName());
            response.setShopStatus(ShopStatusEnum.getDesc(dto.getShopStatus()));
            response.setCreateTime(dto.getCreateTime());
            response.setDays();
            response.setManagerRegionId(dto.getManagerRegionId());
            response.setManagerRegionName(regionNameMap.getOrDefault(dto.getManagerRegionId(), ""));
            response.setInvestRegionId(dto.getInvestRegionId());
            response.setInvestRegionName(regionNameMap.getOrDefault(dto.getInvestRegionId(), ""));
            responses.add(response);
        }
        pageInfo.setList(responses);
        return pageInfo;
    }


    /**
     * 数据处理
     * @param lineId
     * @return
     */
    @Override
    public Boolean dataHandler(Long lineId) {
        log.info("------dataHandle start-----");
        boolean hasNext = true;
        int pageNum = 1;
        int pageSize = 50;
        while (hasNext) {
            PageHelper.startPage(pageNum, pageSize);
            List<ShopInfoDO> shopInfoDOS = shopInfoDAO.selectAllDataOrByLineId(lineId);
            if (CollectionUtils.isEmpty(shopInfoDOS)) {
                log.info("------dataHandle end------");
                return Boolean.TRUE;
            }
            Set<Long> lineIds = shopInfoDOS.stream().map(ShopInfoDO::getLineId).collect(Collectors.toSet());
            List<LineInfoDO> lines = lineInfoDAO.getByLineIds(new ArrayList<>(lineIds));
            //转为map
            Map<Long, LineInfoDO> lineMap = lines.stream().collect(Collectors.toMap(LineInfoDO::getId, line -> line));
            List<Long> shopIds = shopInfoDOS.stream().map(ShopInfoDO::getId).collect(Collectors.toList());
            Map<Long, Integer> shopStatus = preparationService.getShopStatus(shopIds);
            for (ShopInfoDO shopInfoDO : shopInfoDOS) {
                LineInfoDO lineInfoDO = lineMap.get(shopInfoDO.getLineId());
                if (lineInfoDO == null) {
                    continue;
                }
                shopInfoDO.setDevelopmentManager(lineInfoDO.getDevelopmentManager());
                shopInfoDO.setShopStatus(shopStatus.get(shopInfoDO.getId()));
                shopInfoDO.setJoinMode(lineInfoDO.getJoinMode());
                shopInfoDO.setFranchiseBrand(lineInfoDO.getFranchiseBrand());
                shopInfoDO.setInvestmentManager(lineInfoDO.getInvestmentManager());
                shopInfoDO.setWantShopAreaId(lineInfoDO.getWantShopAreaId());
            }
            shopInfoDAO.batchUpdate(shopInfoDOS);
            log.info("------shopInfoDOS:{}------", JSONObject.toJSONString(shopInfoDOS));
            hasNext = shopInfoDOS.size() >= pageSize;
            pageNum++;
        }
        return Boolean.TRUE;
    }

    @Override
    public PageInfo<MiniShopsResponse> getShopListSuccessOpen(ShopListSuccessOpenRequest request) {
        Long lineId = request.getLineId();
        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        String storeName = request.getStoreName();
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(lineId);
        PageInfo<MiniShopsResponse> storeListByMobile = storeService.getStoreListByMobile(lineInfoDO.getMobile(), pageNum, pageSize, storeName, request.getStoreNum());
        if (CollectionUtils.isEmpty(storeListByMobile.getList())) {
            return new PageInfo<>(new ArrayList<>());
        }
        for (MiniShopsResponse response : storeListByMobile.getList()) {
            response.setYlsCode("ZXA8_" + response.getShopCode());
        }
        return storeListByMobile;
    }

    @Override
    public ShopResponse getShopNameAndCode(Long shopId, Long lineId) {
        boolean flag = false;
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(lineId);
        if (lineInfoDO == null) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        ShopResponse response = new ShopResponse();

        List<ShopNameAndCodeDTO> list = new ArrayList<>();
        List<MiniShopsResponse> shopList = shopInfoDAO.getShopListSuccessOpen(eid, lineId);
        if (CollectionUtils.isNotEmpty(shopList)) {
            for (MiniShopsResponse shopInfoDO : shopList) {
                ShopNameAndCodeDTO dto = new ShopNameAndCodeDTO();
                dto.setShopName(shopInfoDO.getShopName());
                dto.setShopCode(shopInfoDO.getShopCode());
                dto.setShopAddress(shopInfoDO.getDetailAddress());
                list.add(dto);
            }
            Map<Long, MiniShopsResponse> shopMap = shopList.stream().collect(Collectors.toMap(MiniShopsResponse::getShopId, Function.identity()));
            //获取当前门店
            if (Objects.nonNull(shopMap.get(shopId))) {
                ShopNameAndCodeDTO currentShop = new ShopNameAndCodeDTO();
                currentShop.setShopName(shopMap.get(shopId).getShopName());
                currentShop.setShopCode(shopMap.get(shopId).getShopCode());
                currentShop.setShopAddress(shopMap.get(shopId).getDetailAddress());
                response.setCurrentShop(currentShop);
            }
        }
        List<StoreDO> storeDOS = storeDao.listByMobile(lineInfoDO.getMobile());
        storeDOS.stream().forEach(x -> {
            ShopNameAndCodeDTO dto = new ShopNameAndCodeDTO();
            dto.setShopName(x.getStoreName());
            dto.setShopCode(x.getStoreNum());
            dto.setShopAddress(x.getStoreAddress());
            list.add(dto);
        });

        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        //去重
        List<ShopNameAndCodeDTO> distinctList = new ArrayList<>(list.stream()
                .collect(Collectors.toMap(
                        ShopNameAndCodeDTO::getShopCode,
                        dto -> dto,
                        (existing, replacement) -> existing
                ))
                .values());
        response.setShopList(distinctList);
        log.info("shopInfo：{}", JSONObject.toJSONString(response));
        return response;
    }

    @Override
    public ShopResponse getShopNameAndCodeByMobile(String mobile, Long shopId) {
        LineInfoDO lineInfo = lineInfoDAO.getLineByMobile(mobile);
        if (Objects.isNull(lineInfo)) {
            throw new ServiceException(LINE_ID_IS_NOT_EXIST);
        }
        return getShopNameAndCode(shopId, lineInfo.getId());
    }

    @Override
    public String getFranchiseBrandName(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (shopInfo == null) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        return FranchiseBrandEnum.getDescByCode(shopInfo.getFranchiseBrand());
    }

    @Override
    public Integer dateHandler(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ShopStageInfoDO> shopIdListByStageStatus = shopStageInfoDAO.getShopIdListByStageStatus(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_84.getShopSubStageStatus());
        List<Long> shopIds = shopIdListByStageStatus.stream().map(ShopStageInfoDO::getShopId).collect(Collectors.toList());
        List<ShopInfoDO> shopList = shopInfoDAO.getShopListByIds(shopIds);
        List<Long> pointIdList = shopList.stream().filter(o -> o.getPointId() != null).map(ShopInfoDO::getPointId).collect(Collectors.toList());
        List<PointInfoDO> pointListByIds = pointInfoDAO.getPointListByIds(pointIdList);
        Map<Long, PointInfoDO> pointInfoDOMap = pointListByIds.stream().collect(Collectors.toMap(PointInfoDO::getId, Function.identity()));
        for (ShopInfoDO shopInfoDO : shopList) {
            if (shopInfoDO.getPointId() == null) {
                continue;
            }
            PointInfoDO pointInfoDO = pointInfoDOMap.get(shopInfoDO.getPointId());
            if (pointInfoDO == null) {
                continue;
            }
            shopInfoDO.setProvince(pointInfoDO.getProvince());
            shopInfoDO.setCity(pointInfoDO.getCity());
            shopInfoDO.setDistrict(pointInfoDO.getDistrict());
        }
        return shopInfoDAO.updateShopCity(shopList);
    }

    @Override
    public List<UserDTO> getIntendSubStageHandle(Long lineId, Integer subStage) {
        //查询线索
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        List<UserDTO> userList = new ArrayList<>();
        //如果阶段对应不上 直接返回空
        if (!lineInfo.getWorkflowSubStage().equals(subStage)) {
            return userList;
        }
        //加盟商处理时子阶段状态
        List<Integer> intendPartnerList = Arrays.asList(INTENT_0.getCode(), PAY_DEPOSIT_45.getCode());
        if (intendPartnerList.contains(lineInfo.getWorkflowSubStageStatus())) {
            UserDTO userDTO = new UserDTO(lineInfo.getUsername(), lineInfo.getMobile());
            userList.add(userDTO);
            return userList;
        }
        //督导处理阶段
        List<Integer> intendManagerList = Arrays.asList(INTENT_5.getCode(), PAY_DEPOSIT_50.getCode(), SIGN_INTENT_AGREEMENT_70.getCode());
        if (intendManagerList.contains(lineInfo.getWorkflowSubStageStatus())) {
            EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(lineInfo.getInvestmentManager());
            if (Objects.nonNull(userInfo)) {
                UserDTO userDTO = new UserDTO(userInfo.getName(), userInfo.getMobile());
                userList.add(userDTO);
            }
            return userList;
        }
        List<Integer> bigRegionManagerList = Arrays.asList(INTENT_6.getCode());
        if (bigRegionManagerList.contains(lineInfo.getWorkflowSubStageStatus())) {
            return getUsersByRolesAndRegion(Arrays.asList(REGION_MANAGER), lineInfo.getInvestRegionId());
        }
        return userList;
    }


    @Override
    public List<UserDTO> getSubStageHandle(Long shopId, Integer subStage) {
        // 参数校验
        if (shopId == null || subStage == null) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }

        // 基础数据
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        DecorationMeasureDO measureDO = decorationMeasureDAO.getByShopId(shopId);
        DecorationDesignInfoDO decoration = decorationDesignInfoDAO.getByShopId(shopId);
        ShopStageInfoDO stage = shopStageInfoDAO.getByShopIdAndSubStage(shopId, subStage);
        ShopSubStageStatusEnum statusEnum = ShopSubStageStatusEnum.getShopSubStageStatusEnum(stage.getShopSubStageStatus());

        // Handle each status case
        switch (statusEnum) {
            case SHOP_SUB_STAGE_STATUS_10:
            case SHOP_SUB_STAGE_STATUS_20:
            case SHOP_SUB_STAGE_STATUS_22:
            case SHOP_SUB_STAGE_STATUS_30:
            case SHOP_SUB_STAGE_STATUS_40:
            case SHOP_SUB_STAGE_STATUS_71:
            case SHOP_SUB_STAGE_STATUS_74:
            case SHOP_SUB_STAGE_STATUS_905:
            case SHOP_SUB_STAGE_STATUS_121:
            case SHOP_SUB_STAGE_STATUS_150:
            case SHOP_SUB_STAGE_STATUS_180:
            case SHOP_SUB_STAGE_STATUS_182:
            case SHOP_SUB_STAGE_STATUS_190:
            case SHOP_SUB_STAGE_STATUS_194:
            case SHOP_SUB_STAGE_STATUS_200:
            case SHOP_SUB_STAGE_STATUS_202:
            case SHOP_SUB_STAGE_STATUS_210:
            case SHOP_SUB_STAGE_STATUS_214:
            case SHOP_SUB_STAGE_STATUS_220:
            case SHOP_SUB_STAGE_STATUS_222:
            case SHOP_SUB_STAGE_STATUS_250:
            case SHOP_SUB_STAGE_STATUS_254:
            case SHOP_SUB_STAGE_STATUS_60:
            case SHOP_SUB_STAGE_STATUS_280:
            case SHOP_SUB_STAGE_STATUS_283:
            case SHOP_SUB_STAGE_STATUS_284:
            case SHOP_SUB_STAGE_STATUS_281_5:
                return Collections.singletonList(new UserDTO(lineInfo.getUsername(), lineInfo.getMobile()));

            case SHOP_SUB_STAGE_STATUS_11:
            case SHOP_SUB_STAGE_STATUS_21:
            case SHOP_SUB_STAGE_STATUS_50:
            case SHOP_SUB_STAGE_STATUS_140:
            case SHOP_SUB_STAGE_STATUS_141:
            case SHOP_SUB_STAGE_STATUS_142:
            case SHOP_SUB_STAGE_STATUS_171:
            case SHOP_SUB_STAGE_STATUS_270:
            case SHOP_SUB_STAGE_STATUS_274:
                return getUserFromInvestmentManager(shopInfo.getInvestmentManager());
            case SHOP_SUB_STAGE_STATUS_122:
            case SHOP_SUB_STAGE_STATUS_110:
            case SHOP_SUB_STAGE_STATUS_111:
                return getUsersByRolesAndRegion(Collections.singletonList(CONSTRUCTION_CUSTOMER), shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_70:
            case SHOP_SUB_STAGE_STATUS_80:
            case SHOP_SUB_STAGE_STATUS_85:
                return getUsersByRolesAndRegion(Arrays.asList(REGION_OFFICE, JOIN_OFFICE), shopInfo.getInvestRegionId());

            // case SHOP_SUB_STAGE_STATUS_72:
            case SHOP_SUB_STAGE_STATUS_83:
            case SHOP_SUB_STAGE_STATUS_282:
                return getUsersByRolesAndRegion(Arrays.asList(REGION_OFFICE, BRANCH_OFFICE), shopInfo.getInvestRegionId());

            case SHOP_SUB_STAGE_STATUS_83_5:
                return getUsersByRolesAndRegion(Collections.singletonList(FINANCE), shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_85_1:
                return getUsersByRole(FINANCE);

            case SHOP_SUB_STAGE_STATUS_861:
                return getUsersByRole(CONSTRUCTION_CUSTOMER);

            case SHOP_SUB_STAGE_STATUS_862:
                return getUserById(measureDO.getMeasureUserId());

            case SHOP_SUB_STAGE_STATUS_90:
                return getUserById(measureDO.getDesignUserId());

            case SHOP_SUB_STAGE_STATUS_901:
                return getUserById(decoration.getDesignUserId());

            case SHOP_SUB_STAGE_STATUS_902:
                return getUsersByRole(QUOTATION_OFFICE);

            case SHOP_SUB_STAGE_STATUS_903:
                return getUserById(decoration.getQuotationUserId());

            case SHOP_SUB_STAGE_STATUS_151:
                return getUsersByRoleAndRegion(UserRoleEnum.LOGISTICS, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_152:
                UserRoleEnum financeRole = JoinModeEnum.OWN_STORE.getCode() == shopInfo.getJoinMode()
                        ? UserRoleEnum.OWN_SHOP_OFFICE
                        : UserRoleEnum.FINANCE;
                return getUsersByRole(financeRole);

            case SHOP_SUB_STAGE_STATUS_153:
                return getUsersByRolesAndRegion(Arrays.asList(HEAD_OF_DIVISION, REGIONAL_MANAGER), shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_154:
                return getUsersByRoleAndRegion(UserRoleEnum.VICE_PRESIDENT_IN_CHARGE, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_155:
                return getUsersByRoleAndRegion(UserRoleEnum.PRESIDENT, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_160:
                return getUsersByRoleAndRegion(UserRoleEnum.HUO_MA_EMPLOYEE, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_170:
                return getUsersByRoleAndRegion(UserRoleEnum.IT_EMPLOYEE, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_230:
                return getUsersByRoleAndRegion(UserRoleEnum.XIN_FA_SYS_CUSTOMER, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_240:
                return getUsersByRoleAndRegion(UserRoleEnum.TENT_PASS_CUSTOMER, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_181:
                return getUsersByRoleAndRegion(DOU_YIN_CUSTOMER, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_191:
                return getUsersByRoleAndRegion(UserRoleEnum.MEI_TUAN_OPERATIONS_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_193:
                return getUsersByRoleAndRegion(UserRoleEnum.MEI_TUAN_HEADQUARTERS_BUILD_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_201:
                return getUsersByRoleAndRegion(UserRoleEnum.MEI_TUAN_BUY_CUSTOMER, shopInfo.getRegionId());

            case SHOP_SUB_STAGE_STATUS_211:
                return getUsersByRoleAndRegion(UserRoleEnum.E_L_ME_TUAN_OPERATIONS_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_213:
                return getUsersByRoleAndRegion(UserRoleEnum.E_L_ME_HEADQUARTERS_BUILD_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_221:
                return getUsersByRoleAndRegion(UserRoleEnum.KUAI_SHOU_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_251:
                return getUsersByRoleAndRegion(UserRoleEnum.JING_DONG_OPERATIONS_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_253:
                return getUsersByRoleAndRegion(UserRoleEnum.JING_DONG_HEADQUARTERS_BUILD_CUSTOMER, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_272:
                return getUsersByRoleAndRegion(OPERATION_GENERAL_CONSULTANT, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_172:
                return getUsersByRoleAndRegion(ORDER_GROUP, shopInfo.getRegionId());
            case SHOP_SUB_STAGE_STATUS_281:
                return getUsersByRole(AI_STORE_TYPE_APPROVE);
            case SHOP_SUB_STAGE_STATUS_281_2:
                return getUsersByRole(DEVICE_SHIPMENT_CG);
            default:
                return Collections.emptyList();
        }
    }

    @Override
    public ShopStageInfoVO getShopStageStatus(Long shopId, Integer subStage) {
        if (shopId == null || subStage == null) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        ShopStageInfoDO stage = shopStageInfoDAO.getByShopIdAndSubStage(shopId, subStage);
        if (stage != null) {
            return new ShopStageInfoVO(stage.getShopStage(), stage.getShopSubStage(), stage.getShopSubStageStatus(), stage.getIsTerminated());
        }
        return null;
    }

    @Override
    public Boolean checkShopCodeRepeat(String shopCode, Long shopId) {
        //false 未重复, true 重复
        List<ShopInfoDO> shopListByShopCode = shopInfoDAO.getShopListByShopCode(shopCode);
        if (CollectionUtils.isEmpty(shopListByShopCode)){
            return false;
        }
        if (CollectionUtils.isNotEmpty(shopListByShopCode)&&shopId ==null){
            return true;
        }
        if (shopListByShopCode.size() == 1 && shopListByShopCode.get(0).getId().equals(shopId)){
            return false;
        }
        return true;
    }

    @Override
    public Boolean isShowButton(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        //店已关联HQT 不展示按钮
        if (StringUtils.isNotBlank(shopInfo.getHqtShopId())){
            return false;
        }
        return true;
    }

    @Override
    public Boolean submitOpenDateReport(OpenDateReportRequest request) {
        if (Objects.isNull(request.getShopId())||Objects.isNull(request.getOpenDate())){
            throw new ServiceException(PARAMS_VALIDATE_ERROR);
        }
        //查询门店
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        if (Objects.isNull(shopInfo)){
            throw new ServiceException(ErrorCodeEnum.STORE_NOT_FIND);
        }
        shopInfo.setPlanOpenDate(request.getOpenDate());
        shopInfoDAO.updateShopInfo(shopInfo);
        //阶段状态变为待确定
        shopStageInfoDAO.updateShopStageInfo(request.getShopId(),ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_310);

        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());

        HashMap<String, String> map = new HashMap<>();
        map.put("partnerUsername", lineInfo.getUsername());
        map.put("storeName", shopInfo.getShopName());
        map.put("planOpenDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,shopInfo.getPlanOpenDate()));
        map.put("shopAddress", shopInfo.getDetailAddress());
        commonService.sendQWMessage(Collections.singletonList(shopInfo.getOperationsConsultant()),
                MessageEnum.MESSAGE_63, map);
        //新增
        List<EnterpriseUserDO> sendUsers = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.OPERATION_GENERAL_CONSULTANT, shopInfo.getRegionId());
        if (CollectionUtils.isNotEmpty(sendUsers)){
            List<String> userIdList = sendUsers.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList());
            commonService.sendTextMessage(userIdList,MessageEnum.MESSAGE_100,map);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean confirmOpen(OpenDateReportRequest request,String userId) {
        log.info("confirmOpen_request:{}",JSONObject.toJSONString(request));
        if (Objects.isNull(request.getShopId())||Objects.isNull(request.getOpenDate())){
            throw new ServiceException(PARAMS_VALIDATE_ERROR);
        }
        //查询门店
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        if (Objects.isNull(shopInfo)){
            throw new ServiceException(ErrorCodeEnum.STORE_NOT_FIND);
        }
        //只能运营顾问操作
        if (StringUtils.isNotEmpty(shopInfo.getOperationsConsultant())&&!shopInfo.getOperationsConsultant().equals(userId)){
            throw new ServiceException(ErrorCodeEnum.NO_OPERATIONS_CONSULTANT);
        }
        shopInfo.setActualOpenDate(request.getOpenDate());
        shopInfoDAO.updateShopInfo(shopInfo);
        //阶段状态变为带确定
        shopStageInfoDAO.updateShopStageInfo(request.getShopId(),ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_320);
        //更新门店为开业状态 且使用开业日期
        StoreDO store = storeDao.getByStoreNum(shopInfo.getShopCode());
        if (store!=null){
            storeDao.updateStoreStatus(store.getStoreId(),"open",request.getOpenDate());
        }
        return Boolean.TRUE;
    }

    @Override
    public OpenInfoDTO getShopOpenInfo(Long shopId) {
        if (Objects.isNull(shopId)){
            throw new ServiceException(PARAMS_VALIDATE_ERROR);
        }
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)){
            throw new ServiceException(ErrorCodeEnum.STORE_NOT_FIND);
        }
        OpenInfoDTO openInfoDTO = new OpenInfoDTO();
        openInfoDTO.setShopId(shopId);
        openInfoDTO.setPlanOpenDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,shopInfo.getPlanOpenDate()));
        openInfoDTO.setActualOpenDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,shopInfo.getActualOpenDate()));
        return openInfoDTO;
    }

    /**
     * 获取招商经理信息
     * @param
     * @return
     */
    private List<UserDTO> getUserFromInvestmentManager(String userId) {
        EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(userId);
        if (userInfo != null) {
            return Collections.singletonList(new UserDTO(userInfo.getName(), userInfo.getMobile()));
        }
        return Collections.emptyList();
    }

    private List<UserDTO> getUserById(String userId) {
        EnterpriseUserDO user = enterpriseUserDAO.getUserInfoById(userId);
        if (user != null) {
            return Collections.singletonList(new UserDTO(user.getName(), user.getMobile()));
        }
        return Collections.emptyList();
    }

    private List<UserDTO> getUsersByRole(UserRoleEnum role) {
        SysRoleRequest request = new SysRoleRequest();
        request.setRoleName(role.getDesc());
        return convertToUserDTOs(userAuthMappingService.findUserListByRole(request, false));
    }

    private List<UserDTO> getUsersByRoleAndRegion(UserRoleEnum role, Long regionId) {
        return convertToUserDTOs(userAuthMappingService.getAllUserByRoleEnumAndRegionId(role, regionId));
    }

    private List<UserDTO> getUsersByRolesAndRegion(List<UserRoleEnum> roles, Long regionId) {
        return convertToUserDTOs(userAuthMappingService.getUserIdByRoleEnumAndRegionId(roles, regionId));
    }

    private List<UserDTO> convertToUserDTOs(List<EnterpriseUserDO> users) {
        //最多给10条数据
        return users.stream()
                .map(user -> new UserDTO(user.getName(), user.getMobile()))
                .limit(10)
                .collect(Collectors.toList());
    }


}
