package com.hotent.project.manager.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.baseInfo.manager.AuditedUnitManager;
import com.hotent.baseInfo.manager.CostDocumentTemplateFileManager;
import com.hotent.baseInfo.manager.CostDocumentTemplateManager;
import com.hotent.baseInfo.manager.CostDocumentWhManager;
import com.hotent.baseInfo.model.AuditedUnit;
import com.hotent.baseInfo.model.CostDocumentTemplate;
import com.hotent.baseInfo.model.CostDocumentTemplateFile;
import com.hotent.baseInfo.model.CostDocumentWh;
import com.hotent.config.EipConfig;
import com.hotent.constant.BaseConstant;
import com.hotent.project.manager.*;
import com.hotent.project.model.*;
import com.hotent.project.dao.CostProjectDocumentDao;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.project.req.CostProjectDocumentPageReq;
import com.hotent.project.req.CostProjectDocumentReq;
import com.hotent.project.resp.CostProjectDocumentResp;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.exception.BaseException;
import com.hotent.uc.manager.OrgManager;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.Org;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import com.hotent.util.CostDataUtil;
import com.hotent.util.FileUtils;
import com.hotent.util.HtmlUtils;
import com.hotent.util.wordexcelutils.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.tools.ant.util.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.hotent.util.FileUploadUtil;
import springfox.documentation.spring.web.json.Json;

import static org.apache.tools.ant.util.DateUtils.ISO8601_DATE_PATTERN;


/**
 * 监审项目文书表 服务实现类
 *
 * @author 超级管理员
 * @company 山西清众科技股份有限公司
 * @since 2025-09-26
 */
@Service
public class CostProjectDocumentManagerImpl extends BaseManagerImpl<CostProjectDocumentDao, CostProjectDocument> implements CostProjectDocumentManager {

    @Autowired
    private CostProjectDocumentFileManager costProjectDocumentFileManager;

    @Autowired
    private CostDocumentTemplateManager costDocumentTemplateManager;

    @Autowired
    private AuditedUnitManager auditedUnitManager;

    @Autowired
    private CostDocumentTemplateFileManager costDocumentTemplateFileManager;

    @Autowired
    private CostProjectTaskEvidenceManager costProjectTaskEvidenceManager;

    @Autowired
    private CostProjectTaskManager costProjectTaskManager;

    @Autowired
    private CostDocumentWhManager costDocumentWhManager;

    @Autowired
    private CostProjectApprovalManager costProjectApprovalManager;

    @Autowired
    private UserManager userService;

    @Autowired
    private CostDocumentTemplateFileManager costTemplateFileManager;
    @Autowired
    private OrgManager orgManager;

    @Override
    public CostProjectDocument getDetail(String id) {
        CostProjectDocument costProjectDocument = this.get(id);


        return costProjectDocument;
    }

    @Override
    public void deleteByIds(List<String> ids) {
        List<CostProjectDocument> costProjectDocuments = this.listByIds(ids);
        if (costProjectDocuments!=null){
            costProjectDocuments.forEach(item -> {
                //逻辑删除
                item.setIsDeleted( BaseConstant.DELETE_FLAG);

            });
            this.updateBatchById(costProjectDocuments);
        }
    }

    @Override
    @Transactional
    public void createOrUpdate(CostProjectDocument costProjectDocument) {
        //新建或更新
        this.saveOrUpdate(costProjectDocument);
    }

    @Override
    public IPage<CostProjectDocument> pageList(CostProjectDocumentPageReq req) throws Exception {
        LambdaQueryWrapper<CostProjectDocument> qw = new LambdaQueryWrapper<>();
        if (req.getDocumentType() != null) {
//            LambdaQueryWrapper<CostDocumentTemplate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(CostDocumentTemplate::getId, req.getDocumentType());
//            lambdaQueryWrapper.eq(CostDocumentTemplate::getIsWh, "0");
            qw.eq(CostProjectDocument::getDocumentType, req.getDocumentType());
        }
        if (StringUtil.isNotEmpty(req.getProjectId())) {
            qw.eq(CostProjectDocument::getProjectId, req.getProjectId());
        }

        if(req.getPermissionType().equals(1)){
            IUser iUser = ContextUtil.getCurrentUser();
            User user = userService.getByAccount(iUser.getAccount());
            List<AuditedUnit> auditedUnit=auditedUnitManager.getByUserAccount(user.getId());
            List<String> collected = auditedUnit.stream().map(AuditedUnit::getUnitId).distinct().collect(Collectors.toList());
            if(!collected.isEmpty()){
                qw.in(CostProjectDocument::getEnterpriseId, collected);
            }

        } else if (req.getPermissionType().equals(2)) {
            IUser iUser = ContextUtil.getCurrentUser();
            User user = userService.getByAccount(iUser.getAccount());
            qw.eq(CostProjectDocument::getCreateBy, user.getAccount());
        }

        IPage<CostProjectDocument> page = new Page<>(req.getPageNum(), req.getPageSize());
        return this.page(page, qw);
    }

//    @Override
//    public void create(CostProjectDocument costProjectDocument) {
//        if (ObjectUtil.isEmpty(costProjectDocument.getDocumentId())) {
//            throw new BaseException("请选择文书模板");
//        }
//        if (ObjectUtil.isEmpty(costProjectDocument.getProjectId())) {
//            throw new BaseException("请选择项目");
//        }
//        if (ObjectUtil.isEmpty(costProjectDocument.getDocumentNumber())) {
//            throw new BaseException("请填写通知文号");
//        }
//        if (ObjectUtil.isEmpty(costProjectDocument.getEnterpriseId())) {
//            throw new BaseException("请选择监审单位");
//        }
//        costProjectDocument.setGenerateTime(LocalDateTime.now());
//        costProjectDocument.setIsPushed("1");
//
//        CostDocumentTemplate costDocumentTemplate = this.costDocumentTemplateManager.get(costProjectDocument.getDocumentId());
//        if (costDocumentTemplate == null || BaseConstant.DELETE_FLAG.equals(costDocumentTemplate.getIsDeleted())) {
//            throw new BaseException("文书模板不存在");
//        }
//        costProjectDocument.setDocumentAlias(costDocumentTemplate.getAlias());
//        AuditedUnit auditedUnit = auditedUnitManager.get(costProjectDocument.getEnterpriseId());
//        if (auditedUnit == null || BaseConstant.DELETE_FLAG.equals(auditedUnit.getIsDeleted())) {
//            throw new BaseException("被监审单位不存在");
//        }
//        CostDocumentWh costDocumentWh = costDocumentWhManager.get(costProjectDocument.getDocumentWhId());
//        if (costDocumentWh == null || BaseConstant.DELETE_FLAG.equals(costDocumentWh.getIsDeleted())) {
//            throw new BaseException("文书文号不存在");
//        }
//
//        LambdaQueryWrapper<CostProjectDocument> qw = new LambdaQueryWrapper<>();
//        qw.eq(CostProjectDocument::getProjectId, costProjectDocument.getProjectId());
//        qw.eq(CostProjectDocument::getDocumentId, costProjectDocument.getDocumentId());
//        qw.eq(CostProjectDocument::getEnterpriseId, costProjectDocument.getEnterpriseId());
//        if (this.count(qw) > 0) {
//            throw new BaseException("该项目监审单位已存在此文书");
//        }
//        super.create(costProjectDocument);
//
//
//    }


    @Override
    @Transactional
    public String create(CostProjectDocumentReq req) throws Exception {
        if (ObjectUtil.isEmpty(req.getDocumentId())) {
            throw new BaseException("请选择文书模板");
        }
        if (ObjectUtil.isEmpty(req.getProjectId())) {
            throw new BaseException("请选择项目");
        }
        CostDocumentTemplate costDocumentTemplate = this.costDocumentTemplateManager.get(req.getDocumentId());
        if (costDocumentTemplate == null || BaseConstant.DELETE_FLAG.equals(costDocumentTemplate.getIsDeleted())) {
            throw new BaseException("文书模板不存在");
        }
        if (costDocumentTemplate.getIsWh().equals("0") && StringUtil.isEmpty(req.getDocumentNumber())) {
            throw new BaseException("请填写通知文号");
        }
        if (ObjectUtil.isEmpty(req.getEnterpriseId())) {
            throw new BaseException("请选择监审单位");
        }
        req.setGenerateTime(LocalDateTime.now());
        req.setIsPushed("1");


        req.setDocumentAlias(costDocumentTemplate.getAlias());
        AuditedUnit auditedUnit = auditedUnitManager.get(req.getEnterpriseId());
        if (auditedUnit == null || BaseConstant.DELETE_FLAG.equals(auditedUnit.getIsDeleted())) {
            throw new BaseException("被监审单位不存在");
        }
        CostDocumentWh costDocumentWh;
        //返回文号
        String whNo;

        if (costDocumentTemplate.getIsWh().equals("0")) {
            costDocumentWh= costDocumentWhManager.get(req.getDocumentWhId());
            if (costDocumentWh == null) {
                throw new BaseException("文书文号不存在");
            }
            //返回文号
            whNo = this.getWH(costDocumentWh);
        } else {
            costDocumentWh = null;
            whNo = "";
        }
        LambdaQueryWrapper<CostProjectDocument> qw = new LambdaQueryWrapper<>();
        qw.eq(CostProjectDocument::getProjectId, req.getProjectId());
        qw.eq(CostProjectDocument::getDocumentId, req.getDocumentId());
        qw.eq(CostProjectDocument::getEnterpriseId, req.getEnterpriseId());
        if (this.count(qw) > 0) {
            throw new BaseException("该项目监审单位已存在此文书");
        }
        IUser iUser = ContextUtil.getCurrentUser();
        User user = userService.getByAccount(iUser.getAccount());
        CostProjectApproval costProjectApproval = costProjectApprovalManager.get(req.getProjectId());
        Org org = orgManager.getById(costProjectApproval.getOrgId());
        //类型转换
        CostProjectDocument costProjectDocument = new CostProjectDocument();
        BeanUtil.copyProperties(req, costProjectDocument);
        costProjectDocument.setDocumentNumber(whNo);
        costProjectDocument.setDocumentName(costDocumentTemplate.getDocumentName());
        costProjectDocument.setCreateBy(user.getCreateBy());
        costProjectDocument.setDocumentType(costDocumentTemplate.getType());
        costProjectDocument.setProjectId(costProjectApproval.getProjectId());
        super.create(costProjectDocument);

        //文件关联信息赋值
        req.getCostProjectDocumentFiles().forEach(costProjectDocumentFile -> {
            costProjectDocumentFile.setDocumentId(costProjectDocument.getDocumentId());
            costProjectDocumentFile.setProjectId(costProjectDocument.getProjectId());
            costProjectDocumentFile.setProjectDocumentId(costProjectDocument.getId());
            switch (costProjectDocumentFile.getPinyin()) {
                case "SongDaWenShuWenHao":
                    costProjectDocumentFile.setDataValue(whNo);
                    break;
            }
            if (StringUtils.isNotBlank(costProjectDocumentFile.getTableName()) && StringUtil.isEmpty(costProjectDocumentFile.getDataValue())){
                if(StringUtil.isEmpty(costProjectDocumentFile.getWhereValue()) && StringUtil.isNotEmpty(costProjectDocumentFile.getWhereName())){
                    costProjectDocumentFile.setWhereValue(costProjectApproval.getProjectId());
                } else if (costProjectDocument.getDocumentAlias().equals("cbjsgzdg")
                        &&!costProjectDocument.getDocumentAlias().equals("cbjsjtsyjl")
                        &&!costProjectDocument.getDocumentAlias().equals("cbshcbyjb1")
                        &&!costProjectDocument.getDocumentAlias().equals("cbjstqzldjb")) {
                    String whereValue1 = costProjectDocumentFile.getWhereValue();
                    String replace = whereValue1.replace("?", "'" + costProjectApproval.getProjectId() + "'");
                    String replaced = replace.replace("&", auditedUnit.getUnitId());
                    costProjectDocumentFile.setWhereValue(replaced);
                    String colValue = costTemplateFileManager.getColValue(costProjectDocumentFile.getTableName(), costProjectDocumentFile.getColName(), costProjectDocumentFile.getWhereName(), costProjectDocumentFile.getWhereValue());
                    //获取whereValue字段值

                    costProjectDocumentFile.setDataValue(colValue);
                } else if (StringUtil.isEmpty(costProjectDocumentFile.getWhereName()) && StringUtil.isEmpty(costProjectDocumentFile.getWhereValue())) {
                    String tableName = costProjectDocumentFile.getTableName();
                    List<CostProjectTask> taskByProjectId = costProjectTaskManager.findTaskByProjectId(costProjectApproval.getProjectId(), auditedUnit.getUnitId());
                    if (taskByProjectId!=null && !taskByProjectId.isEmpty()) {
                        String replace = tableName.replace("?", "'" + taskByProjectId.get(0).getId() + "'");
                        String colValue = costTemplateFileManager.getColValue2(replace);
                        costProjectDocumentFile.setDataValue(colValue);
                    }

                } else {
                    String whereValue1 = costProjectDocumentFile.getWhereValue();
                    String replace = whereValue1.replace("?", "'" + costProjectApproval.getProjectId() + "'");
                    costProjectDocumentFile.setWhereValue(replace);
                    String colValue = costTemplateFileManager.getColValue(costProjectDocumentFile.getTableName(), costProjectDocumentFile.getColName(), costProjectDocumentFile.getWhereName(), costProjectDocumentFile.getWhereValue());
                    //获取whereValue字段值
                    costProjectDocumentFile.setDataValue(colValue);
                }

            }

        });


        if (costDocumentTemplate.getIsWh().equals("0")) {

            CostDocumentTemplate templateManagerById = costDocumentTemplateManager.getByAlias("sdhz");
            if (templateManagerById==null) {
                throw new BaseException("未查询到送达回证文书模板信息，请先添加");
            }


            ArrayList<CostProjectDocumentFile> arrayList = new ArrayList<>();
            CostProjectDocument projectDocument = new CostProjectDocument();
            BeanUtil.copyProperties(costProjectDocument, projectDocument);
            projectDocument.setId(UniqueIdUtil.getSuid());
            projectDocument.setCreateBy(user.getAccount());
            projectDocument.setCreateTime(LocalDateTime.now());


            projectDocument.setDocumentNumber(costProjectDocument.getDocumentNumber());
            projectDocument.setElectronicDocumentUrl(templateManagerById.getFileUrl());
            if(costDocumentWh!=null){
                projectDocument.setDocumentWhId(costDocumentWh.getId());
            }
            projectDocument.setDocumentId(String.valueOf(templateManagerById.getId()));
            projectDocument.setDocumentName(costProjectDocument.getDocumentName()+"-"+templateManagerById.getDocumentName());
            projectDocument.setDocumentType(templateManagerById.getType());
            projectDocument.setDocumentAlias(templateManagerById.getAlias());
            //super.create(projectDocument);
            this.save(projectDocument);


            List<CostDocumentTemplateFile> documentFileList = costDocumentTemplateFileManager.getDocumentFileList(String.valueOf(templateManagerById.getId()));
            documentFileList.forEach(f->{
                CostProjectDocumentFile costProjectDocumentFile = new CostProjectDocumentFile();
                BeanUtils.copyProperties(f,costProjectDocumentFile);
                costProjectDocumentFile.setId(UniqueIdUtil.getUId());
                costProjectDocumentFile.setCreateBy(user.getAccount());
                costProjectDocumentFile.setCreateTime(LocalDateTime.now());
                costProjectDocumentFile.setProjectId(costProjectApproval.getProjectId());
                costProjectDocumentFile.setProjectDocumentId(projectDocument.getId());
                //costProjectDocumentFile.setProjectId(costProjectDocument.getProjectId());
                switch (f.getPinyin()) {
                    case "JiaGeZhuGuanBuMenHuoChengBenDiaoChaJiGou":
                    case "JiaGeZhuGuanBuMenHuoChengBenJianShenJiGou":
                        costProjectDocumentFile.setDataValue(org.getName());
                        break;
                    case "SongDaWenShuMingCheng":
                        if (costDocumentWh!=null) {
                            costProjectDocumentFile.setDataValue(costDocumentWh.getWhName());
                        }
                        break;
                    case "SongDaWenShuWenHao":
                        costProjectDocumentFile.setDataValue(costProjectDocument.getDocumentNumber());
                        break;
                    case "ShouSongDaRen":
                        costProjectDocumentFile.setDataValue(auditedUnit.getContactName());
                        break;
                    case "BeiJianShenDanWeiBanGongDiDian":
                        costProjectDocumentFile.setDataValue(auditedUnit.getAddress());
                        break;
                    case "TongZhiSongDaShiJian":
                        costProjectDocumentFile.setDataValue(DateUtils.format(new Date(),"yyyy-MM-dd"));
                        break;
                    case "BeiJianShenDanWeiLianXiRenDianHua":
                        costProjectDocumentFile.setDataValue(auditedUnit.getContactMobile());
                        break;
                    default:
                        costProjectDocumentFile.setDataValue("");
                        break;
                }

                arrayList.add(costProjectDocumentFile);
            });
            costProjectDocumentFileManager.saveBatch(arrayList);
        }

        //保存解析出的文件内容
        costProjectDocumentFileManager.saveBatch(req.getCostProjectDocumentFiles());
        return costProjectDocument.getId();
    }

    public synchronized String getWH(CostDocumentWh costDocumentWh){
        if("incremental".equals(costDocumentWh.getGenerateType())){
            costDocumentWh.setCurrentValue(costDocumentWh.getCurrentValue()+1);
            costDocumentWh.setLastGenerateDate(LocalDate.now());
        } else if ("daily".equals(costDocumentWh.getGenerateType())) {
            boolean b = LocalDate.now().isEqual(costDocumentWh.getLastGenerateDate());
            if (!b) {
                costDocumentWh.setCurrentValue(costDocumentWh.getCurrentValue()+1);
                costDocumentWh.setLastGenerateDate(LocalDate.now());
            }
        }else if ("monthly".equals(costDocumentWh.getGenerateType())) {
            LocalDate date = LocalDate.now(); // 获取当前日期
            YearMonth currentYearMonth = YearMonth.from(date);
            if (currentYearMonth.equals(YearMonth.from(costDocumentWh.getLastGenerateDate()))) {
                costDocumentWh.setCurrentValue(costDocumentWh.getCurrentValue()+1);
                costDocumentWh.setLastGenerateDate(LocalDate.now());
            }
        }else if ("yearly".equals(costDocumentWh.getGenerateType())) {
            LocalDate date = LocalDate.now(); // 获取当前日期
            // 获取当前年份
            int currentYear = date.getYear();
            if (costDocumentWh.getLastGenerateDate().getYear() == currentYear) {
                costDocumentWh.setCurrentValue(costDocumentWh.getCurrentValue()+1);
                costDocumentWh.setLastGenerateDate(LocalDate.now());
            }
        }
        costDocumentWhManager.update(costDocumentWh);
        return costDocumentWh.getRulePattern().replace("{prefixText}", costDocumentWh.getPrefixText())
                .replace("{year}","【" +costDocumentWh.getYear()+"】").replace("{currentValue}", costDocumentWh.getCurrentValue().toString());
    }

    @Override
    public List<CostProjectDocumentFile> getDocumentFileList(String id) {
        CostProjectDocument costProjectDocument = this.get(id);
        if(costProjectDocument == null){
            throw new BaseException("文书模板不存在");
        }

        return null;
    }



    @Override
    public void updateProjectDocument(CostProjectDocumentReq req) {
        if (ObjectUtil.isEmpty(req.getId())) {
            throw new BaseException("请选择要修改的文书");
        }
        if (ObjectUtil.isEmpty(req.getDocumentId())) {
            throw new BaseException("请选择文书模板");
        }
        if (ObjectUtil.isEmpty(req.getProjectId())) {
            throw new BaseException("请选择项目");
        }


        if (ObjectUtil.isEmpty(req.getEnterpriseId())) {
            throw new BaseException("请选择监审单位");
        }
        CostProjectDocument selectCostProjectDocument = this.get(req.getId());
        if (selectCostProjectDocument == null) {
            throw new BaseException("请选择要修改的文书");
        }

        req.setIsPushed("1");

        CostDocumentTemplate costDocumentTemplate = this.costDocumentTemplateManager.get(req.getDocumentId());

        if (costDocumentTemplate == null || BaseConstant.DELETE_FLAG.equals(costDocumentTemplate.getIsDeleted())) {
            throw new BaseException("文书模板不存在");
        }
        /*if (costDocumentTemplate.getIsWh().equals("1")) {
            throw new BaseException("请填写通知文号");
        }*/
        req.setDocumentAlias(costDocumentTemplate.getAlias());
        AuditedUnit auditedUnit = auditedUnitManager.get(req.getEnterpriseId());
        if (auditedUnit == null || BaseConstant.DELETE_FLAG.equals(auditedUnit.getIsDeleted())) {
            throw new BaseException("被监审单位不存在");
        }
        /*CostDocumentWh costDocumentWh = costDocumentWhManager.get(req.getDocumentWhId());
        if(costDocumentTemplate.getIsWh().equals("0")){
            if (costDocumentWh == null || BaseConstant.DELETE_FLAG.equals(costDocumentWh.getIsDeleted())) {
                throw new BaseException("文书文号不存在");
            }
        }*/
        LambdaQueryWrapper<CostProjectDocument> qw = new LambdaQueryWrapper<>();
        qw.eq(CostProjectDocument::getProjectId, req.getProjectId());
        qw.eq(CostProjectDocument::getDocumentId, req.getDocumentId());
        qw.eq(CostProjectDocument::getEnterpriseId, req.getEnterpriseId());
        /*if (this.count(qw) > 0) {
            throw new BaseException("该项目监审单位已存在此文书");
        }*/
        CostDocumentWh costDocumentWh;
        //返回文号
        String whNo=selectCostProjectDocument.getDocumentNumber();

        /*if (costDocumentTemplate.getIsWh().equals("0")) {
            costDocumentWh= costDocumentWhManager.get(req.getDocumentWhId());
            if (costDocumentWh == null) {
                throw new BaseException("文书文号不存在");
            }
            //返回文号
            whNo = this.getWH(costDocumentWh);
        } else {
            costDocumentWh = null;
            whNo = "";
        }*/

        selectCostProjectDocument.setDocumentWhId(req.getDocumentWhId());
        selectCostProjectDocument.setDocumentId(req.getDocumentId());
        selectCostProjectDocument.setEnterpriseId(req.getEnterpriseId());
        selectCostProjectDocument.setElectronicDocumentUrl("");
//        类型转换
         BeanUtil.copyProperties(req,selectCostProjectDocument);
        selectCostProjectDocument.setDocumentNumber(whNo);
        super.update(selectCostProjectDocument);

        req.getCostProjectDocumentFiles().forEach(f->{
            f.setProjectDocumentId(selectCostProjectDocument.getId());
        });
        costProjectDocumentFileManager.updateBatchById(req.getCostProjectDocumentFiles());
    }

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

     @Override
     public CostProjectDocumentResp getByProjectId(String projectId){
        //查询监审文书
         LambdaQueryWrapper<CostProjectDocument> qw = new LambdaQueryWrapper<>();
         qw.eq(CostProjectDocument::getProjectId, projectId);
         qw.eq(CostProjectDocument::getIsDeleted, BaseConstant.NORMAL_STATUS);
         CostProjectDocument costProjectDocument = this.getOne(qw);
         //转换为返回类型
         CostProjectDocumentResp costProjectDocumentResp = BeanUtil.copyProperties(costProjectDocument, CostProjectDocumentResp.class);

            //查询文书下的文书内容
             LambdaQueryWrapper<CostProjectDocumentFile> wrapper = new LambdaQueryWrapper<>();
             wrapper.eq(CostProjectDocumentFile::getProjectId, costProjectDocument.getProjectId());
             //获取文件内容返回
             costProjectDocumentResp.setCostProjectDocumentFiles(costProjectDocumentFileManager.list(wrapper));
         CostDocumentTemplate costDocumentTemplate = costDocumentTemplateManager.get(costProjectDocument.getDocumentId());
         costProjectDocumentResp.setFullPath(EipConfig.getImgUrl()+costDocumentTemplate.getFileUrl());
         return costProjectDocumentResp;

     }

    @Override
    public String createDocument(String id) {
        CostProjectDocument costProjectDocument = this.getDetail(id);
        if (StringUtil.isEmpty(costProjectDocument.getActUrl())) {
            List<CostProjectDocumentFile> list = costProjectDocumentFileManager.getCostProjectDocumentFiles(costProjectDocument.getProjectId(),costProjectDocument.getDocumentId());
            CostDocumentTemplate costDocumentTemplate = this.costDocumentTemplateManager.get(costProjectDocument.getDocumentId());
            //生成文书
            Map<String,String> map = new HashMap<>();
            list.stream().forEach(p->{
                map.put("{"+p.getOriginalText()+"}", HtmlUtils.stripHtmlFast(p.getDataValue()) );
            });
            //先处理一种文件
            String templatePath = costDocumentTemplate.getFileUrl().replace(BaseConstant.RESOURCE_PREFIX,"");
            templatePath = EipConfig.getProfile()+templatePath;

            String fileExtension = FileUploadUtil.getFileExtension(costDocumentTemplate.getFileUrl());
            String fileName = FileUploadUtil.generateFileName(costDocumentTemplate.getDocumentName()+"."+fileExtension);
            String outputPath = FileUploadUtil.generateSavePath(EipConfig.getUploadPath(), fileName, fileExtension);
            try (FileInputStream fis = new FileInputStream(templatePath);
                 XWPFDocument document = new XWPFDocument(fis);
                 FileOutputStream fos = FileUtils.createFileOutputStream(outputPath);) {


                if (costProjectDocument.getDocumentAlias().equals("cbjstqzldjb")) {
                    List<CostProjectTaskEvidence> costProjectTaskEvidences= costProjectTaskEvidenceManager.findEvidenceListByTaskIds(costProjectDocument.getProjectId(),costProjectDocument.getEnterpriseId());
                    if (!costProjectTaskEvidences.isEmpty()) {
                        List<CompleteTemplateProcessor.TableRowData> mapList = costProjectTaskEvidences.stream().map(c -> {
                            CompleteTemplateProcessor.TableRowData tableRowData = new CompleteTemplateProcessor.TableRowData();

                            tableRowData.setDocumentName(c.getMaterialName());
                            tableRowData.setRemark(c.getRemark());
                            tableRowData.setPageCount(c.getPageCount());
                            return tableRowData;
                        }).collect(Collectors.toList());
                        AuditedUnit auditedUnit = auditedUnitManager.get(costProjectDocument.getEnterpriseId());

                        CompleteTemplateProcessor.processTemplateComplete(document,auditedUnit.getUnitName(),mapList,DateUtils.format(new Date(),ISO8601_DATE_PATTERN));
                    }
                } else if (costProjectDocument.getDocumentAlias().equals("zfdjcbjsjlbg")) {
                    CostProjectApproval costProjectApproval = costProjectApprovalManager.get(costProjectDocument.getProjectId());

                    List<CostProjectTask> taskByProjectId = costProjectTaskManager.findTaskByProjectId(costProjectApproval.getProjectId(), costProjectDocument.getEnterpriseId());

                    List<Map<String,Object>> maps= costTemplateFileManager.getSurveyTemplate(taskByProjectId.get(0).getId());

                    CostDataUtil costDataUtil = new CostDataUtil();
                    Map<String, Object> map1 = costDataUtil.convertToCostFormat(maps);
                    @SuppressWarnings("unchecked")
                    List<String> years = (List<String>)map1.get("years");
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> costItems = (List<Map<String, Object>>) map1.get("costItems");

                    // 处理文档
                    RobustComplexDocumentProcessor.processDocumentWithMaps(
                            document,
                            map,
                            years,
                            costItems
                    );

                } else {
                    SmartTemplateWriter.writeToTemplate(document,map);
                }
                document.write(fos);
            } catch (IOException e) {
                throw new RuntimeException("处理Word文档时出错", e);
            }
            costProjectDocument.setActUrl(EipConfig.getImgUrl() + FileUploadUtil.getPathFileName(outputPath, fileName));
        }
        return costProjectDocument.getActUrl() ;
    }


    @Override
    public void feedbackDocumentUrl(CostProjectDocumentReq req) {
        if (ObjectUtil.isEmpty(req.getId())) {
            throw new BaseException("请选择要修改的文书");
        }
        if (ObjectUtil.isEmpty(req.getFeedbackDocumentUrl())) {
            throw new BaseException("被监审单位反馈资料附件ID集合不能为空");
        }
        CostProjectDocument projectDocument = this.get(req.getId());
        if(projectDocument==null){
            throw new BaseException("根据id未查询到实体信息");
        }
        projectDocument.setFeedbackDocumentUrl(req.getFeedbackDocumentUrl());
        projectDocument.setFeedbackTime(LocalDateTime.now());
        this.update(projectDocument);
    }
}
