package com.ruoyi.project.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.enums.FileBuzType;
import com.ruoyi.common.enums.SerialNumberPrefix;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SpecialCharacterEscaper;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.business.domain.TbFile;
import com.ruoyi.project.business.domain.TcProject;
import com.ruoyi.project.business.domain.TjCivilEngineering;
import com.ruoyi.project.business.domain.TjElevator;
import com.ruoyi.project.business.domain.TjElevatorFloorPara;
import com.ruoyi.project.business.domain.TjElevatorParaDetail;
import com.ruoyi.project.business.domain.bo.civil.CivilElevatorAddBO;
import com.ruoyi.project.business.domain.bo.civil.EngineeringAddBO;
import com.ruoyi.project.business.domain.vo.Civil.CivilParam;
import com.ruoyi.project.business.domain.vo.Civil.EngineeringInfoVO;
import com.ruoyi.project.business.domain.vo.Civil.TjCivilEngineeringVo;
import com.ruoyi.project.business.domain.vo.Civil.TjElevatorVo;
import com.ruoyi.project.business.domain.vo.selectParam.CivilEngineeringParam;
import com.ruoyi.project.business.enums.DelFlagEnum;
import com.ruoyi.project.business.enums.PlotStatusEnum;
import com.ruoyi.project.business.mapper.TbFileMapper;
import com.ruoyi.project.business.mapper.TcProjectMapper;
import com.ruoyi.project.business.mapper.TjCivilEngineeringMapper;
import com.ruoyi.project.business.mapper.TjElevatorMapper;
import com.ruoyi.project.business.mapper.TjElevatorParaDetailMapper;
import com.ruoyi.project.business.service.ITcLeadService;
import com.ruoyi.project.business.service.ITjCivilEngineeringService;
import com.ruoyi.project.business.service.ITjElevatorFloorParaService;
import com.ruoyi.project.business.service.quotation.ITqQuotationService;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【土建出图】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-20
 */
@Service
@Slf4j
public class TjCivilEngineeringServiceImpl implements ITjCivilEngineeringService {

    private static final List<String> ALLOW_STATUS_LIST = Arrays.asList("2", "3");

    @Resource
    private TjCivilEngineeringMapper tjCivilEngineeringMapper;

    @Resource
    private TjElevatorMapper tjElevatorMapper;

    @Resource
    private TjElevatorParaDetailMapper tjElevatorParaDetailMapper;

    @Resource
    private ITjElevatorFloorParaService tjElevatorFloorParaService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private TbFileMapper tbFileMapper;

    @Resource
    private ITcLeadService tcLeadService;

    @Resource
    private ITqQuotationService tqQuotationService;

    @Resource
    private TcProjectMapper tcProjectMapper;

    /**
     * 查询【土建出图】
     *
     * @param id 【土建出图】主键
     * @return 【土建出图】
     */
    @Override
    public EngineeringInfoVO selectTjCivilEngineeringById(Long id) {
        CivilEngineeringParam param =new CivilEngineeringParam();

        param.setPermissionChar(SecurityUtils.getPermissionCharIns());
        param.setId(id);
        List<TjCivilEngineering> tjCivilEngineerings = tjCivilEngineeringMapper.selectTjCivilEngineeringList(
                param);
        if(ObjectUtils.isEmpty(tjCivilEngineerings)){
            throw new ServiceException(MessageUtils.message("common.data.noPermession"));
        }

        EngineeringInfoVO tjCivilEngineering = tjCivilEngineeringMapper.selectTjCivilEngineeringById(id);
        // 查询土建出图关联电梯
        List<TjElevatorVo> tjElevators = tjElevatorMapper.selectElevatorListByCivilEngineeringId(id, null);
        List<Long> elevatorIds = tjElevators.stream().map(TjElevatorVo::getId).collect(Collectors.toList());
        // 查询土建出图关联电梯的所有参数
        List<TjElevatorParaDetail> detailList = tjElevatorParaDetailMapper.selectByElevatorIds(elevatorIds);
        // 查询关联的楼层参数
        List<TjElevatorFloorPara> floorParaList = tjElevatorFloorParaService.list(
            Wrappers.<TjElevatorFloorPara>lambdaQuery()
                .in(TjElevatorFloorPara::getElevatorId, elevatorIds)
                .eq(TjElevatorFloorPara::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        // 根据电梯id分组参数
        tjElevators.forEach(elevator -> {
            elevator.setParamList(
                detailList.stream()
                    .filter(detail -> detail.getElevatorId().equals(elevator.getId()))
                    .collect(Collectors.toList())
            );
            elevator.setFloorParamList(
                floorParaList.stream()
                    .filter(detail -> detail.getElevatorId().equals(elevator.getId()))
                    .collect(Collectors.toList())
            );
        });
        tjCivilEngineering.setElevatorList(tjElevators);

        return tjCivilEngineering;
    }

    /**
     * 查询【土建出图】列表
     *
     * @param tjCivilEngineering 【土建出图】
     * @return 【土建出图】
     */
    @Override
    public PageInfo<TjCivilEngineering> selectTjCivilEngineeringList(CivilEngineeringParam tjCivilEngineering) {
        SpecialCharacterEscaper.escapeSpecialCharacters(tjCivilEngineering
            , CivilEngineeringParam::getProjectNo
            , CivilEngineeringParam::getProjectName
            , CivilEngineeringParam::getCivilEngineeringNo
            , CivilEngineeringParam::getQuotationNo
        );
        tjCivilEngineering.setPermissionChar(SecurityUtils.getPermissionCharIns());
        SpecialCharacterEscaper.escapeSpecialCharacters(tjCivilEngineering, CivilEngineeringParam::getProjectNo,
            CivilEngineeringParam::getProjectName,
            CivilEngineeringParam::getCivilEngineeringNo, CivilEngineeringParam::getQuotationNo,
            CivilEngineeringParam::getElevatorModel);
        List<TjCivilEngineering> tjCivilEngineerings = tjCivilEngineeringMapper.selectTjCivilEngineeringList(
            tjCivilEngineering);
        // 设置土建出图的文件
        PageInfo<TjCivilEngineering> tjCivilEngineeringPageInfo = new PageInfo<>(tjCivilEngineerings);
        List<TjCivilEngineering> list = tjCivilEngineeringPageInfo.getList();
        List<Long> civilIdList = list.stream().filter(a -> a.getStatus().equals("2"))
            .map(TjCivilEngineering::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(civilIdList)) {
            List<TbFile> tbFiles = tbFileMapper.selectList(
                Wrappers.<TbFile>lambdaQuery()
                    .eq(TbFile::getBusinessType, FileBuzType.CIVIL_PIC_DRAWING.getType())
                    .in(TbFile::getBusinessId, civilIdList)
            );
            if (CollUtil.isNotEmpty(tbFiles)) {
                Map<Long, List<TbFile>> tbFileMap = tbFiles.stream()
                    .collect(Collectors.groupingBy(TbFile::getBusinessId));
                list.forEach(item -> {
                    List<TbFile> itemTbFileList = tbFileMap.get(item.getId());
                    if (CollUtil.isNotEmpty(itemTbFileList)) {
                        for (TbFile tbFile : itemTbFileList) {
                            if (tbFile.getFilePath().endsWith(".pdf")) {
                                item.setPdfFilePath(tbFile.getFilePath());
                            } else if (tbFile.getFilePath().endsWith(".dwg")) {
                                item.setDwgFilePath(tbFile.getFilePath());
                            } else {
                                log.info("土建出图文件异常 {}", JSONUtil.parse(tbFile).toStringPretty());
                            }
                        }
                    }
                });
            }
        }
        return tjCivilEngineeringPageInfo;
    }

    /**
     * 新增【土建出图】
     *
     * @param addBO 【土建出图】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTjCivilEngineering(EngineeringAddBO addBO) {
        List<Pair<Long, String>> collect = addBO.getElevatorList()
            .stream()
            .map(item -> Pair.of(item.getElevatorModelId(), item.getElevatorModel()))
            .collect(Collectors.toList());
        TcProject tcProjects = tcProjectMapper.selectTcProjectByProjectId(addBO.getProjectId());
        if (Objects.nonNull(tcProjects)) {
            tqQuotationService.checkAreaElevatorCorrelation(tcProjects.getCountryId(), collect);
        } else {
            log.info("项目不存在 [{}]", addBO.getProjectId());
        }

        // 土建出图编号
        addBO.setCivilEngineeringNo(redisCache.generateSerialNumber(SerialNumberPrefix.CE.getPrefix()));
        // 默认出图状态为出图中
        addBO.setStatus(PlotStatusEnum.PROGRESSING.getValue());
        addBO.setPermissionChar(SecurityUtils.getPermissionCharIns());
        String userId = SecurityUtils.getStrUserId();
        addBO.setCreateBy(userId);
        addBO.setUpdateBy(userId);
        Date nowDate = DateUtils.getNowDate();
        addBO.setCreateTime(nowDate);
        addBO.setUpdateTime(nowDate);
        TjCivilEngineering tjCivilEngineering = new TjCivilEngineering();
        BeanUtils.copyProperties(addBO, tjCivilEngineering);
        int result = tjCivilEngineeringMapper.insertTjCivilEngineering(tjCivilEngineering);
        List<CivilElevatorAddBO> elevatorList = addBO.getElevatorList();
        elevatorList.forEach(elevator -> {
            elevator.setCivilEngineeringId(tjCivilEngineering.getId());
            elevator.setCreateBy(userId);
            elevator.setCreateTime(nowDate);
            // 土建的电梯数量默认是1
            elevator.setQuantity(1L);
            // 新增电梯
            TjElevator tjElevator = new TjElevator();
            BeanUtils.copyProperties(elevator, tjElevator);
            tjElevatorMapper.insertTjElevator(tjElevator);
            // 电梯参数
            List<TjElevatorParaDetail> paramList = elevator.getParamList();
            if (CollUtil.isNotEmpty(paramList)) {
                paramList.forEach(param -> {
                    param.setId(null);
                    param.setElevatorId(tjElevator.getId());
                    param.setDelFlag(DelFlagEnum.NORMAL.getValue());
                    param.setCreateBy(userId);
                    param.setUpdateBy(userId);
                    param.setCreateTime(nowDate);
                    param.setUpdateTime(nowDate);
                });
                tjElevatorParaDetailMapper.batchInsertTjElevatorParaDetail(paramList);
            }

            // 楼层参数
            List<TjElevatorFloorPara> floorParamList = elevator.getFloorParamList();
            if (CollUtil.isNotEmpty(floorParamList)) {
                floorParamList.forEach(param -> {
                    param.setId(null);
                    param.setElevatorId(tjElevator.getId());
                    param.setDelFlag(DelFlagEnum.NORMAL.getValue());
                    param.setCreateBy(userId);
                    param.setUpdateBy(userId);
                    param.setCreateTime(nowDate);
                    param.setUpdateTime(nowDate);
                });
                tjElevatorFloorParaService.saveBatch(floorParamList);
            }

        });
        tcLeadService.convertQuotationFromProject(addBO.getProjectId(), addBO.getQuotationId());
        return result;
    }

    /**
     * 修改【土建出图】
     *
     * @param tjCivilEngineering 【土建出图】
     * @return 结果
     */
    @Override
    public int updateTjCivilEngineering(TjCivilEngineering tjCivilEngineering) {
        tjCivilEngineering.setUpdateTime(DateUtils.getNowDate());
        return tjCivilEngineeringMapper.updateTjCivilEngineering(tjCivilEngineering);
    }

    /**
     * 批量删除【土建出图】
     *
     * @param ids 需要删除的【土建出图】主键
     * @return 结果
     */
    @Override
    public int deleteTjCivilEngineeringByIds(Long[] ids) {
        return tjCivilEngineeringMapper.deleteTjCivilEngineeringByIds(ids);
    }

    /**
     * 删除【土建出图】信息
     *
     * @param id 【土建出图】主键
     * @return 结果
     */
    @Override
    public int deleteTjCivilEngineeringById(Long id) {
        return tjCivilEngineeringMapper.deleteTjCivilEngineeringById(id);
    }

    @Override
    public List<TjCivilEngineeringVo> getOutList() {
        return tjCivilEngineeringMapper.getOutList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(CivilParam tjCivilEngineering) {
        log.info("土建出图回调处理：" + JSONUtil.toJsonStr(tjCivilEngineering));
        if (!ALLOW_STATUS_LIST.contains(tjCivilEngineering.getStatus())) {
            throw new ServiceException("status not allowed");
        }

        //保存图片
        TbFile fileJPG = new TbFile();
        fileJPG.setBusinessId(tjCivilEngineering.getId());
        fileJPG.setBusinessType(FileBuzType.CIVIL_PIC_DRAWING.getType());
        fileJPG.setRealFileName(tjCivilEngineering.getFileName());
        fileJPG.setServerFileName(tjCivilEngineering.getFileName());
        fileJPG.setFilePath(tjCivilEngineering.getFileName());
        fileJPG.setCreateBy("1");
        fileJPG.setCreateTime(new Date());
        tbFileMapper.insertTbFile(fileJPG);
        TbFile filePDF = new TbFile();
        filePDF.setBusinessId(tjCivilEngineering.getId());
        filePDF.setBusinessType(FileBuzType.CIVIL_PIC_DRAWING.getType());
        filePDF.setRealFileName(tjCivilEngineering.getFilePathPDF());
        filePDF.setServerFileName(tjCivilEngineering.getFilePathPDF());
        filePDF.setFilePath(tjCivilEngineering.getFilePathPDF());
        filePDF.setCreateBy("1");
        filePDF.setCreateTime(new Date());
        tbFileMapper.insertTbFile(filePDF);
        return tjCivilEngineeringMapper.changeStatus(tjCivilEngineering);
    }
}
