package com.pusong.business.service.approver.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pusong.business.domain.PsApproverRecord;
import com.pusong.business.domain.PsContractInfo;
import com.pusong.business.domain.PsTaskAppoint;
import com.pusong.business.domain.PsTaskMain;
import com.pusong.business.enums.ApproverStatusEnum;
import com.pusong.business.enums.ApproverTypeEnum;
import com.pusong.business.enums.ContractStatusEnum;
import com.pusong.business.enums.TaskStatusEnum;
import com.pusong.business.mapper.PsApproverRecordMapper;
import com.pusong.business.mapper.PsTaskAppointMapper;
import com.pusong.business.mapper.PsTaskMainMapper;
import com.pusong.business.service.IPsContractInfoService;
import com.pusong.business.service.IPsTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 任务作废审批
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class TaskCancellaApproverServiceImpl extends ApproverAbstractServiceImpl {
    @Override
    public String approverType() {
        return ApproverTypeEnum.TASKCANCE.getCode();
    }
    private final PsTaskMainMapper taskMainMapper;
    private final PsTaskAppointMapper taskAppointMapper;
    private final PsApproverRecordMapper baseMapper;

    /**
     * 1 审批成功 任务作废成功，合同状态显示为【已作废】
     * @param psApproverRecord 神瀑类
     */
    @Override
    public void success(PsApproverRecord psApproverRecord) {
        //主任务作废
        PsTaskMain info = taskMainMapper.selectById(psApproverRecord.getBusinessId());
        info.setTaskStatus(TaskStatusEnum.CANCEL.getCode());
        info.setComment(psApproverRecord.getApplyDesc());
        taskMainMapper.updateById(info);
        List<PsTaskAppoint> list = taskAppointMapper.selectList(Wrappers.<PsTaskAppoint>lambdaQuery().eq(PsTaskAppoint::getTaskId, info.getId()));

        //子任务作废
        taskAppointMapper.update(Wrappers.<PsTaskAppoint>lambdaUpdate()
                .set(PsTaskAppoint::getAppointStatus, TaskStatusEnum.AppointStatusEnum.CANCEL.getCode())
                .eq(PsTaskAppoint::getTaskId, info.getId()));
        if(CollectionUtils.isNotEmpty(list)){
            List<String> ids = list.stream().map(PsTaskAppoint::getId).map(Object::toString).toList();
//        ids.add(info.getId());
            baseMapper.update(Wrappers.<PsApproverRecord>lambdaUpdate().set(PsApproverRecord::getDelFlag, "2").in(PsApproverRecord::getBusinessId, ids));
        }

    }

    /**
     * 审批拒绝 合同的状态变回原状态，并在原状态下方展示【拒绝原因】
     * @param psApproverRecord
     */
    @Override
    public void fail(PsApproverRecord psApproverRecord) {
        //还原状态
        PsTaskMain info = taskMainMapper.selectById(psApproverRecord.getBusinessId());
        info.setTaskStatus(psApproverRecord.getUpdateData());
        taskMainMapper.updateById(info);
    }
}
