package com.cool.store.service.impl;

import com.cool.store.constants.CommonConstants;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dao.*;
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.entity.*;
import com.cool.store.enums.AuditResultTypeEnum;
import com.cool.store.enums.AuditTypeEnum;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.UserRoleEnum;
import com.cool.store.enums.point.ShopSubStageEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.LineInfoMapper;
import com.cool.store.mapper.ShopInfoMapper;
import com.cool.store.request.AcceptanceListRequest;
import com.cool.store.request.SeeAcceptanceRequest;
import com.cool.store.request.SeeAccetanceListRequest;
import com.cool.store.service.*;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.vo.fitmentCheckVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * @Auther: WangShuo
 * @Date: 2024/05/17/下午5:58
 * @Version 1.0
 * @注释:
 */
@Service
public class SeeAcceptanceServiceImpl implements SeeAcceptanceService {
    private static final Logger log = LoggerFactory.getLogger(SeeAcceptanceServiceImpl.class);
    @Resource
    private DecorationService decorationService;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private YlfService ylfService;
    @Resource
    private ShopAuditInfoDAO shopAuditInfoDAO;
    @Resource
    private TempUserDetailDAO tempUserDetailDAO;
    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    private PreparationService preparationService;
    @Resource
    private UserAuthMappingService userAuthMappingService;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private LineInfoMapper lineInfoMapper;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private RegionService regionService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private AcceptanceInfoDAO acceptanceInfoDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditSeeAcceptance(SeeAcceptanceRequest request, LoginUserInfo user) {
        if (request.getShopId() == null || request.getShopId() == 0) {
            throw new ServiceException(ErrorCodeEnum.SHOP_ID_IS_NULL);
        }
        if (request.getResultType() == null) {
            throw new ServiceException(ErrorCodeEnum.SEE_ACCEPTANCE_AUDIT_NULL);
        }
        if (Objects.isNull(user)) {
            throw new ServiceException(ErrorCodeEnum.USER_NOT_LOGIN);
        }

        ShopAuditInfoDO shopAuditInfoDO = new ShopAuditInfoDO();
        shopAuditInfoDO.setShopId(request.getShopId());
        shopAuditInfoDO.setAuditType(AuditTypeEnum.VISUAL_ACCEPTANCE.getCode());
        shopAuditInfoDO.setSubmittedUserId(user.getUserId());
        shopAuditInfoDO.setSubmittedUserName(user.getName());
        shopAuditInfoDO.setResultType(request.getResultType());
        if (AuditResultTypeEnum.PASS.getCode().equals(request.getResultType())) {
            shopAuditInfoDO.setPassReason(request.getReason());
        } else {
            shopAuditInfoDO.setRejectReason(request.getReason());
        }
        shopAuditInfoDO.setCreateTime(new Date());
        shopAuditInfoDO.setDataType(CommonConstants.ONE);
        Long id = shopAuditInfoDAO.addAuditInfo(shopAuditInfoDO);
        if (AuditResultTypeEnum.PASS.getCode().equals(request.getResultType())) {
            shopStageInfoDAO.updateShopStageAndAuditInfo(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_132, id);
            preparationService.whetherToOpenForAcceptance(request.getShopId());
        } else {
            shopStageInfoDAO.updateShopStageAndAuditInfo(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_131, id);
        }
        return true;
    }

    @Override
    public ConstructionScheduleDTO getWithdrawal(Long shopId) {
        DecorationDTO decoration = getDecorationDTO(shopId);
        if (decoration == null) {
            log.error("DecorationModel  is null");
            return null;
        }
        ConstructionScheduleDTO constructionScheduleDTO = new ConstructionScheduleDTO();
        List<ConstructionScheduleDTO> constructionSchedule = decoration.getConstructionSchedule();
        for (ConstructionScheduleDTO a : constructionSchedule) {
            if (CommonConstants.WITHDRAWAL.equals(a.getName())) {
                constructionScheduleDTO = a;
            }
        }
        if (Objects.isNull(constructionScheduleDTO)) {
            throw new ServiceException(ErrorCodeEnum.SEE_ACCEPTANCE_ERROR);
        }
        return constructionScheduleDTO;

    }

    @Override
    public List<ShopAuditInfoDO> getAuditInfo(Long shopId) {
        return shopAuditInfoDAO.getAuditList(shopId, AuditTypeEnum.VISUAL_ACCEPTANCE.getCode());
    }

    @Override
    public PageInfo<fitmentCheckVO> getAcceptanceList(AcceptanceListRequest request, LoginUserInfo user) {
        List<String> authRegionIds = userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(user.getUserId());
        List<Long> regions = new ArrayList<>();
        for (String authRegionId : authRegionIds) {
            regions.add(Long.parseLong(authRegionId));
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        if (regions.isEmpty()) {
            log.info("该用户下权限没有管理区域");
            return new PageInfo<>();
        }
        List<fitmentCheckVO> fitmentCheckVOList = new ArrayList<>();
        //shopId,lineid,regionid,shopname,storenum,

        List<ShopInfoDO> shopInfoDOS = shopInfoMapper.selectShopListByRegionId(regions, ShopSubStageEnum.SHOP_STAGE_13.getShopSubStage(),request.getSubStageStatus(),request.getKeyWord());
        PageInfo pageInfo = new PageInfo<>(shopInfoDOS);
        if (shopInfoDOS.isEmpty()) {
            log.info("该工程部监理下门店为空");
            return pageInfo;
        }
        Map<Long, ShopInfoDO> ShopIdmap = shopInfoDOS.stream().collect(Collectors.toMap(ShopInfoDO::getId, dto1 -> dto1));
        //招商经理，选址人员（拓展经理）id
        List<Long> lineIds = shopInfoDOS.stream().filter(o -> o.getLineId() != null)
                .map(ShopInfoDO::getLineId).distinct().collect(Collectors.toList());
        List<LineInfoDO> lineInfos = lineInfoMapper.getByLineIds(lineIds);
        Map<Long, LineInfoDO> lineInfoDOMap = lineInfos.stream().collect(Collectors.toMap(LineInfoDO::getId, dto -> dto));
        //招商name
        List<String> userIds = new ArrayList<>();
        userIds.addAll(lineInfos.stream().filter(o -> o.getInvestmentManager() != null)
                .map(LineInfoDO::getInvestmentManager).distinct().collect(Collectors.toList()));
        //选址人员（拓展经理）name
        userIds.addAll(lineInfos.stream().filter(o -> o.getDevelopmentManager() != null)
                .map(LineInfoDO::getDevelopmentManager).distinct().collect(Collectors.toList()));
        Map<String, String> userNameMap = enterpriseUserDAO.getUserNameMap(userIds);
        //所属战区
        List<Long> regionIds = shopInfoDOS.stream().filter(o -> o.getRegionId() != null).
                map(ShopInfoDO::getRegionId).distinct().collect(Collectors.toList());
        Map<Long, String> regionNameMap = regionService.getBelongWarRegionNameMap(regionIds);
        //战区经理name
        Map<Long, String> fightManger = new HashMap<>();
        for (Long regionId : regionIds) {
            String fightMangerUserId = sysRoleService.getUserIdByRegionIdWithRolePriority(regionId, Arrays.asList(UserRoleEnum.THEATER_MANAGER));
            String userName = enterpriseUserDAO.getUserName(fightMangerUserId);
            fightManger.put(regionId, userName);
        }
        //施工实际完成实际
        List<Long> shopIds = new ArrayList<>(ShopIdmap.keySet());
        List<AcceptanceInfoDO> acceptanceInfoDOS = acceptanceInfoDAO.selectByShopIds(shopIds);
        Map<Long, AcceptanceInfoDO> acceptanceInfoDOSMap = acceptanceInfoDOS.stream()
                .collect(Collectors.toMap(AcceptanceInfoDO::getShopId, dto1 -> dto1));
        //验收状态
        List<ShopStageInfoDO> subStageList = shopStageInfoDAO.getSubStageList(shopIds, ShopSubStageEnum.SHOP_STAGE_13.getShopSubStage());
        List<Long> audits = subStageList.stream().filter(o -> o.getAuditId() != null).map(ShopStageInfoDO::getAuditId).collect(Collectors.toList());
        //验收时间
        List<ShopAuditInfoDO> auditInfoList = shopAuditInfoDAO.getAuditInfoList(audits);
        Map<Long, ShopAuditInfoDO> auditMap = auditInfoList.stream().filter(o -> o.getShopId() != null).collect(Collectors.toMap(ShopAuditInfoDO::getShopId, Function.identity()));

        Map<Long, ShopStageInfoDO> ShopStageInfoDOMap = subStageList.stream()
                .collect(Collectors.toMap(ShopStageInfoDO::getShopId, dto1 -> dto1));
        for (ShopInfoDO shopInfoDO : shopInfoDOS) {
            Long shopId = shopInfoDO.getId();
            Long lineId = shopInfoDO.getLineId();
            Long regionId = shopInfoDO.getRegionId();
            fitmentCheckVO fitmentCheckVO = new fitmentCheckVO();
            fitmentCheckVO.setShopId(shopId);
            fitmentCheckVO.setLineId(lineId);
            fitmentCheckVO.setShopName(shopInfoDO.getShopName());
            fitmentCheckVO.setStoreNum(shopInfoDO.getStoreNum());
            fitmentCheckVO.setRegionId(regionId);
            fitmentCheckVO.setRegion(regionNameMap.get(regionId));
            fitmentCheckVO.setFightManager(fightManger.get(regionId));
            if (lineId != null) {
                fitmentCheckVO.setInvestmentManagerId(lineInfoDOMap.get(lineId)
                        .getInvestmentManager());
                fitmentCheckVO.setInvestmentManager(userNameMap.get(lineInfoDOMap.get(lineId)
                        .getInvestmentManager()));
                fitmentCheckVO.setSitterId(lineInfoDOMap.get(lineId)
                        .getDevelopmentManager());
                fitmentCheckVO.setSitterName(userNameMap.get(lineInfoDOMap.get(lineId)
                        .getDevelopmentManager()));
                fitmentCheckVO.setPartnerName(lineInfoDOMap.get(lineId).getUsername());
            }
            AcceptanceInfoDO acceptanceInfoDO = acceptanceInfoDOSMap.get(shopId);
            if (shopId != null) {
                if (Objects.nonNull(acceptanceInfoDO)) {
                    fitmentCheckVO.setActualEndTime(acceptanceInfoDO.getConstructionCompletionTime());
                }
            }
            if (Objects.nonNull(auditMap.get(shopId))) {
                fitmentCheckVO.setAcceptanceTime(auditMap.get(shopId).getCreateTime());
            }
            if (Objects.nonNull(ShopStageInfoDOMap.get(shopId))) {
                fitmentCheckVO.setShopSubStageStatus(ShopStageInfoDOMap.get(shopId).getShopSubStageStatus());
            }
            fitmentCheckVOList.add(fitmentCheckVO);
        }
        pageInfo.setList(fitmentCheckVOList);
        return pageInfo;
    }



    private DecorationDTO getDecorationDTO(Long shopId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.SHOP_ID_NOT_EXIST);
        }
        String storeNum = shopInfo.getStoreNum();
        if (StringUtils.isNotEmpty(storeNum)) {
            ProjectDTO projectList = ylfService.getProjectList(storeNum);
            Long projectId = projectList.getProjectId();
            DecorationDTO decoration = ylfService.getDecoration(projectId);
            return decoration;
        }
        return null;
    }
}
