package com.cool.store.service.impl;

import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dto.Preparation.PreparationDTO;
import com.cool.store.dto.Preparation.ScheduleDTO;
import com.cool.store.dto.decoration.ConstructionScheduleDTO;
import com.cool.store.dto.decoration.DecorationDTO;
import com.cool.store.dto.decoration.ProjectDTO;
import com.cool.store.dto.openPreparation.OpenPlanShopInfoDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.MessageEnum;
import com.cool.store.enums.SMSMsgEnum;
import com.cool.store.enums.point.ShopStageEnum;
import com.cool.store.enums.point.ShopSubStageEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.PreparationRequest;
import com.cool.store.service.*;
import com.cool.store.utils.poi.DateUtils;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.utils.poi.constant.Constants;
import com.cool.store.vo.Preparation.PreparationProcessVO;
import com.cool.store.vo.Preparation.PreparationScheduleDetailVO;
import com.cool.store.vo.Preparation.PreparationScheduleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author suzhuhong
 * @Date 2024/4/22 16:21
 * @Version 1.0
 */
@Service
public class PreparationServiceImpl implements PreparationService {

    private static final Logger log = LoggerFactory.getLogger(PreparationServiceImpl.class);
    @Resource
    private CommonService commonService;
    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    private OpenAcceptanceInfoDAO openAcceptanceInfoDAO;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private UserAuthMappingService userAuthMappingService;
    @Resource
    private RegionService regionService;
    @Resource
    ShopInfoDAO shopInfoDAO;
    @Resource
    EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    LineInfoDAO lineInfoDAO;
    @Resource
    private AcceptanceInfoDAO acceptanceInfoDAO;
    @Resource
    private DecorationService decorationService;

    @Override
    public PageInfo<PreparationScheduleVO> getPreparationSchedule(PreparationRequest request) {
        if (!sysRoleService.checkIsAdmin(request.getCurUserId())) {
            request.setAuthRegionIds(userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(request.getCurUserId()));
        }
        if (CollectionUtils.isNotEmpty(request.getRegionIds())) {
            if (request.getRegionIds().contains(CommonConstants.ROOT_DEPT_ID_STR)) {
                request.setRegionIds(null);
            } else {
                request.setRegionIds(regionService.getSubRegionIdsByRegionIds(request.getRegionIds()));
            }
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        //开业进度数据
        List<PreparationDTO> preparationDTOS = shopInfoDAO.ListByCondition(request);
        PageInfo pageInfo = new PageInfo<>(preparationDTOS);
        List<Long> shopIds = preparationDTOS.stream().map(PreparationDTO::getId).collect(Collectors.toList());
        List<ScheduleDTO> scheduleList = shopStageInfoDAO.getScheduleList(shopIds);
        List<ShopStageInfoDO> shopContractActualCompletionTime = shopStageInfoDAO.getShopContractActualCompletionTime(shopIds);
        Map<Long, ScheduleDTO> scheduleDTOMap = scheduleList.stream().collect(Collectors.toMap(ScheduleDTO::getShopId, x -> x));
        Map<Long, ShopStageInfoDO> shopStageInfoDOMap = shopContractActualCompletionTime.stream().collect(Collectors.toMap(ShopStageInfoDO::getShopId, x -> x));
        List<Long> regionIds = preparationDTOS.stream().map(PreparationDTO::getRegionId).collect(Collectors.toList());
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIds);
        Set<String> userIds = preparationDTOS.stream().filter(x -> StringUtils.isNotEmpty(x.getShopManagerUserId())).map(PreparationDTO::getShopManagerUserId).collect(Collectors.toSet());
        userIds.addAll(preparationDTOS.stream().filter(x -> StringUtils.isNotEmpty(x.getInvestmentManager())).map(PreparationDTO::getInvestmentManager).collect(Collectors.toSet()));
        userIds.addAll(preparationDTOS.stream().filter(x -> StringUtils.isNotEmpty(x.getSupervisorUserId())).map(PreparationDTO::getSupervisorUserId).collect(Collectors.toSet()));
        Map<String, EnterpriseUserDO> userInfoMap = enterpriseUserDAO.getUserInfoMap(new ArrayList<>(userIds));

        List<PreparationScheduleVO> preparationScheduleVOS = new ArrayList<>();
        preparationDTOS.forEach(x -> {
            PreparationScheduleVO preparationScheduleVO = new PreparationScheduleVO();
            preparationScheduleVO.setMobile(x.getMobile());
            preparationScheduleVO.setUsername(x.getUsername());
            preparationScheduleVO.setShopId(x.getId());
            preparationScheduleVO.setLineId(x.getLineId());
            preparationScheduleVO.setShopName(x.getShopName());
            preparationScheduleVO.setShopCode(x.getShopCode());
            preparationScheduleVO.setPlanOpenTime(x.getPlanOpenTime());
            preparationScheduleVO.setStoreNum(x.getStoreNum());
            preparationScheduleVO.setShopManagerUserName(userInfoMap.getOrDefault(x.getShopManagerUserId(), new EnterpriseUserDO()).getName());
            preparationScheduleVO.setSupervisionName(userInfoMap.getOrDefault(x.getSupervisorUserId(), new EnterpriseUserDO()).getName());
            preparationScheduleVO.setInvestmentManagerName(userInfoMap.getOrDefault(x.getInvestmentManager(), new EnterpriseUserDO()).getName());
            preparationScheduleVO.setRegionNodeName(regionNameMap.getOrDefault(x.getRegionId(), ""));
            ScheduleDTO dto = scheduleDTOMap.getOrDefault(x.getId(), new ScheduleDTO());
            preparationScheduleVO.setCompletionColumn(dto.getCompletionColumn());
            //-1 去掉视觉验收
            preparationScheduleVO.setTotalColumn(dto.getTotalColumn());
            ShopStageInfoDO stageInfoDO = shopStageInfoDOMap.getOrDefault(x.getId(), new ShopStageInfoDO());
            if (StringUtils.isNotEmpty(stageInfoDO.getActualCompleteTime())) {
                preparationScheduleVO.setContractCompletionTime(DateUtils.strToDate(stageInfoDO.getActualCompleteTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            }
            preparationScheduleVO.setDays();
            preparationScheduleVOS.add(preparationScheduleVO);
        });
        pageInfo.setList(preparationScheduleVOS);
        return pageInfo;
    }

    @Override
    public PreparationScheduleDetailVO getPreparationDetail(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (shopInfo == null) {
            throw new ServiceException(ErrorCodeEnum.SHOP_ID_IS_NULL);
        }
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());

        List<ScheduleDTO> shopContractActualCompletionTime = shopStageInfoDAO.getScheduleList(Collections.singletonList(shopId));
        PreparationScheduleDetailVO preparationScheduleDetailVO = new PreparationScheduleDetailVO();
        List<ShopStageInfoDO> shop = shopStageInfoDAO.getShopContractActualCompletionTime(Collections.singletonList(shopId));
        Set<Object> userSet = new HashSet<>();
        if (StringUtils.isNotEmpty(lineInfo.getInvestmentManager())) {
            userSet.add(lineInfo.getInvestmentManager());
        }
        if (StringUtils.isNotEmpty(lineInfo.getDevelopmentManager())) {
            userSet.add(lineInfo.getDevelopmentManager());
        }
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(Collections.singletonList(shopInfo.getRegionId()));
        Map<String, EnterpriseUserDO> userInfoMap = enterpriseUserDAO.getUserInfoMap(new ArrayList(userSet));
        preparationScheduleDetailVO.setShopId(shopId);
        preparationScheduleDetailVO.setUsername(lineInfo.getUsername());
        preparationScheduleDetailVO.setMobile(lineInfo.getMobile());
        preparationScheduleDetailVO.setJoinStatus(lineInfo.getJoinStatus());
        preparationScheduleDetailVO.setShopName(shopInfo.getShopName());
        preparationScheduleDetailVO.setShopCode(shopInfo.getShopCode());
        preparationScheduleDetailVO.setPlanOpenTime(shopInfo.getPlanOpenTime());
        preparationScheduleDetailVO.setStoreNum(shopInfo.getStoreNum());
        preparationScheduleDetailVO.setJoinStatus(lineInfo.getJoinStatus());
        if (CollectionUtils.isNotEmpty(shopContractActualCompletionTime)) {
            ScheduleDTO scheduleDTO = shopContractActualCompletionTime.get(CommonConstants.ZERO);
            preparationScheduleDetailVO.setCompletionColumn(scheduleDTO.getCompletionColumn());
            preparationScheduleDetailVO.setTotalColumn(scheduleDTO.getTotalColumn());
            preparationScheduleDetailVO.setPlanCompletionTime(scheduleDTO.getPlanCompleteTime());
        }
        if (CollectionUtils.isNotEmpty(shop)) {
            ShopStageInfoDO shopStageInfoDO = shop.get(CommonConstants.ZERO);
            preparationScheduleDetailVO.setContractCompletionTime(DateUtils.strToDate(shopStageInfoDO.getActualCompleteTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        EnterpriseUserDO developmentManager = userInfoMap.getOrDefault(lineInfo.getDevelopmentManager(), new EnterpriseUserDO());
        EnterpriseUserDO investmentManager = userInfoMap.getOrDefault(lineInfo.getInvestmentManager(), new EnterpriseUserDO());
        preparationScheduleDetailVO.setDevelopmentManagerName(developmentManager.getName());
        preparationScheduleDetailVO.setDevelopmentManagerMobile(developmentManager.getMobile());
        preparationScheduleDetailVO.setInvestmentManagerName(investmentManager.getName());
        preparationScheduleDetailVO.setInvestmentManagerMobile(investmentManager.getMobile());
        preparationScheduleDetailVO.setRegionNodeName(regionNameMap.get(shopInfo.getRegionId()));
        preparationScheduleDetailVO.setDays();
        return preparationScheduleDetailVO;
    }

    @Override
    public PreparationProcessVO getPreparationProcess(Long shopId) {
        PreparationProcessVO preparationProcess = shopStageInfoDAO.getPreparationProcess(shopId);
        if (preparationProcess == null){
            return null;
        }
        preparationProcess.setTotalCount(10);
        return preparationProcess;
    }

    @Override
    public void contractAndBuildStoreCompletion(Long shopId) {
        List<ShopStageInfoDO> shopStageInfo = shopStageInfoDAO.getShopStageInfo(shopId, null);
        if (CollectionUtils.isNotEmpty(shopStageInfo)) {
            Map<Integer, ShopStageInfoDO> shopStageInfoDOMap = shopStageInfo.stream().collect(Collectors.toMap(ShopStageInfoDO::getShopSubStage, data -> data));
            Boolean contractCompletionFlag = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_84.getShopSubStageStatus().equals(shopStageInfoDOMap.get(ShopSubStageEnum.SHOP_STAGE_8.getShopSubStage()).getShopSubStageStatus());
            //都完成了 初始化后续流程数据
            if (contractCompletionFlag) {
                //初始化后续流程数据s
                List<ShopSubStageStatusEnum> list = new ArrayList<>();
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_30);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_40);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_90);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_140);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_150);
                shopStageInfoDAO.batchUpdateShopStageStatus(shopId,list);
            }
        }
    }

    @Override
    public void sysStoreCompleted(Long shopId) {
        List<ShopStageInfoDO> shopStageInfo = shopStageInfoDAO.getShopStageInfo(shopId, null);
        if (CollectionUtils.isNotEmpty(shopStageInfo)) {
            Map<Integer, ShopStageInfoDO> shopStageInfoDOMap = shopStageInfo.stream().collect(Collectors.toMap(ShopStageInfoDO::getShopSubStage, data -> data));
            Boolean flag3 = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_153.getShopSubStageStatus().
                    equals(shopStageInfoDOMap.get(ShopSubStageEnum.SHOP_STAGE_15.getShopSubStage()).getShopSubStageStatus());
            if (flag3){
                List<ShopSubStageStatusEnum> list = new ArrayList<>();
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_160);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_170);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_230);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_240);
                shopStageInfoDAO.batchUpdateShopStageStatus(shopId,list);
            }
        }
    }

    @Override
    public void licenseCompleted(Long shopId) {
        List<ShopStageInfoDO> shopStageInfo = shopStageInfoDAO.getShopStageInfo(shopId, null);
        if (CollectionUtils.isNotEmpty(shopStageInfo)) {
            Map<Integer, ShopStageInfoDO> shopStageInfoDOMap = shopStageInfo.stream().collect(Collectors.toMap(ShopStageInfoDO::getShopSubStage, data -> data));
            Boolean flag1 = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_33.getShopSubStageStatus().
                    equals(shopStageInfoDOMap.get(ShopSubStageEnum.SHOP_STAGE_3.getShopSubStage()).getShopSubStageStatus());
            Boolean flag2 = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_43.getShopSubStageStatus().
                    equals(shopStageInfoDOMap.get(ShopSubStageEnum.SHOP_STAGE_4.getShopSubStage()).getShopSubStageStatus());
            Boolean flag3 = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_153.getShopSubStageStatus().
                    equals(shopStageInfoDOMap.get(ShopSubStageEnum.SHOP_STAGE_15.getShopSubStage()).getShopSubStageStatus());

            //都完成了 初始化后续流程数据
            if (flag1&&flag2&&flag3) {
                //初始化后续流程数据s
                List<ShopSubStageStatusEnum> list = new ArrayList<>();
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_180);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_190);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_200);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_210);
                list.add(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_220);
                shopStageInfoDAO.batchUpdateShopStageStatus(shopId,list);
                ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
                LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
                Map<String, String> templateParam = new HashMap<>();
                templateParam.put("shopName", shopInfo.getShopName());
                commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.PLATFORM_BUILD_STORE,templateParam);
            }
        }
    }

    @Override
    public void whetherToOpenForAcceptance(Long shopId) {

    }

    @Override
    public Boolean decorationFlush(Long shopId) {
        return Boolean.TRUE;
    }


}
