package com.pusong.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pusong.business.domain.PsContractInfo;
import com.pusong.business.domain.PsTaskAppoint;
import com.pusong.business.domain.bo.AppointBo;
import com.pusong.business.domain.bo.MediaCompanySaveBo;
import com.pusong.business.domain.bo.PsTaskMediaBo;
import com.pusong.business.domain.bo.PsTaskQueryBo;
import com.pusong.business.domain.vo.*;
import com.pusong.business.enums.ApproverTypeEnum;
import com.pusong.business.enums.ContractStatusEnum;
import com.pusong.business.enums.TaskStatusEnum;
import com.pusong.business.enums.TaskStatusEnum.*;
import com.pusong.business.enums.TaskTypeEnum;
import com.pusong.business.mapper.PsContractInfoMapper;
import com.pusong.business.mapper.PsTaskAppointMapper;
import com.pusong.business.service.*;
import com.pusong.business.service.approver.ApproverContainer;
import com.pusong.business.service.approver.ApproverService;
import com.pusong.common.core.exception.ServiceException;
import com.pusong.common.core.utils.DateUtils;
import com.pusong.common.core.utils.StringUtils;
import com.pusong.common.mybatis.core.page.PageQuery;
import com.pusong.common.mybatis.core.page.TableDataInfo;
import com.pusong.common.satoken.utils.LoginHelper;
import com.pusong.system.domain.vo.SysOssVo;
import com.pusong.system.service.ISysOssService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.executor.BatchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.pusong.business.domain.PsTaskMain;
import com.pusong.business.mapper.PsTaskMainMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 主任务Service业务层处理
 *
 * @author wls
 * @date 2024-08-07
 */
@RequiredArgsConstructor
@Service
public class PsTaskServiceImpl implements IPsTaskService {

    private static final Logger log = LoggerFactory.getLogger(PsTaskServiceImpl.class);
    private final PsTaskMainMapper baseMapper;
    private final PsTaskAppointMapper appointMapper;
    private final IPsTaskMediaService mediaService;
    private final IPsCompanyInfoService companyInfoService;
    private final ISysOssService ossService;
    @Resource
    private ApproverContainer approverContainer;
    @Resource
    private PsContractInfoMapper contractInfoMapper;
    private final IPsApproverRecordService approverRecordService;
    /**
     * 新增主任务
     *
     * @param add 主任务
     * @return 是否新增成功
     */
    @Override
    public Boolean insert(PsTaskMain add) {
        boolean flag = baseMapper.insert(add) > 0;

        return flag;
    }

    @Override
    public Boolean insertBatch(Collection<PsTaskMain> bos){
        List<BatchResult> insert = baseMapper.insert(bos);
        return !insert.isEmpty();
    }
    /**
     * 分页查询主任务列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 主任务分页列表
     */
    public TableDataInfo<PsTaskMainVo> queryPageList(PsTaskQueryBo bo, PageQuery pageQuery){
        QueryWrapper<PsTaskMain> lqw = buildQueryWrapper(bo);
        Page<PsTaskMainVo> page;
        if(StringUtils.equals(TaskTypeEnum.INVOICE.getCode(), bo.getType())){//发票任务无需数据权限
            page = baseMapper.queryInvoiceTaskPageList(pageQuery.build(), lqw);
            for (PsTaskMainVo vo : page.getRecords()) {
                PsInvoiceVo psInvoiceVo = JSONObject.parseObject(vo.getExtend(), PsInvoiceVo.class);
                vo.setPsInvoiceVo(psInvoiceVo);
                vo.setExtend(null);
            }
        }else{
            page = baseMapper.queryTaskPageList(pageQuery.build(), lqw);
        }

        fillInfo(page);


        return TableDataInfo.build(page);
    }

    private void fillInfo(Page<PsTaskMainVo> page) {
        String contractCode = null;
        List<Long> serviceCompanyIdList = new ArrayList<>();
        for (PsTaskMainVo vo : page.getRecords()) {
            if(vo.getStartDate() != null){
                vo.setNumOfDat(DateUtils.calWorkDate(vo.getStartDate(),new Date()));
            }
            //任务作废审批
            vo.setTaskStatusDesc(approverRecordService.getLastFail(vo.getId() + "",null,List.of(ApproverTypeEnum.TASKCANCE.getCode())));

            //装填服务公司信息
            if (vo.getServiceCompanyId() != null){
//                serviceCompanyIdList.add(vo.getServiceCompanyId());
//                contractCode = vo.getContractCode();
                PsCompanyInfoVo psCompanyInfoVo = companyInfoService.queryVoAndProxyById(vo.getServiceCompanyId(), vo.getContractCode());
                vo.setPsCompanySerivceVo(psCompanyInfoVo);
            }
            if (vo.getTaskType().equals("2")){
                vo.setBusinessTypeName(vo.getBusinessType());
            }
        }

        //装填服务公司信息
        if (!serviceCompanyIdList.isEmpty()){
            List<PsCompanyInfoVo> serviceCompany = companyInfoService.queryVoAndProxyByIds(serviceCompanyIdList, contractCode);
            Map<Long, PsCompanyInfoVo> serviceCompanyMap = serviceCompany.stream().collect(Collectors.toMap(PsCompanyInfoVo::getId, v -> v));
            for (PsTaskMainVo vo : page.getRecords()) {
                vo.setPsCompanySerivceVo(serviceCompanyMap.get(vo.getServiceCompanyId()));
            }
        }
    }

    /**
     * 分页查询子任务列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 主任务分页列表
     */
    public TableDataInfo<PsTaskMainVo> queryChildPageList(PsTaskQueryBo bo, PageQuery pageQuery){
        Long id = bo.getId(); //此时是子任务的id
        bo.setId(null);
        //执行者的查询条件与主任中不同需要单独处理
        String ex = bo.getExecutor();
        bo.setExecutor(null);
        QueryWrapper<PsTaskMain> lqw = buildQueryWrapper(bo);
        lqw.exists(StringUtils.isNotBlank(ex), "select 1 from sys_user su where  appo.executor = su.user_id and  su.nick_name like '%" + ex + "%'");
        lqw.eq("appo.appoint_type",bo.getAppointType());
        lqw.eq(id != null,"appo.id",id);
        lqw.eq(StringUtils.isNotBlank(bo.getAppointStatus()),"appo.appoint_status", bo.getAppointStatus());
        log.info(lqw.getCustomSqlSegment());
        Page<PsTaskMainVo> page = baseMapper.queryChildTaskPageList(pageQuery.build(), lqw);
        fillInfo(page);

        return TableDataInfo.build(page);
    }

    /**
     * 查询主任务进度
     *
     * @param id 任务主表主键
     */
    public TaskPlanVo plan(Long id){
        List<PsTaskAppoint> list = appointMapper.selectList(Wrappers.<PsTaskAppoint>lambdaQuery().eq(PsTaskAppoint::getTaskId, id)
                .ne(PsTaskAppoint::getAppointStatus,AppointStatusEnum.CANCEL.getCode()).eq(PsTaskAppoint::getDelFlag,"0"));
        TaskPlanVo planVo = new TaskPlanVo();
        if(CollectionUtils.isEmpty(list)){return planVo;}
        list.forEach(item->{
            if(StringUtils.equals("1",item.getAppointType())){
                planVo.setInExector(item.getExecutor());
                planVo.setInState(item.getAppointStatus());
            }else if (StringUtils.equals("2",item.getAppointType())){
                planVo.setOutExector(item.getExecutor());
                planVo.setOutState(item.getAppointStatus());
            }else if (StringUtils.equals("3",item.getAppointType())){
                planVo.setSecExector(item.getExecutor());
                planVo.setSecState(item.getAppointStatus());
            }
        });
        planVo.setState(baseMapper.selectById(id).getTaskStatus());
        return planVo;
    }
    /**
     * 根据任务id查询任务的公司信息和资料信息
     *
     * @param id 任务主表主键
     * @return 公司及资料信息
     */
    public PsTaskMainVo queryInfo(String id){
        //查询任务信息
        PsTaskMain mainTask = baseMapper.selectById(id);
        Long customId = 0l;
        Long companyId ;
        if(mainTask == null){
//            PsContractInfo con = contractInfoMapper.selectOne(Wrappers.<PsContractInfo>lambdaQuery().eq(PsContractInfo::getContractCode, id).last("limit 1"));
            companyId = Long.valueOf(id);
            PsCompanyInfoVo psCompanyInfoVo = companyInfoService.queryById(companyId);
            if (psCompanyInfoVo != null){
                customId = psCompanyInfoVo.getCustomId();
            }
        }else{
            customId = mainTask.getCustomId();
            companyId = mainTask.getServiceCompanyId();
        }

        //查询公司信息
        PsCompanyInfoVo companyInfoVo = companyInfoService.queryById(companyId);
        //查询资料信息
        List<PsTaskMediaVo> list = mediaService.queryMediaList(customId, companyId);
        PsTaskMainVo psTaskMainVo = new PsTaskMainVo();
        psTaskMainVo.setCompanyInfoVo(companyInfoVo);
        psTaskMainVo.setTaskMediaVoList(list);
        return psTaskMainVo;
    }
    /**
     * 根据合同编码查询任务
     *
     * @param contractCode 合同编码
     * @return
     */
    public List<PsTaskMain> queryByContractCode(String contractCode){
        return baseMapper.selectList(Wrappers.<PsTaskMain>lambdaQuery().eq(PsTaskMain::getContractCode, contractCode)
                .eq(PsTaskMain::getTaskType,TaskTypeEnum.CONTRACT.getCode()).ne(PsTaskMain::getTaskStatus,TaskStatusEnum.CANCEL.getCode()));
    }

    public PsTaskMain queryByContractCodeAndServiceCompanyId(String contractCode, Long serviceCompanyId){
        return baseMapper.selectOne(Wrappers.<PsTaskMain>lambdaQuery().eq(PsTaskMain::getContractCode, contractCode)
                .eq(PsTaskMain::getTaskType, TaskTypeEnum.CONTRACT.getCode())
                .eq(PsTaskMain::getServiceCompanyId, serviceCompanyId)
                .ne(PsTaskMain::getTaskStatus, TaskStatusEnum.CANCEL.getCode()));
    }
    /**
     * 上传资料和公司信息
     *
     * @param save 公司及资料信息
     * @return
     */
    @Override
    @Transactional
    public void saveInfo(MediaCompanySaveBo save){
        //1.1信息校验
        Long customerId ;
        Long companyId ;
        if(save.getId() != null){
            PsTaskMain taskMain = baseMapper.selectById(save.getId());
//            if(!TaskStatusEnum.canUpload(taskMain.getTaskStatus())){
//                log.error("任务已完成，无法修改");
//                throw new ServiceException("任务已完成，无法修改");
//            }
            customerId = taskMain.getCustomId();
            companyId = taskMain.getServiceCompanyId();
        }else if(StringUtils.isNotBlank(save.getContractCode())){
            PsContractInfo con = contractInfoMapper.selectOne(Wrappers.<PsContractInfo>lambdaQuery().eq(PsContractInfo::getContractCode, save.getContractCode()));
            customerId = con.getCustomId();
            companyId = con.getCompanyId();
        }else{
            log.error("必传参数为空");
            throw new ServiceException("必传参数为空");
        }

        save.getPsCompanyInfo().setId(companyId);
        if(!CollectionUtils.isEmpty(save.getMediaBoList())){
            boolean repetition = save.getMediaBoList().stream().map(PsTaskMediaBo::getMediaType)
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                    .entrySet().stream().anyMatch(e -> e.getValue() > 1);
            if(repetition){
                log.error("请求的任务类型重复");
                throw new ServiceException("请求的任务类型重复，请刷新页面重试");
            }
        }

        //1.2保存公司信息
        companyInfoService.saveBo(save.getPsCompanyInfo());
        if(CollectionUtils.isEmpty(save.getMediaBoList())){
            return;
        }
        //2.1查询原始的合同资料信息
        List<PsTaskMediaVo> mediaList = mediaService.queryMediaList(customerId,companyId);
        //此次需要保存的资料id（后续删除使用）
        List<String> ossIdList = new ArrayList<>();
        save.getMediaBoList().forEach(item->{
            item.setCustomId(customerId);
            item.setCompanyId(companyId);
            if(StringUtils.isNotBlank(item.getMediaOssId()) && !StringUtils.equals("-1",item.getMediaOssId())){
                ossIdList.addAll(List.of(item.getMediaOssId().split(",")));
            }
        });
        //2.2保存最新的合同资料信息
        mediaService.saveMediaList(save.getMediaBoList());
        //把历史的资料id储存到list中
        List<String> list = mediaList.stream().filter(item -> StringUtils.isNotBlank(item.getMediaOssId())).map(item -> item.getMediaOssId().split(",")).flatMap(Arrays::stream).collect(Collectors.toList());
        //去掉与本次保存重叠的资料，和-1
        list.removeIf(item->StringUtils.equals("-1", item) || ossIdList.contains(item));
        //2.3删除无用资料
        if(CollectionUtils.isNotEmpty(list)){
            ossService.deleteWithValidByIds(list.stream().map(Long::parseLong).collect(Collectors.toList()),false);
        }
    }
    /**
     * 任务委派
     *
     * @param bo 任务委派请求信息
     * @return
     */
    @Override
    @Transactional
    public void appoint(AppointBo bo){
        //前置校验
        PsTaskMain mainTask = baseMapper.selectById(bo.getId());
        if(!TaskStatusEnum.canAppoint(mainTask.getTaskStatus())){
            throw new ServiceException("任务已完成，无法继续派单");
        }
        if(StringUtils.equals(TaskTypeEnum.INVOICE.getCode(),mainTask.getTaskType())){
            throw new ServiceException("发票任务无需派单");
        }

        List<PsTaskAppoint> list = appointMapper.selectList(Wrappers.<PsTaskAppoint>lambdaQuery()
                .eq(PsTaskAppoint::getDelFlag,"0").eq(PsTaskAppoint::getTaskId, bo.getId())
                .eq(PsTaskAppoint::getAppointType, bo.getAppointType())
                .ne(PsTaskAppoint::getAppointStatus, AppointStatusEnum.CANCEL.getCode()));
        if(CollectionUtils.isNotEmpty(list)){
            throw new ServiceException("操作失败，任务已委派");
        }
        //如果是第一次派单，需要修改任务状态
        if(StringUtils.equals(TaskStatusEnum.INIT.getCode(),mainTask.getTaskStatus())){
            PsTaskMain update = new PsTaskMain();
            update.setId(mainTask.getId());
            update.setTaskStatus(TaskStatusEnum.ING.getCode());
            update.setStartDate(new Date());
            update.setOperateUser(LoginHelper.getUserId());
            baseMapper.updateById(update);
            contractInfoMapper.update(Wrappers.<PsContractInfo>lambdaUpdate().set(PsContractInfo::getContractStatus, ContractStatusEnum.EXECUTION.getCode())
                    .eq(PsContractInfo::getContractCode,mainTask.getContractCode()).eq(PsContractInfo::getDelFlag,0));

        }

        for (Long userId : bo.getUserIds()) {
            PsTaskAppoint psTaskAppoint = new PsTaskAppoint();
            psTaskAppoint.setAppointStatus(AppointStatusEnum.ING.getCode());
            psTaskAppoint.setAppointType(bo.getAppointType());
            psTaskAppoint.setContractCode(mainTask.getContractCode());
            psTaskAppoint.setTaskId(mainTask.getId());
            psTaskAppoint.setExecutor(userId);
            psTaskAppoint.setTaskContentDesc(bo.getTaskContentDesc());
            appointMapper.insert(psTaskAppoint);
        }

    }
    /**
     * 主任务完成
     *
     * @param id 任务主键id
     * @return
     */
    public String finishMain(Long id){
        PsTaskMain main = baseMapper.selectById(id);
        if(!TaskStatusEnum.canFinish(main.getTaskStatus())){
            throw new ServiceException("此任务无法执行此操作，请刷新页面后重新操作");
        }
        List<PsTaskAppoint> list = appointMapper.selectList(Wrappers.<PsTaskAppoint>lambdaQuery()
                        .eq(PsTaskAppoint::getDelFlag,"0").eq(PsTaskAppoint::getTaskId, id)
                        .notIn(PsTaskAppoint::getAppointStatus, AppointStatusEnum.getEndStauts()));
        if(CollectionUtils.isNotEmpty(list)){
            throw new ServiceException("操作失败，子任务未完成");
        }
        main.setTaskStatus(TaskStatusEnum.FINISH.getCode());
        main.setFinishDate(new Date());
        baseMapper.updateById(main);
        return main.getContractCode();
    }
    /**
     * 子任务完成
     *
     * @param id 任务主键id
     * @return
     */
    public void finishChild(Long id,String desc){
        PsTaskAppoint appoint = appointMapper.selectById(id);
        if(StringUtils.equals("3",appoint.getAppointType()) && StringUtils.isBlank(desc)){
            throw  new ServiceException("请填写特勤备注");
        }
        if(!AppointStatusEnum.canFinish(appoint.getAppointStatus())){
            throw  new ServiceException("此任务无法执行此操作，请刷新页面后重新操作");
        }
//        ApproverService service = approverContainer.getService(ApproverTypeEnum.TASKFINISH.getCode());
//        service.apply(id+"",appoint.getContractCode(),desc,appoint.getAppointType());
//        appoint.setAppointStatus(AppointStatusEnum.OA.getCode());
        appoint.setAppointStatus(TaskStatusEnum.AppointStatusEnum.FINISH.getCode());
        appoint.setFinishDate(new Date());
        appoint.setTaskDesc(desc);
        appointMapper.updateById(appoint);
    }

    /**
     * 获取任务执行者列表
     *
     * @param id 主任务主键id
     * @return
     */
    public Map<String, PsTaskAppointVo> getExecutors(Long id){
        List<PsTaskAppointVo> list = appointMapper.selectVoList(Wrappers.<PsTaskAppoint>lambdaQuery()
                .eq(PsTaskAppoint::getDelFlag,"0").eq(PsTaskAppoint::getTaskId, id)
                .ne(PsTaskAppoint::getAppointStatus, AppointStatusEnum.CANCEL.getCode()));
        Map<String, PsTaskAppointVo> map = new HashMap<>();
        if(CollectionUtils.isNotEmpty(list)){
            map = list.stream().collect(Collectors.groupingBy(PsTaskAppointVo::getAppointType,
                    Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingLong(PsTaskAppointVo::getId)), Optional::get)));
        }
        return map;
    }


    /**
     * 任务改派
     * @param id 任务委派表id
     * @param executorId 任务新的执行者id
     */
    public void taskReset(Long id,Long executorId){
        PsTaskAppoint appoint = appointMapper.selectById(id);
        if(!AppointStatusEnum.canReset(appoint.getAppointStatus())){
            throw new ServiceException("操作失败，子任务状态无法改派");
        }
        appoint.setExecutor(executorId);
        appointMapper.updateById(appoint);
    }
    /**
     * 免费工单任务作废
     * @param id 任务主表id
     * @param desc 作废原因
     */
    public void cancel(Long id, String desc){
        PsTaskMain info = baseMapper.selectById(id);
        if(!StringUtils.equals(TaskTypeEnum.FREE.getCode(),info.getTaskType())){
            throw new ServiceException("只有免费工单的任务可以作废");
        }
        //发起审批
        ApproverService service = approverContainer.getService(ApproverTypeEnum.TASKCANCE.getCode());
        service.apply(id+"", info.getContractCode(),desc, info.getTaskStatus());
        //修改状态为审批中
        info.setTaskStatus(TaskStatusEnum.CANCELAPPO.getCode());
        baseMapper.updateById(info);
    }

    private QueryWrapper<PsTaskMain> buildQueryWrapper(PsTaskQueryBo bo) {
        QueryWrapper<PsTaskMain> lqw = new QueryWrapper<PsTaskMain>();
        lqw.eq("main.del_flag","0");


        lqw.ne(StringUtils.isBlank(bo.getTaskStatus()), "main.task_status", TaskStatusEnum.CANCEL.getCode());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskStatus()),"main.task_status", bo.getTaskStatus());

        if(bo.getType() == null){
            lqw.in("main.task_type", List.of("1", "2"));
        }else{
            lqw.eq("main.task_type", bo.getType());
        }



        lqw.eq(bo.getId() != null,"main.id",bo.getId());
        lqw.like(StringUtils.isNotBlank(bo.getContractCode()), "main.contract_code", bo.getContractCode());

        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), "com.company_name", bo.getCompanyName());//公司名称
        lqw.like(StringUtils.isNotBlank(bo.getCustomerNum()), "com.customer_num", bo.getCustomerNum());//纳税人识别号
        lqw.eq(StringUtils.isNotBlank(bo.getCustomerCert()), "com.customer_cert", bo.getCustomerCert());//纳税人资格
        lqw.like(StringUtils.isNotBlank(bo.getCustomManagerName()), "usr.nick_name", bo.getCustomManagerName());//销售经理姓名
        lqw.like(StringUtils.isNotBlank(bo.getCompanyAdress()), "com.company_adress", bo.getCompanyAdress());//公司地址
        lqw.like(StringUtils.isNotBlank(bo.getMobile()), "com.legal_person_phone", bo.getMobile());//法人手机号
        lqw.like(StringUtils.isNotBlank(bo.getIdNo()), "com.legal_person_idcard", bo.getIdNo());//法人身份证
        lqw.like(StringUtils.isNotBlank(bo.getName()), "com.legal_person_name", bo.getName());//法人姓名
        lqw.like(StringUtils.isNotBlank(bo.getCustomName()), "cus.custom_name", bo.getCustomName());//客户姓名
        lqw.like(StringUtils.isNotBlank(bo.getCustomMobile()), "cus.custom_mobile", bo.getCustomMobile());//客户电话
        lqw.eq(StringUtils.isNotBlank(bo.getCustomScene()), "con.custom_scene", bo.getCustomScene());//是否到达现场
        lqw.eq(StringUtils.isNotBlank(bo.getIsProxy()), "con.is_proxy", bo.getIsProxy());//是否代账


        //服务项目编码集合
        lqw.exists(CollectionUtils.isNotEmpty(bo.getServiceProjectCode()), "select 1 from ps_contract_business detail " +
                "where detail.contract_code = con.contract_code and detail.business_type in ("+StringUtils.join(bo.getServiceProjectCode(),",")+")");//服务项目编码集合
        //执行者姓名
        lqw.exists(StringUtils.isNotBlank(bo.getExecutor()), "select 1 from ps_task_appoint appoint,sys_user su " +
                "where appoint.appoint_status != '50' and appoint.executor = su.user_id and appoint.task_id = main.id and su.nick_name like '%" + bo.getExecutor() + "%'");
        lqw.orderByDesc("main.create_time");
        return lqw;
    }

    /**
     * 上传发票
     * @param id 任务主表id
     * @param file 发票文件
     */
    public void invoice(MultipartFile file, Long id){
        PsTaskMain info = baseMapper.selectById(id);
        if(!StringUtils.equals(TaskTypeEnum.INVOICE.getCode(),info.getTaskType())){
            throw new ServiceException("发票任务才可以上传发票");
        }
        SysOssVo vo = ossService.upload(file);
        info.setInvoice(vo.getOssId()+"");
        info.setTaskStatus(TaskStatusEnum.FINISH.getCode());
        baseMapper.updateById(info);
    }
    /**
     * 任务暂停
     * @param id 任务主表id
     */
    public void pause( Long id){
        PsTaskMain info = baseMapper.selectById(id);
        if(!StringUtils.equals(info.getTaskStatus(),TaskStatusEnum.ING.getCode())){
            throw new ServiceException("只有进行中的任务可以暂停");
        }
        PsTaskMain main = new PsTaskMain();
        main.setId(id);
        main.setTaskStatus(TaskStatusEnum.PAUSE.getCode());
        baseMapper.updateById(main);
        //只有进行中可以暂停
        appointMapper.update(Wrappers.<PsTaskAppoint>lambdaUpdate()
                .set(PsTaskAppoint::getAppointStatus,AppointStatusEnum.PAUSE.getCode())
                .eq(PsTaskAppoint::getTaskId,id).eq(PsTaskAppoint::getAppointStatus,AppointStatusEnum.ING.getCode()));

    }
    /**
     * 任务恢复
     * @param id 任务主表id
     */
    public void recover( Long id){
        PsTaskMain info = baseMapper.selectById(id);
        if(!StringUtils.equals(info.getTaskStatus(),TaskStatusEnum.PAUSE.getCode())){
            throw new ServiceException("只有暂停中的任务可以恢复");
        }
        PsTaskMain main = new PsTaskMain();
        main.setId(id);
        main.setTaskStatus(TaskStatusEnum.ING.getCode());
        baseMapper.updateById(main);
        //只有暂停可以恢复
        appointMapper.update(Wrappers.<PsTaskAppoint>lambdaUpdate()
                .set(PsTaskAppoint::getAppointStatus,AppointStatusEnum.ING.getCode())
                .eq(PsTaskAppoint::getTaskId,id).eq(PsTaskAppoint::getAppointStatus,AppointStatusEnum.PAUSE.getCode()));

    }
//    /**
//     * 查询主任务
//     *
//     * @param id 主键
//     * @return 主任务
//     */
//    @Override
//    public PsTaskMainVo queryById(Long id){
//        return baseMapper.selectVoById(id);
//    }
//
//    /**
//     * 分页查询主任务列表
//     *
//     * @param bo        查询条件
//     * @param pageQuery 分页参数
//     * @return 主任务分页列表
//     */
//    @Override
//    public TableDataInfo<PsTaskMainVo> queryPageList(PsTaskMainBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<PsTaskMain> lqw = buildQueryWrapper(bo);
//        Page<PsTaskMainVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
//    }
//
//    /**
//     * 查询符合条件的主任务列表
//     *
//     * @param bo 查询条件
//     * @return 主任务列表
//     */
//    @Override
//    public List<PsTaskMainVo> queryList(PsTaskMainBo bo) {
//        LambdaQueryWrapper<PsTaskMain> lqw = buildQueryWrapper(bo);
//        return baseMapper.selectVoList(lqw);
//    }
//
//    private LambdaQueryWrapper<PsTaskMain> buildQueryWrapper(PsTaskMainBo bo) {
//        Map<String, Object> params = bo.getParams();
//        LambdaQueryWrapper<PsTaskMain> lqw = Wrappers.lambdaQuery();
//        lqw.eq(StringUtils.isNotBlank(bo.getContractCode()), PsTaskMain::getContractCode, bo.getContractCode());
//        lqw.eq(StringUtils.isNotBlank(bo.getTaskType()), PsTaskMain::getTaskType, bo.getTaskType());
//        lqw.eq(bo.getStartDate() != null, PsTaskMain::getStartDate, bo.getStartDate());
//        lqw.eq(StringUtils.isNotBlank(bo.getTaskStatus()), PsTaskMain::getTaskStatus, bo.getTaskStatus());
//        return lqw;
//    }
//
//
//
//    /**
//     * 修改主任务
//     *
//     * @param bo 主任务
//     * @return 是否修改成功
//     */
//    @Override
//    public Boolean updateByBo(PsTaskMainBo bo) {
//        PsTaskMain update = MapstructUtils.convert(bo, PsTaskMain.class);
//        validEntityBeforeSave(update);
//        return baseMapper.updateById(update) > 0;
//    }
//
//    /**
//     * 保存前的数据校验
//     */
//    private void validEntityBeforeSave(PsTaskMain entity){
//        //TODO 做一些数据校验,如唯一约束
//    }
//
//    /**
//     * 校验并批量删除主任务信息
//     *
//     * @param ids     待删除的主键集合
//     * @param isValid 是否进行有效性校验
//     * @return 是否删除成功
//     */
//    @Override
//    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if(isValid){
//            //TODO 做一些业务上的校验,判断是否需要校验
//        }
//        return baseMapper.deleteBatchIds(ids) > 0;
//    }
}
