package com.ruoyi.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.tc.entity.*;
import com.ruoyi.tc.entity.history.*;
import com.ruoyi.tc.entity.po.*;
import com.ruoyi.tc.entity.request.*;
import com.ruoyi.tc.entity.response.AssestTaskXqresponse;
import com.ruoyi.tc.entity.response.AssetTaskResponse;
import com.ruoyi.tc.entity.response.AssetdwHcBlResponse;
import com.ruoyi.tc.entity.response.AssetdwHcResponse;
import com.ruoyi.tc.historyService.*;
import com.ruoyi.tc.mapper.AssetTaskMapper;
import com.ruoyi.tc.service.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务主表(AssetTask)表服务实现类
 *
 * @author makejava
 * @since 2024-11-18 13:23:09
 */
@Service("assetTaskService")
public class AssetTaskServiceImpl extends ServiceImpl<AssetTaskMapper, AssetTask> implements AssetTaskService {
    @Resource
    private AssetTaskMapper assetTaskDao;

    @Resource
    private AssetCurrentCpService assetCurrentCpService;

    @Resource
    private AssetBusinessFormCpService assetBusinessFormCpService;

    @Resource
    private AssetSupplyChainCpService assetSupplyChainCpService;


    @Resource
    private AssetBasicNetworkCpService assetBasicNetworkCpService;


    @Resource
    private UnitOtherConcatCpService unitOtherConcatCpService;

    @Resource
    private AssetLcService assetLcService;

    @Resource
    private AssetCurrentService assetCurrentService;

    @Resource
    private AssetOfficialAccountService assetOfficialAccountService;
    @Resource
    private AssetBusinessFormService assetBusinessFormService;

    @Resource
    private AssetBasicNetworkService assetBasicNetworkService;


    @Resource
    private AssetSupplyChainService assetSupplyChainService;

    @Resource
    private UnitOtherConcatService unitOtherConcatService;


    @Resource
    private AssetMiniProgramsService assetMiniProgramsService;

    @Resource
    private AssetMiniProgramsCpService assetMiniProgramsCpService;

    @Resource
    private AssetOfficialAccountCpService assetOfficialAccountCpService;


    @Resource
    private AssetEmailCpService assetEmailCpService;

    @Resource
    private AssetEmailService assetEmailService;
    @Resource
    private AssetAppService assetAppService;

    @Resource
    private AssetAppCpService assetAppCpService;


    @Resource
    private UnitService unitService;

    @Resource
    private AssetTaskService assetTaskService;


    @Resource
    private AssetCurrentHistoryService assetCurrentHistoryService;


    @Resource
    private AssetAppHistoryService assetAppHistoryService;


    @Resource
    private AssetBasicNetworkHistoryService assetBasicNetworkHistoryService;

    @Resource
    private AssetBusinessFormHistoryService assetBusinessFormHistoryService;

    @Resource
    private AssetEmailHistoryService assetEmailHistoryService;


    @Resource
    private AssetMiniProgramsHistoryService assetMiniProgramsHistoryService;


    @Resource
    private AssetOfficialAccountHistoryService assetOfficialAccountHistoryService;

    @Resource
    private AssetSupplyChainHistoryService assetSupplyChainHistoryService;

    @Resource
    private UnitOtherConcatHistoryService unitOtherConcatHistoryService;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AssetTaskResponse queryById(Integer id) {
        return assetTaskDao.queryById(id);
    }


    /**
     * 分页查询
     *
     * @param assetTask   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<AssetTask> queryByPage(Page<AssetTask> assetTask, AssetTaskPageRequest pageRequest) {
        return assetTaskDao.queryByPage(assetTask, pageRequest);
    }

    /**
     * 新增数据
     *
     * @param assetTask 实例对象
     */
    @Override
    public void insert(AssetTask assetTask) {
        int a = 0;
        //遍历单位
        String[] taskParts = assetTask.getDwmc().split(",");
        int current = 0;
        int xcx = 0;
        int gzh = 0;
        int email = 0;
        int app = 0;
        int totalCount = 0;
        for (String part : taskParts) {
            //根据单位查询所有资产
            //web
            //  遍历资产类型字段
            String[] uParts = assetTask.getType().split(",");
            for (String qq : uParts) {
                if (qq.equals("0")) {
                    current = assetCurrentService.findBydwmc(part);
                    totalCount += current;
                } else if (qq.equals("1")) {
                    xcx = assetMiniProgramsService.findBydwmc(part);
                    totalCount += xcx;
                } else if (qq.equals("2")) {
                    gzh = assetOfficialAccountService.findBydwmc(part);
                    totalCount += gzh;
                } else if (qq.equals("3")) {
                    email = assetEmailService.findBydwmc(part);
                    totalCount += email;
                } else if (qq.equals("4")) {
                    app = assetAppService.findBydwmc(part);
                    totalCount += app;
                }

            }
            assetTask.setTotalCount(totalCount);
        }
        //任务新增
        assetTaskDao.insert(assetTask);
        int id = assetTask.getId();
        //新增流程节点
        AssetLc assetLc = new AssetLc();
        assetLc.setTaskId(id);
        assetLc.setXfTime(LocalDateTime.now());
        assetLc.setAssetName("管理员任务下发");
        assetLcService.insert(assetLc);
        //  遍历资产类型字段
        String[] assetParts = assetTask.getType().split(",");
        for (String assetPart : assetParts) {
            if (assetPart.equals("0")) {
                //遍历单位
                String[] parts = assetTask.getDwmc().split(",");
                for (String part : parts) {
                    //根据单位名称查询资产
                    List<AssetCurrentCpPo> list = assetTaskDao.findByDwmcAssetCurrent(part);
                    for (AssetCurrentCpPo assetCurrentResponse : list) {
                        assetCurrentResponse.setTaskId(id);
                    }
                    assetCurrentCpService.saveBatch(list);
                    List<AssetBusinessFormCpPo> assetBusinessFormCpResponseList = new ArrayList<>();
                    for (AssetCurrentCpPo assetCurrentResponse : list) {
                        //新增新监管业务形态
                        //根据资产id查询新监管业务形态主表id
                        List<AssetBusinessFormCpPo> bussList = assetBusinessFormCpService.findByassetId(assetCurrentResponse.getId());
                        if (bussList != null) {
                            for (AssetBusinessFormCpPo assetBusinessFormCpResponse : bussList) {
                                if (assetCurrentResponse.getXjgywxt() != null) {
                                    assetCurrentResponse.getXjgywxt().setAssetId(assetBusinessFormCpResponse.getAssetId());
                                    assetCurrentResponse.getXjgywxt().setTaskId(id);
                                    assetBusinessFormCpResponseList.add(assetCurrentResponse.getXjgywxt());
                                }
                            }
                            assetBusinessFormCpService.saveBatch(assetBusinessFormCpResponseList);
                        }
                        //根据资产id查询供应链主表id-
                        List<AssetSupplyChainCpPo> supplyChainList = assetSupplyChainCpService.findByassetId(assetCurrentResponse.getId());
                        if (supplyChainList != null) {
                            for (AssetSupplyChainCpPo items : supplyChainList) {
                                items.setAssetId(assetCurrentResponse.getId());
                                items.setSupplyId(items.getSupplyId());
                                items.setTaskId(id);
                                //新增供应链
                            }
                            assetSupplyChainCpService.saveBatch(supplyChainList);
                        }
                        List<AssetBasicNetworkCpPo> BasicNetworkCpList = assetBasicNetworkCpService.findByassetId(assetCurrentResponse.getId());
                        if (BasicNetworkCpList != null) {
                            for (AssetBasicNetworkCpPo items : BasicNetworkCpList) {
                                //根据资产id查询基础网络主表id
                                items.setAssetId(assetCurrentResponse.getId());
                                items.setNetworkId(items.getNetworkId());
                                items.setTaskId(id);
                                //新增基础网络
                            }
                            assetBasicNetworkCpService.saveBatch(BasicNetworkCpList);
                        }
                        List<UnitOtherConcatCpPo> unitOtherConcatList = unitOtherConcatCpService.findByassetId(assetCurrentResponse.getId());
                        if (unitOtherConcatList != null) {
                            for (UnitOtherConcatCpPo items : unitOtherConcatList) {
                                //根据资产id查询其他联系人主表id
                                items.setAssetId(assetCurrentResponse.getId());
                                items.setConcatId(items.getConcatId());
                                items.setTaskId(id);
                                //新增其他联系人
                            }
                            unitOtherConcatCpService.saveBatch(unitOtherConcatList);
                        }
                    }
                }
            } else if (assetPart.equals("1")) {
                //遍历小程序资产单位
                String[] parts = assetTask.getDwmc().split(",");
                for (String part : parts) {
                    //根据单位名称查询资产
                    QueryWrapper<AssetMiniPrograms> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ssdw", part);
                    queryWrapper.eq("del_flag", 0);
                    List<AssetMiniPrograms> list = assetMiniProgramsService.lambdaQuery().eq(AssetMiniPrograms::getSsdw, part).eq(AssetMiniPrograms::getDelFlag, 0).list();
                    List<AssetMiniProgramsCpPo> miniProgramsNewList = list.stream()
                            .map(cpPo -> {
                                AssetMiniProgramsCpPo assetMiniProgramsCpPo = new AssetMiniProgramsCpPo();
                                assetMiniProgramsCpPo.setTaskId(id);
                                assetMiniProgramsCpPo.setStatus(0);
                                assetMiniProgramsCpPo.setAssetId(cpPo.getId());
                                BeanUtils.copyProperties(cpPo, assetMiniProgramsCpPo); // 复制属性
                                return assetMiniProgramsCpPo; // 返回新对象
                            })
                            .collect(Collectors.toList()); // 收集到列表中
                    assetMiniProgramsCpService.saveBatch(miniProgramsNewList);
                }
            } else if (assetPart.equals("2")) {
                //遍历公众号资产单位
                String[] parts = assetTask.getDwmc().split(",");
                for (String part : parts) {
                    //根据单位名称查询资产
                    QueryWrapper<AssetOfficialAccount> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ssdw", part);
                    queryWrapper.eq("del_flag", 0);
                    List<AssetOfficialAccount> list = assetOfficialAccountService.lambdaQuery().eq(AssetOfficialAccount::getSsdw, part).eq(AssetOfficialAccount::getDelFlag, 0).list();
                    List<AssetOfficialAccountCpPo> officialAccountProgramsNewList = list.stream()
                            .map(cpPo -> {
                                AssetOfficialAccountCpPo assetOfficialAccountCpPo = new AssetOfficialAccountCpPo();
                                assetOfficialAccountCpPo.setTaskId(id);
                                assetOfficialAccountCpPo.setStatus(0);
                                assetOfficialAccountCpPo.setAssetId(cpPo.getId());
                                BeanUtils.copyProperties(cpPo, assetOfficialAccountCpPo); // 复制属性
                                return assetOfficialAccountCpPo; // 返回新对象
                            })
                            .collect(Collectors.toList()); // 收集到列表中
                    assetOfficialAccountCpService.saveBatch(officialAccountProgramsNewList);
                }
            } else if (assetPart.equals("3")) {
                //遍历电子邮件资产单位
                String[] parts = assetTask.getDwmc().split(",");
                for (String part : parts) {
                    //根据单位名称查询资产
                    QueryWrapper<AssetEmail> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ssdw", part);
                    queryWrapper.eq("del_flag", 0);
                    List<AssetEmail> list = assetEmailService.lambdaQuery().eq(AssetEmail::getSsdw, part).eq(AssetEmail::getDelFlag, 0).list();
                    ;
                    List<AssetEmailCpPo> emailCpNewList = list.stream()
                            .map(cpPo -> {
                                AssetEmailCpPo emailCpPo = new AssetEmailCpPo();
                                emailCpPo.setTaskId(id);
                                emailCpPo.setAssetId(cpPo.getId());
                                emailCpPo.setStatus(0);
                                BeanUtils.copyProperties(cpPo, emailCpPo); // 复制属性
                                return emailCpPo; // 返回新对象
                            })
                            .collect(Collectors.toList()); // 收集到列表中
                    assetEmailCpService.saveBatch(emailCpNewList);
                }
            } else if (assetPart.equals("4")) {
                //遍历资产移动应用程序资产单位
                String[] parts = assetTask.getDwmc().split(",");
                for (String part : parts) {
                    //根据单位名称查询资产
                    QueryWrapper<AssetApp> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ssdw", part);
                    queryWrapper.eq("del_flag", 0);
                    List<AssetApp> list = assetAppService.lambdaQuery().eq(AssetApp::getSsdw, part).eq(AssetApp::getDelFlag, 0).list();
                    List<AssetAppCpPo> appCpNewList = list.stream()
                            .map(cpPo -> {
                                AssetAppCpPo appCpPo = new AssetAppCpPo();
                                appCpPo.setTaskId(id);
                                appCpPo.setAssetId(cpPo.getId());
                                appCpPo.setStatus(0);
                                BeanUtils.copyProperties(cpPo, appCpPo); // 复制属性
                                return appCpPo; // 返回新对象
                            })
                            .collect(Collectors.toList()); // 收集到列表中
                    assetAppCpService.saveBatch(appCpNewList);
                }
            }

        }
    }

    /**
     * 修改数据
     *
     * @param assetTask 实例对象
     * @return 实例对象
     */
    @Override
    public int update(AssetTask assetTask) {
        return this.assetTaskDao.update(assetTask);

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.assetTaskDao.deleteById(id) > 0;
    }

    @Override
    public AssetCurrentCpPo taskSh(int taskId, int assetId) {

        AssetCurrentCpPo byId = assetTaskDao.findBytaskIdandAssestId(taskId, assetId);
        byId.setGylxxList(assetSupplyChainCpService.lambdaQuery().eq(AssetSupplyChainCpPo::getAssetId, assetId).eq(AssetSupplyChainCpPo::getDelFlag, "0").eq(AssetSupplyChainCpPo::getTaskId, taskId).list());
        byId.setJcwlList(assetBasicNetworkCpService.lambdaQuery().eq(AssetBasicNetworkCpPo::getAssetId, assetId).eq(AssetBasicNetworkCpPo::getDelFlag, "0").eq(AssetBasicNetworkCpPo::getTaskId, taskId).list());
        byId.setXjgywxt(assetBusinessFormCpService.lambdaQuery().eq(AssetBusinessFormCpPo::getAssetId, assetId).eq(AssetBusinessFormCpPo::getDelFlag, "0").eq(AssetBusinessFormCpPo::getTaskId, taskId).one());
        byId.setOtherConcat(unitOtherConcatCpService.lambdaQuery().eq(UnitOtherConcatCpPo::getAssetId, assetId).eq(UnitOtherConcatCpPo::getDelFlag, "0").eq(UnitOtherConcatCpPo::getTaskId, taskId).list());
        List<Acomma> a1 = new ArrayList<>();
        if (byId.getGlym() != null) {
            Arrays.asList(byId.getGlym().split(",")).forEach(x -> {
                Acomma acomma = new Acomma();
                acomma.setKey(x);
                a1.add(acomma);
            });
            byId.setGlymList(a1);
        }
        List<Acomma> a2 = new ArrayList<>();
        if (byId.getGlIp() != null) {
            Arrays.asList(byId.getGlIp().split(",")).forEach(x -> {
                Acomma acomma = new Acomma();
                acomma.setKey(x);
                a2.add(acomma);
            });
            byId.setGlIpList(a2);
        }
        return byId;


    }

    @Override
    public AssetMiniProgramsCpPo minitaskSh(int taskId, int assetId) {
        QueryWrapper<AssetMiniProgramsCpPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("asset_id", assetId);
        queryWrapper.eq("task_id", taskId);
        return assetMiniProgramsCpService.getOne(queryWrapper);
    }

    @Override
    public AssetOfficialAccountCpPo officetaskSh(int taskId, int assetId) {
        QueryWrapper<AssetOfficialAccountCpPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("asset_id", assetId);
        queryWrapper.eq("task_id", taskId);

        AssetOfficialAccountCpPo byId = assetOfficialAccountCpService.getOne(queryWrapper);
        List<AssetOfficialAccountMenu> a1 = new ArrayList<>();
        String[] s1 = byId.getCdmc().split("\\|");
        String[] s2 = byId.getCdlj().split("\\|");
        String[] s3 = byId.getCdlx().split("\\|");
        for (int i = 0; i < s1.length; i++) {
            AssetOfficialAccountMenu as = new AssetOfficialAccountMenu();
            if (s1[i] != null && !Objects.equals(s1[i], "")) {
                as.setCdmc(s1[i]);
            }
            if (s2[i] != null && !Objects.equals(s2[i], "")) {
                as.setCdlj(s2[i]);
            }
            if (s3[i] != null && !Objects.equals(s3[i], "")) {
                as.setCdlx(s3[i]);
            }
            a1.add(as);
        }
        byId.setCdList(a1);
        return byId;
    }

    @Override
    public AssetEmailCpPo emailtaskSh(int taskId, int assetId) {
        QueryWrapper<AssetEmailCpPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("asset_id", assetId);
        queryWrapper.eq("task_id", taskId);
        return assetEmailCpService.getOne(queryWrapper);
    }

    @Override
    public AssetAppCpPo apptaskSh(int taskId, int assetId) {
        QueryWrapper<AssetAppCpPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("asset_id", assetId);
        queryWrapper.eq("task_id", taskId);
        return assetAppCpService.getOne(queryWrapper);
    }

    @Override
    public Page<AssestTaskXqresponse> zcHc(Page<AssestTaskXqresponse> assetTask, AssestTaskXqRequest pageRequest) {
        assetTask.setOptimizeCountSql(false);
        Page<AssestTaskXqresponse> result = null;
        if (pageRequest.getType().equals("0")) {
            result = assetTaskDao.zcHc(assetTask, pageRequest);
        } else if (pageRequest.getType().equals("1")) {
            result = assetTaskDao.xcxZcHc(assetTask, pageRequest);
        } else if (pageRequest.getType().equals("2")) {
            result = assetTaskDao.gzhZcHc(assetTask, pageRequest);
        } else if (pageRequest.getType().equals("3")) {
            result = assetTaskDao.emailZcHc(assetTask, pageRequest);
        } else if (pageRequest.getType().equals("4")) {
            result = assetTaskDao.appZcHc(assetTask, pageRequest);
        }
        // 确保 records 不为 null
        if (result.getRecords() == null) {
            result.setRecords(new ArrayList<>()); // 设置为空数组
        }
        return result;
    }

    @SneakyThrows
    @Override
    public int sh(AssetCurrentShRequest req) {
        //根据taskid获取当前任务的count数量
        AssetTask assetTask = assetTaskDao.getByTaskId(req.getTaskId());
        // 获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();
        // 转换为 Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        if (req.getType() == 0) {
            //web资产
            //是否超期
            ifCq(req, assetTask);
            //创建任务流程
            getTaskStatus(req);
            if (req.getBtgyy() != null) {
                assetTaskDao.sh(req);
                //修改子表和新增历史表
                updateZiandHistory(req, date);
            } else {
                //修改子表和新增历史表
                updateZiandHistory(req, date);
                //同步主表
                taskSaveOrDelete(req);
            }
        } else if (req.getType() == 1) {
            //小程序资产
            //创建任务流程
            ifCq(req, assetTask);
            // //创建任务流程
            getTaskStatus(req);
            if (req.getBtgyy() != null) {
                assetTaskDao.xcxsh(req);
                //修改子表和新增历史表
                updateMinZiandHistory(req, date);
            } else {
                //修改子表和新增历史表
                updateMinZiandHistory(req, date);
                //同步主表
                syb(req);
            }

        } else if (req.getType() == 2) {
            //公众号资产
            //创建任务流程
            ifCq(req, assetTask);
            //创建任务流程
            getTaskStatus(req);
            if (req.getBtgyy() != null) {
                assetTaskDao.gzhsh(req);
                //修改子表和历史表新增
                updateGzhZiandHistory(req, date);
            } else {
                //修改子表和历史表新增
                updateGzhZiandHistory(req, date);
                //同步主表
                syb(req);
            }

        } else if (req.getType() == 3) {
            //电子邮件
            //创建任务流程
            ifCq(req, assetTask);
            //创建任务流程
            getTaskStatus(req);
            if (req.getBtgyy() != null) {
                assetTaskDao.emailsh(req);
                //修改子表和历史表新增
                updateEmailZiandHistory(req, date);
            } else {
                //修改子表和历史表新增
                updateEmailZiandHistory(req, date);
                //同步主表
                syb(req);
            }

        } else if (req.getType() == 4) {
            //app
            //创建任务流程
            ifCq(req, assetTask);
            //创建任务流程
            getTaskStatus(req);
            if (req.getBtgyy() != null) {
                assetTaskDao.appsh(req);
                //修改子表和历史表新增
                updateAppZiandHistory(req, date);
            } else {
                //修改子表和历史表新增
                updateAppZiandHistory(req, date);
                //同步主表
                syb(req);
            }

        }
        AssetTask finalTask = assetTaskDao.getByTaskId(req.getTaskId());
        LocalDateTime finishTime = null;
        //根据任务id查询是否进行中
        Integer jxz=assetTaskDao.getJxz(req.getTaskId());
         if(jxz>0){
             //进行中
             finalTask.setTaskStatus(1);
             finalTask.setTaskFinishTime(finishTime);
             assetTaskService.update(finalTask);
         }else{
             //根据任务id查询是否超期
             String ifcq=assetTaskDao.getifcq(req.getTaskId());
             String taskDeadline = finalTask.getTaskDeadline(); // 定义日期格式，确保格式与字符串一致
             SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据你的时间格式调整
                 // 将字符串转换为日期对象
                 Date ifcqDate = dateFormat.parse(ifcq);
                 Date taskDeadlineDate = dateFormat.parse(taskDeadline);
                 // 比较两个日期
                 if (ifcqDate.before(taskDeadlineDate)) {
                    //超期完成
                     finalTask.setTaskStatus(3);
                     finishTime = LocalDateTime.now();
                     finalTask.setTaskFinishTime(finishTime);
                     assetTaskService.update(finalTask);
                 } else if (ifcqDate.after(taskDeadlineDate)) {
                  //正常完成
                     finalTask.setTaskStatus(2);
                     finishTime = LocalDateTime.now();
                     finalTask.setTaskFinishTime(finishTime);
                     assetTaskService.update(finalTask);
                 }
         }

        return 0;
    }

    private void updateAppZiandHistory(AssetCurrentShRequest req, Date date) {
        req.getAssetAppCpPo().setStatus(req.getStatus());
        req.getAssetAppCpPo().setUpdateTime(date);
        assetAppCpService.updateById(req.getAssetAppCpPo());
        //新增历史记录表
        AssetAppHistory assetAppHistory = new AssetAppHistory();
        BeanUtils.copyProperties(req.getAssetAppCpPo(), assetAppHistory);
        assetAppHistoryService.save(assetAppHistory);
    }

    private void updateEmailZiandHistory(AssetCurrentShRequest req, Date date) {
        req.getAssetEmailCpPo().setStatus(req.getStatus());
        req.getAssetEmailCpPo().setUpdateTime(date);
        assetEmailCpService.updateById(req.getAssetEmailCpPo());
        //新增历史记录表
        AssetEmailHistory assetEmailHistory = new AssetEmailHistory();
        BeanUtils.copyProperties(req.getAssetEmailCpPo(), assetEmailHistory);
        assetEmailHistoryService.save(assetEmailHistory);
    }

    private void updateGzhZiandHistory(AssetCurrentShRequest req, Date date) {
        if (req.getAssetOfficialAccountCpPo().getCdList() != null && !req.getAssetOfficialAccountCpPo().getCdList().isEmpty()) {
            StringBuilder a = new StringBuilder();
            StringBuilder b = new StringBuilder();
            StringBuilder c = new StringBuilder();
            req.getAssetOfficialAccountCpPo().getCdList().forEach(x -> {
                a.append(x.getCdmc()).append("|");
                b.append(x.getCdlj()).append("|");
                c.append(x.getCdlx()).append("|");
            });
            req.getAssetOfficialAccountCpPo().setCdmc(a.toString());
            req.getAssetOfficialAccountCpPo().setCdlj(b.toString());
            req.getAssetOfficialAccountCpPo().setCdlx(c.toString());
        }
        req.getAssetOfficialAccountCpPo().setStatus(req.getStatus());
        req.getAssetOfficialAccountCpPo().setUpdateTime(date);
        assetOfficialAccountCpService.updateById(req.getAssetOfficialAccountCpPo());
        //新增历史记录表
        AssetOfficialAccountHistory assetOfficialAccountHistory = new AssetOfficialAccountHistory();
        BeanUtils.copyProperties(req.getAssetOfficialAccountCpPo(), assetOfficialAccountHistory);
        assetOfficialAccountHistoryService.save(assetOfficialAccountHistory);
    }

    private void updateMinZiandHistory(AssetCurrentShRequest req, Date date) {
        req.getAssetMiniProgramsCpPo().setStatus(req.getStatus());
        req.getAssetMiniProgramsCpPo().setUpdateTime(date);
        assetMiniProgramsCpService.updateById(req.getAssetMiniProgramsCpPo());
        //新增历史记录表
        AssetMiniProgramsHistory assetMiniProgramsHistory = new AssetMiniProgramsHistory();
        BeanUtils.copyProperties(req.getAssetMiniProgramsCpPo(), assetMiniProgramsHistory);
        assetMiniProgramsHistoryService.save(assetMiniProgramsHistory);
    }

    private void updateZiandHistory(AssetCurrentShRequest req, Date date) {
        //根据资产id和任务id删除五张表数据
        assetCurrentCpService.deletByAssetIdandTaskId(req.getAssetCurrentCpPo().getId(), req.getAssetCurrentCpPo().getTaskId());
        assetBusinessFormCpService.deletByAssetIdandTaskId(req.getAssetCurrentCpPo().getId(), req.getAssetCurrentCpPo().getTaskId());
        assetSupplyChainCpService.deletByAssetIdandTaskId(req.getAssetCurrentCpPo().getId(), req.getAssetCurrentCpPo().getTaskId());
        unitOtherConcatCpService.deletByAssetIdandTaskId(req.getAssetCurrentCpPo().getId(), req.getAssetCurrentCpPo().getTaskId());
        assetBasicNetworkCpService.deletByAssetIdandTaskId(req.getAssetCurrentCpPo().getId(), req.getAssetCurrentCpPo().getTaskId());
        StringBuilder a = new StringBuilder();
        if (!req.getAssetCurrentCpPo().getGlymList().isEmpty()) {
            req.getAssetCurrentCpPo().getGlymList().forEach(x -> {
                if (!Objects.equals(x.getKey(), "") && x.getKey() != null) {
                    a.append(x.getKey());
                    a.append(",");
                }
            });
        }
        req.getAssetCurrentCpPo().setGlym(a.toString());
        StringBuilder b = new StringBuilder();
        if (!req.getAssetCurrentCpPo().getGlIpList().isEmpty()) {
            req.getAssetCurrentCpPo().getGlIpList().forEach(x -> {
                if (!Objects.equals(x.getKey(), "") && x.getKey() != null) {
                    b.append(x.getKey());
                    b.append(",");
                }
            });
        }
        req.getAssetCurrentCpPo().setGlIp(b.toString());
        req.getAssetCurrentCpPo().setStatus(req.getStatus());

        // 设置更新时间
        req.getAssetCurrentCpPo().setUpdateTime(date);
        AssetCurrentHistory assetCurrentHistory = new AssetCurrentHistory();
        assetCurrentCpService.save(req.getAssetCurrentCpPo());
        //新增新监管业务形态
        if (req.getAssetCurrentCpPo().getXjgywxt() != null) {
            req.getAssetCurrentCpPo().getXjgywxt().setAssetId(req.getAssetCurrentCpPo().getId());
            req.getAssetCurrentCpPo().getXjgywxt().setTaskId(req.getAssetCurrentCpPo().getTaskId());
            assetBusinessFormCpService.save(req.getAssetCurrentCpPo().getXjgywxt());
        }
        if (!req.getAssetCurrentCpPo().getGylxxList().isEmpty()) {
            for (AssetSupplyChainCpPo items : req.getAssetCurrentCpPo().getGylxxList()) {
                items.setAssetId(req.getAssetCurrentCpPo().getId());
                items.setTaskId(req.getAssetCurrentCpPo().getTaskId());

            }
            //新增供应链
            assetSupplyChainCpService.saveBatch(req.getAssetCurrentCpPo().getGylxxList());
        }
        if (!req.getAssetCurrentCpPo().getJcwlList().isEmpty()) {
            for (AssetBasicNetworkCpPo items : req.getAssetCurrentCpPo().getJcwlList()) {
                items.setAssetId(req.getAssetCurrentCpPo().getId());
                items.setTaskId(req.getAssetCurrentCpPo().getTaskId());

            }
            //新增基础网络
            assetBasicNetworkCpService.saveBatch(req.getAssetCurrentCpPo().getJcwlList());
        }
        if (!req.getAssetCurrentCpPo().getOtherConcat().isEmpty()) {
            for (UnitOtherConcatCpPo items : req.getAssetCurrentCpPo().getOtherConcat()) {
                items.setAssetId(req.getAssetCurrentCpPo().getId());
                items.setTaskId(req.getAssetCurrentCpPo().getTaskId());
            }
            //新增其他联系人
            unitOtherConcatCpService.saveBatch(req.getAssetCurrentCpPo().getOtherConcat());
        }
        //新增历史记录
        saveHistory(req, a, b, date, assetCurrentHistory);
    }

    private void saveHistory(AssetCurrentShRequest req, StringBuilder a, StringBuilder b, Date date, AssetCurrentHistory assetCurrentHistory) {
        //新增历史记录
        StringBuilder c = new StringBuilder();
        if (!req.getAssetCurrentCpPo().getGlymList().isEmpty()) {
            req.getAssetCurrentCpPo().getGlymList().forEach(x -> {
                if (!Objects.equals(x.getKey(), "") && x.getKey() != null) {
                    c.append(x.getKey());
                    c.append(",");
                }
            });
        }
        req.getAssetCurrentCpPo().setGlym(a.toString());
        StringBuilder d = new StringBuilder();
        if (!req.getAssetCurrentCpPo().getGlIpList().isEmpty()) {
            req.getAssetCurrentCpPo().getGlIpList().forEach(x -> {
                if (!Objects.equals(x.getKey(), "") && x.getKey() != null) {
                    d.append(x.getKey());
                    d.append(",");
                }
            });
        }
        req.getAssetCurrentCpPo().setGlIp(b.toString());
        req.getAssetCurrentCpPo().setStatus(req.getStatus());

        // 设置更新时间
        req.getAssetCurrentCpPo().setUpdateTime(date);
        BeanUtils.copyProperties(req.getAssetCurrentCpPo(), assetCurrentHistory);
        assetCurrentHistoryService.save(assetCurrentHistory);

        //新增新监管业务形态历史表
        if (req.getAssetCurrentCpPo().getXjgywxt() != null) {
            req.getAssetCurrentCpPo().getXjgywxt().setAssetId(req.getAssetCurrentCpPo().getId());
            req.getAssetCurrentCpPo().getXjgywxt().setTaskId(req.getAssetCurrentCpPo().getTaskId());
            AssetBusinessFormHistory assetBusinessFormHistory = new AssetBusinessFormHistory();
            assetBusinessFormHistory.setCopyId(req.getAssetCurrentCpPo().getCurrentId());
            BeanUtils.copyProperties(req.getAssetCurrentCpPo().getXjgywxt(), assetBusinessFormHistory);
            assetBusinessFormHistoryService.save(assetBusinessFormHistory);

        }
        if (!req.getAssetCurrentCpPo().getGylxxList().isEmpty()) {
            for (AssetSupplyChainCpPo items : req.getAssetCurrentCpPo().getGylxxList()) {
                items.setAssetId(req.getAssetCurrentCpPo().getId());
                items.setTaskId(req.getAssetCurrentCpPo().getTaskId());

            }
            //新增供应链历史表
            List<AssetSupplyChainHistory> assetSupplyChainHistoryList = req.getAssetCurrentCpPo().getGylxxList().stream()
                    .map(cpPo -> {
                        AssetSupplyChainHistory assetSupplyChainHistory = new AssetSupplyChainHistory();
                        assetSupplyChainHistory.setCopyId(req.getAssetCurrentCpPo().getCurrentId());
                        BeanUtils.copyProperties(cpPo, assetSupplyChainHistory); // 复制属性
                        return assetSupplyChainHistory; // 返回新对象
                    })
                    .collect(Collectors.toList()); // 收集到列表中
            assetSupplyChainHistoryService.saveBatch(assetSupplyChainHistoryList);
        }
        if (!req.getAssetCurrentCpPo().getJcwlList().isEmpty()) {
            for (AssetBasicNetworkCpPo items : req.getAssetCurrentCpPo().getJcwlList()) {
                items.setAssetId(req.getAssetCurrentCpPo().getId());
                items.setTaskId(req.getAssetCurrentCpPo().getTaskId());

            }
            //新增基础网络历史表
            List<AssetBasicNetworkHistory> assetSupplyChainHistoryList = req.getAssetCurrentCpPo().getJcwlList().stream()
                    .map(cpPo -> {
                        AssetBasicNetworkHistory assetBasicNetworkHistory = new AssetBasicNetworkHistory();
                        assetBasicNetworkHistory.setCopyId(req.getAssetCurrentCpPo().getCurrentId());
                        BeanUtils.copyProperties(cpPo, assetBasicNetworkHistory); // 复制属性
                        return assetBasicNetworkHistory; // 返回新对象
                    })
                    .collect(Collectors.toList()); // 收集到列表中
            assetBasicNetworkHistoryService.saveBatch(assetSupplyChainHistoryList);
        }
        if (!req.getAssetCurrentCpPo().getOtherConcat().isEmpty()) {
            for (UnitOtherConcatCpPo items : req.getAssetCurrentCpPo().getOtherConcat()) {
                items.setAssetId(req.getAssetCurrentCpPo().getId());
                items.setTaskId(req.getAssetCurrentCpPo().getTaskId());
            }
            //新增其他联系人
            List<UnitOtherConcatHistory> unitOtherConcatHistoryList = req.getAssetCurrentCpPo().getOtherConcat().stream()
                    .map(cpPo -> {
                        UnitOtherConcatHistory unitOtherConcatHistory = new UnitOtherConcatHistory();
                        unitOtherConcatHistory.setCopyId(req.getAssetCurrentCpPo().getCurrentId());
                        BeanUtils.copyProperties(cpPo, unitOtherConcatHistory); // 复制属性
                        return unitOtherConcatHistory; // 返回新对象
                    })
                    .collect(Collectors.toList()); // 收集到列表中
            unitOtherConcatHistoryService.saveBatch(unitOtherConcatHistoryList);
        }
    }

    private void syb(AssetCurrentShRequest req) {
        if (req.getType() == 1) {
            //小程序
            AssetMiniProgramsCpPo assetMiniProgramsCpPo = assetMiniProgramsCpService.findByTaskId(req.getAssetId());
            //删除原有数据
            if (assetMiniProgramsCpPo != null) {
                assetMiniProgramsService.deleteIdList(Collections.singletonList(assetMiniProgramsCpPo.getAssetId()));
                //将子表数据复制到主表中
                AssetMiniPrograms assetMiniPrograms = new AssetMiniPrograms();
                BeanUtils.copyProperties(assetMiniProgramsCpPo, assetMiniPrograms); // 复制属性
                assetMiniPrograms.setId(null);
                assetMiniProgramsService.save(assetMiniPrograms);
            }

        }
        if (req.getType() == 2) {
            //公众号资产
            AssetOfficialAccountCpPo assetOfficialAccountCpPo = assetOfficialAccountCpService.findByTaskId(req.getAssetId());

            //删除原有数据
            if (assetOfficialAccountCpPo != null) {
                assetOfficialAccountService.deleteIdList(Collections.singletonList(assetOfficialAccountCpPo.getAssetId()));
                //将子表数据复制到主表中
                AssetOfficialAccount assetOfficialAccount = new AssetOfficialAccount();
                BeanUtils.copyProperties(assetOfficialAccountCpPo, assetOfficialAccount); // 复制属性
                assetOfficialAccountService.save(assetOfficialAccount);
            }


        }
        if (req.getType() == 3) {
            //电子邮件资产
            //根据assetId查询查询数据
            AssetEmailCpPo assetEmailCpPo = assetEmailCpService.findByTaskId(req.getAssetId());
            //删除原有数据
            if (assetEmailCpPo != null) {
                assetEmailService.deleteIdList(Collections.singletonList(assetEmailCpPo.getAssetId()));
                //将子表数据复制到主表中
                AssetEmail assetEmail = new AssetEmail();
                BeanUtils.copyProperties(assetEmailCpPo, assetEmail); // 复制属性
                assetEmail.setId(null);
                assetEmailService.save(assetEmail);
            }
        }
        if (req.getType() == 4) {
            //移动应用程序资产
            //根据资产id查询
            AssetAppCpPo assetAppCpPo = assetAppCpService.findByTaskId(req.getAssetId());
            //删除原有数据
            if (assetAppCpPo != null) {
                assetAppService.deleteIdList(Collections.singletonList(assetAppCpPo.getAssetId()));
                //将子表数据复制到主表中
                AssetApp assetApp = new AssetApp();
                BeanUtils.copyProperties(assetAppCpPo, assetApp); // 复制属性
                assetApp.setId(null);
                assetAppService.save(assetApp);
            }


        }


    }

    private void ifCq(AssetCurrentShRequest req, AssetTask assetTask) {

        if (req.getStatus().equals(3)) {
            AssetTask newAssetTask = new AssetTask();
            //比较是否超期
            int deadlineStatus = extracted(assetTask);
            int deadlineCount = Optional.ofNullable(assetTask.getDeadlineCount()).orElse(0);
            int count = Optional.ofNullable(assetTask.getCount()).orElse(0);
            BeanUtils.copyProperties(assetTask, newAssetTask);
            if (deadlineStatus == 1) {
                //超期
                newAssetTask.setDeadlineCount(deadlineCount + 1);
                assetTaskService.update(newAssetTask);
            } else {
                newAssetTask.setCount(count + 1);
                assetTaskService.update(newAssetTask);
            }

        }
    }

    //当前时间喝任务截至时间比较
    private int extracted(AssetTask assetTask) {
        int status = 0;
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 创建格式化器，时间部分使用冒号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前的日期和时间
        String formattedDateTime = now.format(formatter);
        //获取任务截至时间
        String deadLine = assetTask.getTaskDeadline();
        // 转换为 LocalDateTime，使用相同的格式
        LocalDateTime deadlineDate = LocalDateTime.parse(deadLine, formatter);
        LocalDateTime currentDate = LocalDateTime.parse(formattedDateTime, formatter);
        if (deadlineDate.isBefore(currentDate)) {
            //超期
            status = 1;
        } else {
            //未超期
            status = 2;
        }
        return status;
    }

    //web
    private void taskSaveOrDelete(AssetCurrentShRequest req) {
        // 根据资产id查询五张数据
        AssetCurrentCpPo currentCpPo = assetCurrentCpService.findByTaskId(req.getAssetId());
        //删除主表原有数据
        if (currentCpPo != null) {
            assetCurrentService.deleteIdList(currentCpPo.getId());
            //将子表数据复制到主表中
            AssetCurrent current = new AssetCurrent();
            BeanUtils.copyProperties(currentCpPo, current); // 复制属性
            current.setId(null);
            assetCurrentService.save(current);
        }

        //AssetBusinessFormCpPo
        AssetBusinessFormCpPo businessFormCpPo = assetBusinessFormCpService.findByTaskId(req.getAssetId());
        //删除原有数据
        if (businessFormCpPo != null) {
            assetBusinessFormService.deleteIdList(Collections.singletonList(businessFormCpPo.getAssetId()));
            //将子表数据复制到主表中
            AssetBusinessForm businessForm = new AssetBusinessForm();
            BeanUtils.copyProperties(businessFormCpPo, businessForm); // 复制属性
            businessForm.setId(null);
            assetBusinessFormService.save(businessForm);
        }
        //AssetBasicNetworkCpPo
        AssetBasicNetworkCpPo networkCpPo = assetBasicNetworkCpService.findByTaskId(req.getAssetId());
        //删除原有数据
        if (networkCpPo != null) {
            assetBasicNetworkService.deleteIdList(Collections.singletonList(networkCpPo.getAssetId()));
            AssetBasicNetwork network = new AssetBasicNetwork();
            BeanUtils.copyProperties(networkCpPo, network);
            network.setId(null);
            assetBasicNetworkService.save(network);
        }

        //AssetSupplyChainCpPo
        AssetSupplyChainCpPo supplyChainCpPo = assetSupplyChainCpService.findByTaskId(req.getAssetId());
        //删除原有数据
        if (supplyChainCpPo != null) {
            assetSupplyChainService.deleteIdList(Collections.singletonList(supplyChainCpPo.getAssetId()));
            AssetSupplyChain supplyChain = new AssetSupplyChain();
            BeanUtils.copyProperties(supplyChainCpPo, supplyChain);
            supplyChain.setId(null);
            assetSupplyChainService.save(supplyChain);
        }

        //UnitOtherConcatCpPo
        UnitOtherConcatCpPo unitOtherConcatCpPo = unitOtherConcatCpService.findByTaskId(req.getAssetId());
        //删除原有数据
        if (unitOtherConcatCpPo != null) {
            unitOtherConcatService.deleteIdList(Collections.singletonList(unitOtherConcatCpPo.getAssetId()));
            UnitOtherConcat unitOtherConcat = new UnitOtherConcat();
            BeanUtils.copyProperties(unitOtherConcatCpPo, unitOtherConcat); // 复制属性
            unitOtherConcat.setConcatId(null);
            unitOtherConcatService.save(unitOtherConcat);
        }
    }

    @Override
    public Page<AssetdwHcResponse> dwHc(Page<AssetdwHcResponse> assetdwHcResponsePage, AssetdwHcRequest req) {

        return assetTaskDao.dwHc(assetdwHcResponsePage, req);
    }

    @Override
    public List<AssetdwHcResponse> export(AssetdwHcRequest req) {
        return assetTaskDao.export(req);
    }

    @Override
    public List<AssetTask> taskList(String dwmc) {
        return assetTaskDao.taskList(dwmc);
    }

    @Override
    public void updateYgtByTaskId(Integer taskId, Integer count) {
        assetTaskDao.updateYgtByTaskId(taskId, count);
    }

    @Override
    public void close(Integer taskId) {
        assetTaskDao.close(taskId);
    }

    @Override
    public List<AssetdwHcBlResponse> dwHcBl(AssetdwHcRequest req) {
        return assetTaskDao.dwHcBl(req);
    }

    @Override
    public AssetTask findByDwmc(String dwmc) {
        return assetTaskDao.findByDwmc(dwmc);
    }

    @Override
    public AssetTask findByTaskId(Integer taskId) {
        return assetTaskDao.findBytaskId(taskId);
    }

    //创建任务流程
    private void getTaskStatus(AssetCurrentShRequest req) {
        AssetLc assetLc = new AssetLc();

        if (req.getStatus() == 3) {
            assetLc.setTaskId(req.getTaskId());
            assetLc.setXfTime(LocalDateTime.now());
            assetLc.setAssetName("管理员审核通过" + req.getXtmc());
            assetLcService.insert(assetLc);
        } else if (req.getStatus() == 4) {
            assetLc.setTaskId(req.getTaskId());
            assetLc.setAssetName("管理员审核不通过" + req.getXtmc());
            assetLc.setXfTime(LocalDateTime.now());
            assetLcService.insert(assetLc);

        }
    }


}