package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.common.PageBasicInfo;
import com.cool.store.dao.*;
import com.cool.store.dao.decoration.DecorationTeamConfigDAO;
import com.cool.store.dao.decoration.ShopDecorationAssignDAO;
import com.cool.store.dao.decoration.TeamAreaMappingDAO;
import com.cool.store.dto.ShopSignerInfoDTO;
import com.cool.store.dto.decoration.DecorationListDTO;
import com.cool.store.dto.decoration.DecorationTeamDTO;
import com.cool.store.dto.decoration.TeamAreaMappingDTO;
import com.cool.store.entity.*;
import com.cool.store.entity.decoration.DecorationTeamConfigDO;
import com.cool.store.entity.decoration.ShopDecorationAssignDO;
import com.cool.store.entity.decoration.TeamAreaMappingDO;
import com.cool.store.enums.Decoration.DecorationDescStatus;
import com.cool.store.enums.Decoration.DecorationUseSystemEnum;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.JoinModeEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.decoration.AddTeamRequest;
import com.cool.store.request.decoration.DecorationListRequest;
import com.cool.store.request.decoration.UpdateConstructionTeamRequest;
import com.cool.store.request.decoration.UpdateTeamRequest;
import com.cool.store.service.DecorationHandleService;
import com.cool.store.service.HqtAPIService;
import com.cool.store.service.SignFranchiseService;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.StringUtil;
import com.cool.store.utils.poi.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import springfox.documentation.service.ApiListing;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author suzhuhong
 * @Date 2025/10/29 15:55
 * @Version 1.0
 */
@Service
@Slf4j
public class DecorationHandleServiceImpl implements DecorationHandleService {


    @Resource
    private DecorationTeamConfigDAO decorationTeamConfigDAO;
    @Resource
    private TeamAreaMappingDAO teamAreaMappingDAO;
    @Resource
    ShopDecorationAssignDAO shopDecorationAssignDAO;
    @Resource
    RedisUtilPool redisUtilPool;
    @Resource
    private HqtAPIService hqtAPIService;
    @Resource
    ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    ShopInfoDAO shopInfoDAO;
    @Resource
    SignFranchiseService signFranchiseService;
    @Resource
    RegionDao regionDao;
    @Resource
    LineInfoDAO lineInfoDAO;
    @Resource
    private SignFranchiseDAO signFranchiseDAO;

    @Override
    public Boolean addTeam(AddTeamRequest request) {
        //校验
        if (Objects.isNull(request)||CollectionUtils.isEmpty(request.getOpenCityIdList()) || StringUtil.isEmpty(request.getTeamName())){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        //先删除城市团队关系
        teamAreaMappingDAO.deletedIds(request.getOpenCityIdList());

        DecorationTeamConfigDO decorationTeamConfigDO = new DecorationTeamConfigDO();
        decorationTeamConfigDO.setTeamName(request.getTeamName());
        decorationTeamConfigDO.setTeamCode(getNextNumber());
        decorationTeamConfigDO.setUseSystem(request.getUserSystem());
        decorationTeamConfigDAO.addTeam(decorationTeamConfigDO);
        teamAreaMappingDAO.batchInsert(decorationTeamConfigDO.getId(),request.getOpenCityIdList());
        return Boolean.TRUE;
    }

    @Override
    public Boolean update(UpdateTeamRequest request) {
        if (request.getId() == null||CollectionUtils.isEmpty(request.getOpenCityIdList()) || StringUtil.isEmpty(request.getTeamName())){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        DecorationTeamConfigDO teamConfigDO = decorationTeamConfigDAO.getById(request.getId());
        if (teamConfigDO==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        teamConfigDO.setTeamName(request.getTeamName());
        teamConfigDO.setUseSystem(request.getUserSystem());
        decorationTeamConfigDAO.updateTeam(teamConfigDO);
        //删除团队城市关系
        teamAreaMappingDAO.deletedByTeamId(teamConfigDO.getId());
        //新增更新之后的团队城市关系
        teamAreaMappingDAO.batchInsert(teamConfigDO.getId(),request.getOpenCityIdList());
        return Boolean.TRUE;
    }

    @Override
    public Boolean deleteByTeamId(Long teamId) {
        DecorationTeamConfigDO teamConfigDO = decorationTeamConfigDAO.getById(teamId);
        if (teamConfigDO==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        //查询当前团队是否有门店使用 有的话 不能删除
        Integer count = shopDecorationAssignDAO.countByTeamId(teamId);
        if (count != null && count > 0){
            throw new ServiceException(ErrorCodeEnum.TEAM_USED);
        }
        teamConfigDO.setDeleted(1);
        teamAreaMappingDAO.deletedByTeamId(teamId);
        decorationTeamConfigDAO.updateTeam(teamConfigDO);
        return Boolean.TRUE;
    }

    @Override
    public PageInfo<DecorationTeamDTO> listByCondition(PageBasicInfo pageBasicInfo) {
        PageHelper.startPage(pageBasicInfo.getPageNum(), pageBasicInfo.getPageSize());
        List<DecorationTeamDTO> list = decorationTeamConfigDAO.listByCondition();
        if (CollectionUtils.isEmpty(list)){
            return new PageInfo<>();
        }
        List<Long> teamIds = list.stream().map(DecorationTeamDTO::getId).collect(Collectors.toList());
        Map<Long, List<TeamAreaMappingDTO>> listMap = teamAreaMappingDAO.listByTeamIdList(teamIds);
        list.forEach(x->{
            x.setCityList(listMap.get(x.getId()));
        });
        PageInfo<DecorationTeamDTO> result = new PageInfo<>(list);
        return result;
    }

    @Override
    public Long getDecorationTeamIdByCityId(Long openCityId) {
        if (openCityId==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        TeamAreaMappingDO cityInfo = teamAreaMappingDAO.getByCityId(openCityId);
        if (Objects.isNull(cityInfo)){
            return null;
        }
        DecorationTeamConfigDO teamInfo = decorationTeamConfigDAO.getById(cityInfo.getTeamId());
        return teamInfo.getId();
    }

    @Override
    public Boolean handleDecorationTeam(ShopDecorationAssignDO shopDecorationAssign) {
        //先查询
        if (shopDecorationAssign == null){
            log.info("handleDecorationTeam_error data not exist");
            return Boolean.FALSE;
        }
        //如果门店是已经分配状态 则不能再次分配
        if (DecorationDescStatus.ASSIGNED.getCode().equals(shopDecorationAssign.getDecorationDescStatus())){
            log.info("handleDecorationTeam id:{},门店已分配", JSONObject.toJSONString(shopDecorationAssign));
        }
        //没有分配的门店 开始分配
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(shopDecorationAssign.getShopId());
        //查询装修团队
        DecorationTeamConfigDO teamInfo = decorationTeamConfigDAO.getById(shopDecorationAssign.getDecorationTeamId());
        if (teamInfo == null){
            log.info("handleDecorationTeam_error team not exist");
            return Boolean.FALSE;
        }
        //配置的系统是红圈通 且不是加盟公司自有店 则推送数据  也就是配置了crm或者是加盟公司自有店 走crm流程
        //2026开始 自有店也开始走红圈通
        // 已分配运营顾问的情况下推送
        if (teamInfo.getUseSystem().equals(DecorationUseSystemEnum.HQT.getCode()) && StringUtils.isNotBlank(shopInfoDO.getOperationsConsultant())){
            hqtAPIService.pushHqtBuild(signFranchiseService.getHqtBuildRequest(shopInfoDO.getId()));
        }
        shopDecorationAssign.setDecorationDescStatus(DecorationDescStatus.ASSIGNED.getCode());
        shopDecorationAssignDAO.update(shopDecorationAssign);
        //阶段
        shopStageInfoDAO.updateShopStageInfo(shopInfoDO.getId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_861);
        return Boolean.TRUE;
    }

    @Override
    public PageInfo<DecorationListDTO> getDecorationAssignList(DecorationListRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<DecorationListDTO> decorationListDTOS = shopDecorationAssignDAO.listByCondition(request);
        if (CollectionUtils.isEmpty(decorationListDTOS)){
            return new PageInfo<>();
        }
        Set<String> regionIds = decorationListDTOS.stream().map(DecorationListDTO::getRegionId).collect(Collectors.toSet());
        List<RegionDO> regionList = regionDao.getRegionByRegionIds(new ArrayList<>(regionIds));
        //转为map
        Map<String, String> regionMap = regionList.stream().collect(Collectors.toMap(RegionDO::getRegionId, RegionDO::getName));
        decorationListDTOS.forEach(x->{
            x.setRegionName(regionMap.get(x.getRegionId()));
        });
        return new PageInfo<>(decorationListDTOS);
    }

    @Override
    public ShopSignerInfoDTO getShopSignerInfo(Long shopId) {
        if (shopId==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (shopInfo == null){
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        ShopSignerInfoDTO shopSignerInfoDTO = new ShopSignerInfoDTO();
        shopSignerInfoDTO.setPartnershipSignatoryFirst(lineInfo.getUsername());
        shopSignerInfoDTO.setPartnershipSignatoryFirstMobile(lineInfo.getMobile());
        SignFranchiseDO signFranchiseDO = signFranchiseDAO.selectByShopId(shopId);
        if (signFranchiseDO!=null){
            shopSignerInfoDTO.setPartnershipSignatorySecond(signFranchiseDO.getPartnershipSignatorySecond());
            shopSignerInfoDTO.setPartnershipSignatorySecondMobile(signFranchiseDO.getPartnershipSignatorySecondMobile());
        }
        return shopSignerInfoDTO;
    }

    @Override
    public Boolean updateConstructionTeam(UpdateConstructionTeamRequest request) {
        //查询待分配门店信息
        ShopDecorationAssignDO shopDecorationAssign = shopDecorationAssignDAO.getById(request.getId());
        if (shopDecorationAssign == null){
            log.info("handleDecorationTeam_error data not exist");
            return Boolean.FALSE;
        }
        shopDecorationAssign.setDecorationTeamId(request.getTeamId());
        handleDecorationTeam(shopDecorationAssign);
        return Boolean.TRUE;
    }


    public String getNextNumber() {
        Long current = redisUtilPool.incrby("counter_key", 1);
        if (current == 1) {
            // 如果是第一次，重新设置为 1（因为 increment 从 0 开始）
            redisUtilPool.setString("counter_key", "1");
            current = 1L;
        }
        return String.format("TD%04d", current);
    }

}
