package com.njcn.csdevice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.mapper.CsLedgerMapper;
import com.njcn.csdevice.mapper.CsTopologyDiagramTemplateMapper;
import com.njcn.csdevice.pojo.param.*;
import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csdevice.pojo.vo.EngineeringProjectRelationVo;
import com.njcn.csdevice.service.*;
import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.pojo.po.Area;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据集表 服务实现类
 * </p>
 *
 * @author xuyang
 * @since 2026-01-29
 */
@Service
@RequiredArgsConstructor
public class EngineeringProjectServiceImpl implements IEngineeringProjectService {

    private final CsEngineeringService csEngineeringService;
    private final AppProjectService appProjectService;
    private final ICsLedgerService csLedgerService;
    private final CsLedgerMapper csLedgerMapper;
    private final AppTopologyDiagramService appTopologyDiagramService;
    private final AreaFeignClient areaFeignClient;
    private final CsTopologyDiagramTemplateMapper csTopologyDiagramTemplateMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addEngineering(CsEngineeringAddParm csEngineeringAddParm) {
        boolean result = false;
        //新增工程信息
        CsEngineeringPO po1 = csEngineeringService.add(csEngineeringAddParm);
        //新增cs_ledger数据
        CsLedgerParam csLedgerParam = new CsLedgerParam();
        csLedgerParam.setId(po1.getId());
        csLedgerParam.setPid("9999999");
        csLedgerParam.setName(csEngineeringAddParm.getName());
        csLedgerParam.setLevel(0);
        csLedgerParam.setRemark(csEngineeringAddParm.getDescription());
        csLedgerParam.setSort(csEngineeringAddParm.getSort());
        CsLedger po2 = csLedgerService.addLedgerTree(csLedgerParam);
        if (ObjectUtil.isNotNull(po1) && ObjectUtil.isNotNull(po2)) {
            result = true;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEngineering(CsEngineeringAuditParm csEngineeringAuditParm) {
        //修改工程信息
        CsEngineeringPO po1 = csEngineeringService.updateData(csEngineeringAuditParm);
        //修改cs_ledger数据
        CsLedgerParam.Update csLedgerParam = new CsLedgerParam.Update();
        csLedgerParam.setId(po1.getId());
        csLedgerParam.setName(csEngineeringAuditParm.getName());
        csLedgerParam.setSort(csEngineeringAuditParm.getSort());
        csLedgerService.updateLedgerTree(csLedgerParam);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEngineering(String id) {
        //查询csledger数据
        List<CsLedgerVO> allList = csLedgerMapper.getAll();
        allList.forEach(item->{
            if (Objects.equals(item.getPid(),id)) {
                throw new BusinessException("请先删除该工程下的所有项目");
            }
        });
        //删除工程信息
        csEngineeringService.deleteData(id);
        //删除台账信息
        csLedgerService.deleteLedgerTree(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProject(AppProjectAddParm param) {
        boolean result = false;
        //新增项目信息
        AppProjectPO po1 = appProjectService.add(param);
        //新增cs_ledger数据
        CsLedgerParam csLedgerParam = new CsLedgerParam();
        csLedgerParam.setId(po1.getId());
        csLedgerParam.setPid(param.getEngineeringId());
        csLedgerParam.setName(param.getName());
        csLedgerParam.setLevel(1);
        csLedgerParam.setSort(param.getSort());
        CsLedger po2 = csLedgerService.addLedgerTree(csLedgerParam);
        if (ObjectUtil.isNotNull(po1) && ObjectUtil.isNotNull(po2)) {
            result = true;
        }
        //新增项目拓扑图
        if (CollectionUtil.isNotEmpty(param.getTopoIds())) {
            CsTopologyDiagramTemplate csTopologyDiagramTemplate = csTopologyDiagramTemplateMapper.selectById(param.getTopoIds().get(0));
            AppTopologyDiagramPO po3 = new AppTopologyDiagramPO();
            po3.setFilePath (csTopologyDiagramTemplate.getFilePath());
            po3.setProjectId (po1.getId());
            po3.setName (csTopologyDiagramTemplate.getName());
            po3.setStatus ("1");
            po3.setTopoId(param.getTopoIds().get(0));
            appTopologyDiagramService.save(po3);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProject(AppProjectAuditParm param) {
        //修改工程信息
        AppProjectPO po1 = appProjectService.updateData(param);
        //修改cs_ledger数据
        CsLedgerParam.Update csLedgerParam = new CsLedgerParam.Update();
        csLedgerParam.setId(po1.getId());
        csLedgerParam.setPid(param.getEngineeringId());
        csLedgerParam.setPids("0," + param.getEngineeringId());
        csLedgerParam.setName(param.getName());
        csLedgerParam.setRemark(param.getDescription());
        csLedgerParam.setSort(param.getSort());
        csLedgerService.updateLedgerTree(csLedgerParam);
        //修改项目拓扑图
        AppTopologyDiagramPO po2 = appTopologyDiagramService.getByProjectId(param.getId());
        if (ObjectUtil.isNotNull(po2)) {
            CsTopologyDiagramTemplate csTopologyDiagramTemplate = csTopologyDiagramTemplateMapper.selectById(param.getTopoIds().get(0));
            po2.setId(po2.getId());
            po2.setFilePath (csTopologyDiagramTemplate.getFilePath());
            po2.setName (csTopologyDiagramTemplate.getName());
            po2.setStatus ("1");
            po2.setTopoId(param.getTopoIds().get(0));
            appTopologyDiagramService.updateById(po2);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProject(String id) {
        //删除项目信息
        appProjectService.delete(id);
        //删除台账信息
        csLedgerService.deleteLedgerTree(id);
        //删除项目拓扑图
        AppTopologyDiagramPO po2 = appTopologyDiagramService.getByProjectId(id);
        if (ObjectUtil.isNotNull(po2)) {
            po2.setStatus("0");
            appTopologyDiagramService.updateById(po2);
        }
        return true;
    }

    @Override
    public List<EngineeringProjectRelationVo> getList() {
        List<EngineeringProjectRelationVo> result = new ArrayList<>();
        //查询所有工程
        LambdaQueryWrapper<CsEngineeringPO> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CsEngineeringPO::getStatus,"1").orderByAsc(CsEngineeringPO::getSort);
        List<CsEngineeringPO> list1 = csEngineeringService.list(queryWrapper1);

        //查询所有项目
        LambdaQueryWrapper<AppProjectPO> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(AppProjectPO::getStatus,"1").orderByAsc(AppProjectPO::getSort);
        List<AppProjectPO> list2 = appProjectService.list(queryWrapper2);
        Map<String,AppProjectPO> map = list2.stream().collect(Collectors.toMap(AppProjectPO::getId, item->item));

        //查询所有拓扑图
        LambdaQueryWrapper<AppTopologyDiagramPO> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(AppTopologyDiagramPO::getStatus,1);
        List<AppTopologyDiagramPO> list3 = appTopologyDiagramService.list(queryWrapper3);
        Map<String,AppTopologyDiagramPO> map3 = list3.stream().collect(Collectors.toMap(AppTopologyDiagramPO::getProjectId, item->item));

        //查询台账信息
        List<CsLedgerVO> allList = csLedgerMapper.getAll();

        if (CollectionUtil.isNotEmpty(list1)) {
            list1.forEach(item->{
                EngineeringProjectRelationVo temp = new EngineeringProjectRelationVo();
                temp.setEngineeringId(item.getId());
                temp.setEngineeringName(item.getName());
                temp.setProvinceId(item.getProvince());
                temp.setCityId(item.getCity());
                Area area1 = areaFeignClient.selectIdArea(item.getProvince()).getData();
                Area area2 = areaFeignClient.selectIdArea(item.getCity()).getData();
                temp.setEngineeringAreaName((ObjectUtil.isNotNull(area1)?area1.getName():"") + (ObjectUtil.isNotNull(area2)?area2.getName():""));
                temp.setEngineeringRemark(item.getDescription());
                temp.setEngineeringSort(item.getSort());

                List<CsLedgerVO> projectList = allList.stream().filter(item2->item2.getPid().equals(item.getId())).sorted(Comparator.comparing(CsLedgerVO::getSort)).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(projectList)) {
                    List<EngineeringProjectRelationVo.ProjectInfo> projectInfoList = new ArrayList<>();
                    projectList.forEach(item2->{
                        AppProjectPO po = map.get(item2.getId());
                        EngineeringProjectRelationVo.ProjectInfo projectInfo = new EngineeringProjectRelationVo.ProjectInfo();
                        projectInfo.setProjectId(po.getId());
                        projectInfo.setProjectName(po.getName());
                        projectInfo.setProjectArea(po.getArea());
                        projectInfo.setProjectRemark(po.getDescription());
                        projectInfo.setProjectSort(po.getSort());
                        projectInfo.setTopologyInfoId(Objects.isNull(map3.get(po.getId()))?null:map3.get(po.getId()).getTopoId());
                        projectInfo.setTopologyInfo(Objects.isNull(map3.get(po.getId()))?null:map3.get(po.getId()).getFilePath());
                        projectInfoList.add(projectInfo);
                    });
                    temp.setProjectInfoList(projectInfoList);
                }
                result.add(temp);
            });
        }
        return result;
    }
}
