package com.chinaweal.aiccs.aiccs.seriousillegal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.business.entity.XrTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.vo.XrTaskListVo;
import com.chinaweal.aiccs.aiccs.business.rules.init.FlowUtil;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.RpeiExeInfo;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.RpeiExeInfoTask;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.RpeiExeInfoTaskSaveDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.mapper.RpeiExeInfoTaskMapper;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IRpeiExeInfoService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IRpeiExeInfoTaskService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.common.emnu.AuthEnum;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalSpeQueryDto;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.FlowConstant;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.pojo.AICPermission;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 重整计划或者和解协议执行流程表 服务实现类
 *
 * @author zhouxy
 * @since 2025-12-22
 */
@Service
public class RpeiExeInfoTaskServiceImpl extends ServiceImpl<RpeiExeInfoTaskMapper, RpeiExeInfoTask> implements IRpeiExeInfoTaskService {

    @Resource
    private EBaseinfoService baseinfoService;
    @Resource
    private IXrTaskListService iXrTaskListService;
    @Resource
    private IRpeiExeInfoService rpeiExeInfoService;
    @Resource
    private TSSerIllegalListService tsSerIllegalListService;


    @Override
    public IPage<RpeiExeInfoTask> listRpeiExeInfoTask(BaseQuery<SeriousIllegalSpeQueryDto> query, AICUser user) {
        Map<String, AICPermission> aicPermissions = user.getAicPermissions();
        // 权限
        List<String> authList = new ArrayList<>();
        authList.add(user.getPrimaryKey());
        if (aicPermissions.containsKey(AuthEnum.XR_HANDLE.getTsPermissionCode())) {
            authList.add(user.getRegionID() + ":" + AuthEnum.XR_HANDLE.getCode());
        }
        SeriousIllegalSpeQueryDto entity = query.getEntity(SeriousIllegalSpeQueryDto.class);
        entity.setAuthList(authList);
        IPage<RpeiExeInfoTask> rpeiExeInfoTaskIPage;
        Page<RpeiExeInfoTask> page = new Page<>(query.getCurrent(), query.getSize());
        if (StringUtils.equals(entity.getBusType(), "todo")) {  //待办
            entity.setBusStatus("0");
            rpeiExeInfoTaskIPage = baseMapper.selectRpeiExeInfoTaskTodo(page, entity);
        } else if (StringUtils.equals(entity.getBusType(), "history")) {    //记录
            LambdaQueryWrapper<RpeiExeInfoTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RpeiExeInfoTask::getRegAuth, user.getRegionID().substring(0, 6));

            if (StringUtils.isNotEmpty(entity.getSearchUscc())) {
                queryWrapper.eq(RpeiExeInfoTask::getUniscId, entity.getSearchUscc())
                        .or().eq(RpeiExeInfoTask::getRegNo, entity.getSearchUscc());
            }
            if (StringUtils.isNotEmpty(entity.getEntName())) {
                queryWrapper.like(RpeiExeInfoTask::getEntName, entity.getEntName());
            }
            rpeiExeInfoTaskIPage = page(page, queryWrapper);
        } else {
            throw new BusinessException("查询列表类型错误，请联系管理员处理");
        }
        return rpeiExeInfoTaskIPage;
    }

    @Override
    public XrTaskListVo saveIvdAcceptList(RpeiExeInfo rpeiExeInfo, String operType, AICUser user) {
        EBaseinfo eBaseinfo = baseinfoService.getById(rpeiExeInfo.getPripid());
        if (eBaseinfo == null) {
            throw new BusinessException("主体信息不存在");
        }
        String bizSeqNo = UUID.randomUUID().toString();
        String entName = eBaseinfo.getEntname();

        RpeiExeInfoTask rpeiExeInfoTask = new RpeiExeInfoTask();
        rpeiExeInfoTask.setTaskId(bizSeqNo)
                .setExeId(rpeiExeInfo.getExeId())   //关联的执行信息id
                .setBizSeqNo(bizSeqNo)
                .setEntName(entName)
                .setPripId(eBaseinfo.getPripid())
                .setUniscId(eBaseinfo.getUniscid())
                .setRegNo(eBaseinfo.getRegno())
                .setOperType(operType)
                .setStatus("0")
                .setExeStateBef(rpeiExeInfo.getExeState())
                .setRegAuth(eBaseinfo.getRegorg())
                .setRegAuthCn(eBaseinfo.getRegorgCn())
                .setApplyTime(new Date());
        // 保存业务信息
        this.save(rpeiExeInfoTask);

        // 开启待办
        XrTaskList xrTaskList = new XrTaskList();
        String taskLikeId = UUID.randomUUID().toString();
        xrTaskList.setTaskLikeId(taskLikeId);
        xrTaskList.setBizSeqNo(bizSeqNo);
        xrTaskList.setBusType(BaseDataConstant.BUSINESS_TYPE_RPEI_EXE_INFO);
        xrTaskList.setAreaCode(user.getRegionID().substring(0, 6));
        xrTaskList.setBusName(entName);
        xrTaskList.setApplyOrgId(user.getOrgID());
        xrTaskList.setWorkFlowId(FlowUtil.FORCE_DEREGISTER_WORK_FLOW);
        // 将单个 pripId 转换为 List
        List<String> pripIdList = Collections.singletonList(rpeiExeInfoTask.getPripId());
        // 保存待办信息
        iXrTaskListService.startWorkFlow(xrTaskList, new String[]{user.getPrimaryKey()}, null, pripIdList);
        return new XrTaskListVo(taskLikeId, bizSeqNo, "");
    }

    @Override
    @Transactional
    public void processControl(RpeiExeInfoTaskSaveDto rpeiExeInfoTaskSaveDto, AICUser user) {
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>()
                .eq(XrTaskList::getBizSeqNo, rpeiExeInfoTaskSaveDto.getBizSeqNo()));
        LambdaQueryWrapper<RpeiExeInfoTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RpeiExeInfoTask::getBizSeqNo, rpeiExeInfoTaskSaveDto.getBizSeqNo());
        RpeiExeInfoTask rpeiExeInfoTask = getOne(queryWrapper);
        if (rpeiExeInfoTask == null) {
            throw new BusinessException("暂无数据");
        }

        RpeiExeInfoTask task = rpeiExeInfoTaskSaveDto.getRpeiExeInfoTask();
        //因为前端的主键taskId有重复的值，所以这里的taskId是空的，需要取前面的
        task.setTaskId(rpeiExeInfoTask.getTaskId());
        switch (rpeiExeInfoTaskSaveDto.getNextNodeID()) {
            case FlowConstant.LINK_TYPE_EXAMINE:
                // 保存值
                rpeiExeInfoTask = task;
                //若是修改执行状态，则查出执行信息
                if (StringUtils.isNotEmpty(rpeiExeInfoTask.getExeId())) {
                    RpeiExeInfo rpeiExeInfo = rpeiExeInfoService.getById(rpeiExeInfoTask.getExeId());
                    rpeiExeInfoTask.setExeStateBef(rpeiExeInfo.getExeState());
                }
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_ONE); // 审批流程中把状态设置成 "审核中"
                break;
            case FlowConstant.LINK_TYPE_APPROVE:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_TWO); // 审批流程中把状态设置成 "审批"
                break;
            case FlowConstant.LINK_TYPE_END:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_THREE); // 审批流程中把状态设置成 "通过"
                rpeiExeInfoTask = toEndRpeiExeInfoTask(rpeiExeInfoTask);
                break;
            case FlowConstant.LINK_TYPE_NULLIFY:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_FIVE); // 审批流程中把状态设置成 "不通过"
                break;
            case FlowConstant.LINK_TYPE_EXAMINE_FINISH:
            case FlowConstant.LINK_TYPE_APPROVE_FINISH:
            case FlowConstant.LINK_TYPE_LAW_FINISH:
            case FlowConstant.LINK_TYPE_UP_EXAMINE_FINISH:
            case FlowConstant.LINK_TYPE_UP_APPROVE_FINISH:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_FOUR); // 审批流程中把状态设置成 "作废"
                break;
            case FlowConstant.LINK_TYPE_EXAMINE_RETURN:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_ONE);
                break;
            case FlowConstant.LINK_TYPE_HANDLE_RETURN:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_ZERO);
                break;
            case FlowConstant.LINK_TYPE_LAW_RETURN:
                rpeiExeInfoTask.setStatus(FlowConstant.LINK_STATUS_SEVEN);
                break;
            default:
                break;
        }
        saveOrUpdate(rpeiExeInfoTask);
        iXrTaskListService.updateWorkFlow(rpeiExeInfoTaskSaveDto.getOpinion(), xrTaskList,
                rpeiExeInfoTaskSaveDto.getNextNodeID(), rpeiExeInfoTaskSaveDto.getNextPerformerIds(), null);
    }

    /**
     * 办结重整计划或者和解协议执行信息业务
     *
     * @param rpeiExeInfoTask
     */
    private RpeiExeInfoTask toEndRpeiExeInfoTask(RpeiExeInfoTask rpeiExeInfoTask) {
        //生成重整计划或者和解协议执行信息
        RpeiExeInfo rpeiExeInfo = new RpeiExeInfo();
        BeanUtils.copyProperties(rpeiExeInfoTask, rpeiExeInfo);
        if (StringUtils.isEmpty(rpeiExeInfo.getExeId())) {    //若执行ID空了，则直接取流程表的id
            rpeiExeInfo.setExeId(rpeiExeInfoTask.getTaskId());
        }
        rpeiExeInfo.setExeState(rpeiExeInfoTask.getExeStateAft());
        rpeiExeInfoService.saveOrUpdate(rpeiExeInfo);

        //严重违法查询条件，若要改成3，则查0；若要改成0.则查3
        String status = rpeiExeInfoTask.getHandleType().equals("0") ? "3" : "0";
        //修改严重违法失信数据
        tsSerIllegalListService.update(new LambdaUpdateWrapper<TSSerIllegalList>()
                .set(TSSerIllegalList::getOperationStatus, rpeiExeInfoTask.getHandleType())  //修改严重违法状态
                .set(TSSerIllegalList::getLauptime, LocalDateTime.now())    //更新时间戳
                .eq(TSSerIllegalList::getPripid, rpeiExeInfoTask.getPripId())
                .eq(TSSerIllegalList::getOperationStatus, status)
                .isNull(TSSerIllegalList::getRemdate));
        return rpeiExeInfoTask;
    }

}
