package com.hotent.project.manager.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.baseInfo.model.CostCatalogUnit;
import com.hotent.project.manager.CostProjectApprovalManager;
import com.hotent.project.model.CostProjectApproval;
import com.hotent.project.model.CostProjectDocument;
import com.hotent.project.model.CostProjectMaterial;
import com.hotent.project.dao.CostProjectMaterialDao;
import com.hotent.project.manager.CostProjectMaterialManager;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.project.req.CostProjectBasePageReq;
import com.hotent.req.PageReq;
import com.hotent.surveyinfo.manager.CostSurveyFdTemplateManager;
import com.hotent.surveyinfo.model.CostSurveyFdTemplate;

import com.hotent.sys.persistence.manager.DataDictManager;
import com.hotent.sys.persistence.model.DataDict;
import com.hotent.uc.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import com.hotent.base.util.BeanUtils;


/**
 * 报送资料要求 服务实现类
 *
 * @author 超级管理员
 * @company 山西清众科技股份有限公司
 * @since 2025-09-26
 */
@Service
public class CostProjectMaterialManagerImpl extends BaseManagerImpl<CostProjectMaterialDao, CostProjectMaterial> implements CostProjectMaterialManager {



    @Autowired
    private CostSurveyFdTemplateManager costSurveyFdTemplateManager;


    @Resource
    DataDictManager dataDictManager;

    @Autowired
    private CostProjectApprovalManager costProjectApprovalManager;




    @Override
    public CostProjectMaterial getDetail(String id) {
        CostProjectMaterial costProjectMaterial = this.get(id);


        return costProjectMaterial;
    }

    @Override
    @Transactional
    public int createOrUpdate(CostProjectMaterial costProjectMaterial) {
        //新建或更新
       return this.saveOrUpdate(costProjectMaterial)?1:0;
    }

    @Override
    public boolean save(CostProjectMaterial entity){
        String projectId = entity.getProjectId();
        if(ObjectUtil.isEmpty(projectId)){
            throw new BaseException("项目id不能为空");
        }
        CostProjectApproval costProjectApproval = costProjectApprovalManager.get(projectId);
        if (ObjectUtil.isEmpty(costProjectApproval)) {
            throw new BaseException("项目不存在");
        }
        entity.setCatalogId(costProjectApproval.getCatalogId());
        return super.save(entity);
    }



    @Override
    public IPage<CostProjectMaterial> pageList(CostProjectBasePageReq req) {
        LambdaQueryWrapper<CostProjectMaterial> qw = new LambdaQueryWrapper<>();
        qw.eq(CostProjectMaterial::getProjectId, req.getProjectId());
        qw.orderByAsc(CostProjectMaterial::getOrderNum);
        IPage<CostProjectMaterial> page = new Page<>(req.getPageNum(), req.getPageSize());
        IPage<CostProjectMaterial> pageList = this.page(page, qw);

        List<String> ids = pageList.getRecords().stream().filter(u -> "3".equals(u.getFormatRequired())).map(CostProjectMaterial::getTemplateId).distinct().collect(Collectors.toList());

        Map<String, CostSurveyFdTemplate> fdTemplateMap;
        if(!ObjectUtil.isEmpty(ids)) {
            List<CostSurveyFdTemplate> costSurveyFdTemplates = this.costSurveyFdTemplateManager.listByIds(ids);
            fdTemplateMap = costSurveyFdTemplates.stream().collect(Collectors.toMap(CostSurveyFdTemplate::getSurveyTemplateId, Function.identity()));
        } else {
            fdTemplateMap = null;
        }


        List<CostProjectMaterial> records = pageList.getRecords();
        List<String> list = records.stream().map(CostProjectMaterial::getInformationType).distinct().collect(Collectors.toList());
        QueryWrapper<DataDict> wrapper = new QueryWrapper<>();
        wrapper.eq("TYPE_ID_","1976557733440159744");
        wrapper.in("KEY_",list);
        List<DataDict> costDictDatas= dataDictManager.list(wrapper);

        List<String> listRequire = records.stream().map(CostProjectMaterial::getFormatRequired).distinct().collect(Collectors.toList());
        QueryWrapper<DataDict> wrapperRequire = new QueryWrapper<>();
        wrapperRequire.eq("TYPE_ID_","1976558645202157568");
        wrapperRequire.in("KEY_",listRequire);
        List<DataDict> listRequireDatas= dataDictManager.list(wrapperRequire);

        records.forEach(costCatalogUnit -> {

            costDictDatas.stream()
                    .filter(c -> costCatalogUnit.getInformationType() != null &&
                            costCatalogUnit.getInformationType().equals(String.valueOf(c.getKey())))
                    .findAny().ifPresent(costDictData -> costCatalogUnit.setInformationTypeName(costDictData.getName()));


            listRequireDatas.stream()
                    .filter(c -> costCatalogUnit.getFormatRequired() != null &&
                            costCatalogUnit.getFormatRequired().equals(String.valueOf(c.getKey())))
                    .findAny().ifPresent(costDictData -> costCatalogUnit.setFormatRequiredName(costDictData.getName()));

            if ("3".equals(costCatalogUnit.getFormatRequired())) {
                if(fdTemplateMap!=null) {
                    CostSurveyFdTemplate costSurveyFdTemplate = fdTemplateMap.get(costCatalogUnit.getTemplateId());
                    costCatalogUnit.setSurveyTemplateName(costSurveyFdTemplate.getSurveyTemplateName());
                }else{
                    costCatalogUnit.setSurveyTemplateName("-");
                }
            }else{
                costCatalogUnit.setSurveyTemplateName("-");
            }
        });
        return pageList;
    }

    @Override
    public List<CostProjectMaterial> getListByProjectId(String projectId) {
        LambdaQueryWrapper<CostProjectMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostProjectMaterial::getProjectId, projectId);
        List<CostProjectMaterial> list = this.list(queryWrapper);
        if (ObjectUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list;
    }
}
