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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.business.entity.XrOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.XrTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.dto.ApprovalFormDto;
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.IXrOpinionService;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskListService;
import com.chinaweal.aiccs.aiccs.force.entity.XrForceDeregisterRes;
import com.chinaweal.aiccs.aiccs.force.entity.XrLiccanRec;
import com.chinaweal.aiccs.aiccs.force.entity.XrLiccanRecTask;
import com.chinaweal.aiccs.aiccs.force.entity.querydto.ForceDeregisterSpeQueryDto;
import com.chinaweal.aiccs.aiccs.force.entity.querydto.ForceDeregisterSpeSaveDto;
import com.chinaweal.aiccs.aiccs.force.mapper.XrLiccanRecTaskMapper;
import com.chinaweal.aiccs.aiccs.force.service.IXrLiccanRecService;
import com.chinaweal.aiccs.aiccs.force.service.IXrLiccanRecTaskService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.common.emnu.AuthEnum;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.FlowConstant;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.service.AicorgService;
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 javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 营业执照作废声明流程表 服务实现类
 *
 * @author zhouxy
 * @since 2025/10/9
 */
@Service
public class XrLiccanRecTaskServiceImpl extends ServiceImpl<XrLiccanRecTaskMapper, XrLiccanRecTask> implements IXrLiccanRecTaskService {

    @Resource
    private AicorgService aicorgService;
    @Resource
    private IXrTaskListService iXrTaskListService;
    @Resource
    private TswrittemplateService tswrittemplateService;
    @Resource
    private IXrLiccanRecService iXrLiccanRecService;
    @Resource
    private IXrOpinionService opinionService;


    @Override
    public IPage<XrLiccanRecTask> listXrLiccanRecTask(BaseQuery<ForceDeregisterSpeQueryDto> 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());
        }
        ForceDeregisterSpeQueryDto entity = query.getEntity(ForceDeregisterSpeQueryDto.class);
        entity.setAuthList(authList);
        IPage<XrLiccanRecTask> xrLiccanRecTaskIPage;
        Page<XrLiccanRecTask> page = new Page<>(query.getCurrent(), query.getSize());
        if (Objects.equals(entity.getBusType(), "todo")) {  //待办
            entity.setBusStatus("0");
            xrLiccanRecTaskIPage = baseMapper.selectXrLiccanRecTaskTodo(page, entity);
        } else if (Objects.equals(entity.getBusType(), "history")) {    //记录
            String regOrg = aicorgService.getOrgnumberByUserLevel(user,false);
            entity.setRegOrg(regOrg);
            xrLiccanRecTaskIPage = baseMapper.selectXrLiccanRecTaskHistory(page, entity);
        } else {
            throw new BusinessException("查询列表类型错误，请联系管理员处理");
        }
        return xrLiccanRecTaskIPage;
    }

    @Override
//    @DSTransactional
    public XrTaskListVo saveIvdAcceptList(ForceDeregisterSpeQueryDto queryDto, AICUser user) {
        String bizSeqNo = UUID.randomUUID().toString();
        XrForceDeregisterRes forceRes = queryDto.getXrForceDeregisterRes();
        if (forceRes == null) {
            throw new BusinessException("拟强制注销数据不能为空");
        }

        String entName = forceRes.getEntName();
        //生成营业执照作废声明业务数据
        XrLiccanRecTask xrLiccanRecTask = new XrLiccanRecTask();
        BeanUtils.copyProperties(forceRes, xrLiccanRecTask);
        String taskId = UUID.randomUUID().toString();
        xrLiccanRecTask.setTaskId(taskId)
                .setRecId(taskId)
                .setBizSeqNo(bizSeqNo)
                .setStatus("0")
                .setApplyTime(LocalDateTime.now());
        // 保存业务信息
        this.save(xrLiccanRecTask);

        // 开启待办
        XrTaskList xrTaskList = new XrTaskList();
        String taskLikeId = UUID.randomUUID().toString();
        xrTaskList.setTaskLikeId(taskLikeId);
        xrTaskList.setBizSeqNo(bizSeqNo);
        xrTaskList.setBusType(BaseDataConstant.BUSINESS_TYPE_FORCE_DEREGISTER);
        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(xrLiccanRecTask.getPripId());
        // 保存待办信息
        iXrTaskListService.startWorkFlow(xrTaskList,new String[]{user.getPrimaryKey()}, null,pripIdList, user);
        return new XrTaskListVo(taskLikeId, bizSeqNo, "");
    }

    @Override
    public String generateLiccanSta(AICUser user, XrLiccanRecTask xrLiccanRecTask) {
        //查找对应的模板
        Tswrittemplate templateDB = tswrittemplateService.getOne(new LambdaQueryWrapper<Tswrittemplate>()
                .eq(Tswrittemplate::getWritsType, WorkNoUtil.WORKNOTYPE_74)
                .eq(Tswrittemplate::getIsTemplate, "1"));
        String entName = xrLiccanRecTask.getEntName();
//        if(speList.size() > 1){
//            //取公司共计数量
//            entName = entName + "等" + speList.size() + "户公司（另附附件）";
//        }

        String content = templateDB.getContent();
        return content
                .replace("{{entName}}", entName)
                .replace("公告期内有异议的", "\n        公告期内有异议的")
                .replace("{{regOrg}}", user.getOrgName())
                .replace("联系人：", "\n        联系人：");
    }

    @Override
//    @DSTransactional
    public void processControl(ForceDeregisterSpeSaveDto forceSaveDto, AICUser user) {
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>().eq(XrTaskList::getBizSeqNo, forceSaveDto.getBizSeqNo()));
        LambdaQueryWrapper<XrLiccanRecTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrLiccanRecTask::getBizSeqNo, forceSaveDto.getBizSeqNo());
        List<XrLiccanRecTask> xrLiccanRecTaskList = list(queryWrapper);
        if (xrLiccanRecTaskList.isEmpty()) {
            throw new BusinessException("暂无数据");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
//        // 转发业务
//        if (StringUtils.equals(FlowConstant.LINK_TYPE_REASSIGNMENT,forceQueryDto.getNextNodeID())) {
//            //查出转办单位的单位编号
//            TOrgunits nextOrg = aicorgService.getTOrgunitsById(forceQueryDto.getNextOrgID());
//            xrTaskList.setNextOrgId(nextOrg.getOrgNumber());
//            iXrTaskForwardService.saveByBizSeqNo(forceQueryDto, user,true);
//            iXrTaskListService.updateWorkFlow(forceQueryDto.getOpinion(), xrTaskList,
//                    forceQueryDto.getNextNodeID(), forceQueryDto.getNextPerformerIds(), AuthEnum.XR_HANDLE.getCode());
//            return;
//        }

        for (XrLiccanRecTask xrLiccanRecTask : xrLiccanRecTaskList) {
            XrLiccanRecTask task = forceSaveDto.getXrLiccanRecTask();
            //因为前端的主键taskId有重复的值，所以这里的taskId是空的，需要取前面的
            task.setTaskId(xrLiccanRecTask.getTaskId());
            switch (forceSaveDto.getNextNodeID()) {
                case FlowConstant.LINK_TYPE_EXAMINE:
                    // 保存值
                    xrLiccanRecTask = task;
                    xrLiccanRecTask.setRegType("51")  //强制注销
                            .setStatus(FlowConstant.LINK_STATUS_ONE); // 审批流程中把状态设置成 "审核中"
                    break;
                case FlowConstant.LINK_TYPE_APPROVE:
                    xrLiccanRecTask.setStatus(FlowConstant.LINK_STATUS_TWO); // 审批流程中把状态设置成 "审批"
                    break;
                case FlowConstant.LINK_TYPE_END:
                    xrLiccanRecTask.setStatus(FlowConstant.LINK_STATUS_THREE); // 审批流程中把状态设置成 "通过"
                    xrLiccanRecTask = toEndXrLiccanRecTask(xrLiccanRecTask);
                    break;
                case FlowConstant.LINK_TYPE_NULLIFY:
                    xrLiccanRecTask.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:
                    xrLiccanRecTask.setStatus(FlowConstant.LINK_STATUS_FOUR); // 审批流程中把状态设置成 "作废"
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_RETURN:
                    xrLiccanRecTask.setStatus(FlowConstant.LINK_STATUS_ONE);
                    break;
                case FlowConstant.LINK_TYPE_HANDLE_RETURN:
                    xrLiccanRecTask.setStatus(FlowConstant.LINK_STATUS_ZERO);
                    break;
                case FlowConstant.LINK_TYPE_LAW_RETURN:
                    xrLiccanRecTask.setStatus(FlowConstant.LINK_STATUS_SEVEN);
                    break;
                default:
                    break;
            }
            saveOrUpdate(xrLiccanRecTask);
        }
        iXrTaskListService.updateWorkFlow(forceSaveDto.getOpinion(), xrTaskList,
                forceSaveDto.getNextNodeID(), forceSaveDto.getNextPerformerIds(), null);
    }

    /**
     * 办结营业执照作废声明业务
     *
     * @param xrLiccanRecTask
     */
    private XrLiccanRecTask toEndXrLiccanRecTask(XrLiccanRecTask xrLiccanRecTask) {
        //补全业务表的字段
        xrLiccanRecTask.setLiccanDate(LocalDate.now());
        //生成登记机关营业执照作废声明信息
        XrLiccanRec xrLiccanRec = new XrLiccanRec();
        BeanUtils.copyProperties(xrLiccanRecTask, xrLiccanRec);

        iXrLiccanRecService.saveOrUpdate(xrLiccanRec);
        return xrLiccanRecTask;
    }

    @Override
    public ApprovalFormDto getApprovalFormByBizSeqNo(String bizSeqNo, String recId) {
        ApprovalFormDto approvalFormDto = new ApprovalFormDto();
        XrLiccanRec xrLiccanRec = iXrLiccanRecService.getById(recId);

        LambdaQueryWrapper<XrTaskList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrTaskList::getBizSeqNo, bizSeqNo);
        XrTaskList one = iXrTaskListService.getOne(queryWrapper);
        List<XrOpinion> data = opinionService.list(new LambdaQueryWrapper<XrOpinion>()
                .eq(XrOpinion::getTaskListId,one.getTaskLikeId()).orderByDesc(XrOpinion::getUpdateTime));
        BeanUtils.copyProperties(xrLiccanRec, approvalFormDto);
        approvalFormDto.setAreaName(xrLiccanRec.getRegOrgCn());
        approvalFormDto.setUniscId(xrLiccanRec.getUniscId());
        approvalFormDto.setOpinion(data);
        //事实和理由
        approvalFormDto.setLostCreditExplain(convertLiccanReason(xrLiccanRec.getLiccanReason()));

        //公告内容
        HashMap<String, Object> map = new HashMap<>();
        map.put("content", xrLiccanRec.getLiccanSta());
        map.put("areaName", xrLiccanRec.getRegOrgCn());
//        map.put("writsName", force.getNoticeTitle());
        map.put("writTime", xrLiccanRec.getLiccanDate());
        approvalFormDto.setRepairMap(map);
        return approvalFormDto;
    }

    private String convertLiccanReason(String liccanReason) {
        switch (liccanReason) {
            case "1":
                return "无法缴回";
            case "2":
                return "拒不缴回";
            case "3":
                return "未缴回";
            default:
                return "未知原因";
        }
    }

}
