package com.chinaweal.aiccs.aiccs.seriousillegalPerson.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
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.model.NodeModel;
import com.chinaweal.aiccs.aiccs.business.rules.model.SequenceFlowModel;
import com.chinaweal.aiccs.aiccs.business.service.IXrActivityService;
import com.chinaweal.aiccs.aiccs.business.service.IXrOpinionService;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.PrintTSWritDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.vo.PrintTSWritVo;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.XrSeriousIllegalPersonSpeList;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.PersonSpeSaveIvdDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalProcessDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalSpeQueryDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.vo.TaskCurrentInfoVo;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.service.IXrSeriousillegalPersonSpeListService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
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 com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 列入严重违法失信自然人名单 控制器
 *
 * @author zhouxy
 * @since 2025-07-24
 */
@Api(tags = "列入严重违法失信自然人名单")
@RestController
@RequestMapping("/xrSeriousIllegalPersonSpeList")
@Slf4j
public class XrSeriousIllegalPersonSpeListController extends BaseController {

    @Resource
    private IXrSeriousillegalPersonSpeListService iXrSeriousillegalPersonSpeListService;
    @Resource
    private IXrActivityService iXrActivityService;
    @Resource
    private IXrTaskListService iXrTaskListService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private IXrOpinionService iXrOpinionService;


    @ApiOperation(value = "1.分页查询列入严重违法失信自然人名单", position = 1)
    @PostMapping("/list")
    public RestResult<IPage<XrSeriousIllegalPersonSpeList>> listXrSeriousIllegalPersonSpeList(@RequestBody BaseQuery<SeriousIllegalSpeQueryDto> query, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_LOGGED_IN);
        }
        IPage<XrSeriousIllegalPersonSpeList> data = iXrSeriousillegalPersonSpeListService.listXrSeriousIllegalPersonSpeList(query, user);
        return RestResult.ok(data);
    }

    @ApiOperation(value = "2.启动自然人列严待办", position = 2)
    @PostMapping("/saveIvdAcceptList")
    public RestResult<XrTaskListVo> saveIvdAcceptList(@RequestBody PersonSpeSaveIvdDto speSaveIvdDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        String cerNo = speSaveIvdDto.getCerNo();
        if (StringUtils.isEmpty(speSaveIvdDto.getInv()) ||
                StringUtils.isEmpty(speSaveIvdDto.getCerType()) ||
                StringUtils.isEmpty(cerNo)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }

        //若证件类型是身份证则校验
        if (StringUtils.equals("10", speSaveIvdDto.getCerType())) {
            boolean isMatch = false;
            if (cerNo.length() == 18) { // 18位身份证号码验证
                isMatch = cerNo.matches("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
            } else if (cerNo.length() == 15) {    // 15位身份证号码验证
                isMatch = cerNo.matches("^[1-9]\\d{5}\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}$");
            }
            if (!isMatch)
                return RestResult.error(ResultCode.PARAM_IS_INVALID, "身份证号码格式不正确");
        }

        XrTaskListVo xrTaskListVo = iXrSeriousillegalPersonSpeListService.saveIvdAcceptList(speSaveIvdDto, user);
        return RestResult.ok(xrTaskListVo);
    }

    @ApiOperation(value = "3.业务号查询列入严重违法失信自然人表", position = 3)
    @GetMapping("/listByBizSeqNo")
    public RestResult<XrSeriousIllegalPersonSpeList> listByBizSeqNo(@RequestParam @ApiParam("id") String bizSeqNo) {
        LambdaQueryWrapper<XrSeriousIllegalPersonSpeList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrSeriousIllegalPersonSpeList::getBizSeqNo, bizSeqNo);
        List<XrSeriousIllegalPersonSpeList> xrSeriousIllegalPersonSpeLists = iXrSeriousillegalPersonSpeListService.list(queryWrapper);
        //目前暂时只取第一条业务数据
        XrSeriousIllegalPersonSpeList personSpeList = xrSeriousIllegalPersonSpeLists.get(0);
        return RestResult.ok(personSpeList);
    }

    @ApiOperation(value = "4.流程控制", position = 4)
    @PostMapping("/processControl")
    public RestResult<?> processControl(@RequestBody @Validated SeriousIllegalProcessDto seriousIllegalProcessDto, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (StringUtils.isEmpty(seriousIllegalProcessDto.getNextNodeID()) || StringUtils.isEmpty(seriousIllegalProcessDto.getBizSeqNo())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        Map<String, AICPermission> aicPermissions = user.getAicPermissions();
        //根据当前流程节点判断权限
        if (!iXrActivityService.checkPermissionsAndNodeID(aicPermissions, seriousIllegalProcessDto.getCurrentNodeID(), seriousIllegalProcessDto.getNextNodeID(), "seriousillegal")) {
            return RestResult.error(ResultCode.INTERFACE_FORBID_VISIT, "无权操作");
        }
        iXrSeriousillegalPersonSpeListService.processControl(seriousIllegalProcessDto, user);
        return RestResult.ok();
    }

    @ApiOperation(value = "5.业务号获取审批表", position = 5)
    @GetMapping("/getApprovalFormByBizSeqNo")
    public RestResult<ApprovalFormDto> getApprovalFormByBizSeqNo(@RequestParam @ApiParam("id") String bizSeqNo, String cerNo, String illegalListId) {
        ApprovalFormDto approvalDto = iXrSeriousillegalPersonSpeListService.getApprovalFormByBizSeqNo(bizSeqNo, cerNo, illegalListId);
        return RestResult.ok(approvalDto);
    }

    @ApiOperation(value = "6.下一步可执行流程清单", position = 6)
    @GetMapping("/getNextStepList")
    public RestResult<List<SequenceFlowModel>> getNextStepList(@RequestParam @ApiParam("业务号") String bizSeqNo) {
        // 根据业务号查询待办记录
        XrTaskList xrTaskList = iXrTaskListService.getOne(
                new LambdaQueryWrapper<XrTaskList>().eq(XrTaskList::getBizSeqNo, bizSeqNo)
        );
        if (xrTaskList == null) {
            throw new BusinessException("未找到该业务的待办记录");
        }
        // 查询下一步可执行的流程清单
        List<SequenceFlowModel> nextStepList = iXrActivityService.findNextSequenceFlowList(xrTaskList.getTaskLikeId());
        return RestResult.ok(nextStepList);
    }

    @ApiOperation(value = "7.查询当前待办信息", position = 7)
    @GetMapping("/getCurrentTaskInfo")
    public RestResult<TaskCurrentInfoVo> getCurrentTaskInfo(@RequestParam @ApiParam("业务号") String bizSeqNo) {
        // 根据业务号查询待办记录
        XrTaskList xrTaskList = iXrTaskListService.getOne(
                new LambdaQueryWrapper<XrTaskList>().eq(XrTaskList::getBizSeqNo, bizSeqNo)
        );
        if (xrTaskList == null) {
            throw new BusinessException("未找到该业务的待办记录");
        }
        // 获取当前节点信息
        NodeModel currentNode = iXrActivityService.findCurrentNode(xrTaskList.getTaskLikeId());
        
        // 封装返回结果
        TaskCurrentInfoVo result = new TaskCurrentInfoVo();
        result.setTaskList(xrTaskList);
        result.setCurrentNode(currentNode);
        if (currentNode != null) {
            result.setCurrentNodeID(currentNode.getId());
        }
        return RestResult.ok(result);
    }

    /**
     * 打印文书页面
     */
    @ApiOperation("打印文书页面")
    @PostMapping("/printTSWrit")
    public RestResult<PrintTSWritVo> printTSWrit(@RequestBody PrintTSWritDto dto) {
        PrintTSWritVo result = new PrintTSWritVo();

        if ("1".equals(dto.getPrintstatus())) {
            // 打印决定书
            XrSeriousIllegalPersonSpeList detail = iXrSeriousillegalPersonSpeListService.getById(dto.getIllid());
            if (detail == null) {
                throw new BusinessException("记录不存在");
            }

            TSWrit writQueryModel = new TSWrit();
            if ("enter".equals(dto.getType())) {
                // 列入决定书
                writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_21);
                writQueryModel.setPripid(detail.getCerNo());
                writQueryModel.setBizseq(detail.getBizSeqNo());
            } else if ("remove".equals(dto.getType())) {
                // 移出决定书
                writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_25);
                writQueryModel.setPripid(detail.getCerNo());
                writQueryModel.setBizseq(detail.getBizSeqNo());
            }

            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                result.setWrirsno(tsWritQueryModels.get(0).getWritsno());
            }

            // 设置详细信息（需要将XrSeriousIllegalPersonSpeList转换为EOtIlldisdetailTemp类型）
            // 注意：这里可能需要创建专门的VO或调整返回结构
            result.setNowTime(LocalDate.now());
            if ("enter".equals(dto.getType())) {
                // 列入决定书需要加上届满日期
                if (detail.getAbnTime() != null) {
                    result.setExpirationDate(detail.getAbnTime().plusYears(3));
                }
            }

        } else if ("3".equals(dto.getPrintstatus())) {
            // 打印审批表
            XrTaskList taskListModel = iXrTaskListService.getOne(
                    new LambdaQueryWrapper<XrTaskList>().eq(XrTaskList::getWorkFlowId, dto.getWorkflowid())
            );
            if (taskListModel == null) {
                throw new BusinessException("待办记录不存在");
            }

            String inv = "";
            List<XrSeriousIllegalPersonSpeList> list = iXrSeriousillegalPersonSpeListService.list(
                    new LambdaQueryWrapper<XrSeriousIllegalPersonSpeList>()
                            .eq(XrSeriousIllegalPersonSpeList::getBizSeqNo, taskListModel.getBizSeqNo())
            );

            if (list != null && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    if (i > 2) {
                        inv = inv + "等";
                        break;
                    }
                    if (i > 0) {
                        inv = inv + ", ";
                    }
                    inv = inv + list.get(i).getInv();
                }
            }

            List<XrOpinion> opinionList = iXrOpinionService.list(
                    new LambdaQueryWrapper<XrOpinion>()
                            .eq(XrOpinion::getTaskListId, taskListModel.getTaskLikeId())
                            .orderByDesc(XrOpinion::getUpdateTime)
            );

            // 将XrOpinion转换为TSOpinion
            List<TSOpinion> tsOpinionList = new ArrayList<>();
            if (opinionList != null && !opinionList.isEmpty()) {
                for (XrOpinion xrOpinion : opinionList) {
                    TSOpinion tsOpinion = new TSOpinion();
                    tsOpinion.setOpinionid(xrOpinion.getOpinionId());
                    tsOpinion.setWorkflowid(taskListModel.getWorkFlowId());
                    tsOpinion.setOpiniontype(xrOpinion.getOpinionType());
                    tsOpinion.setHandler(xrOpinion.getHandler());
                    tsOpinion.setHandlerid(xrOpinion.getHandlerId());
                    tsOpinion.setOpinioncontent(xrOpinion.getOpinionContent());
                    if (xrOpinion.getHandelDate() != null) {
                        tsOpinion.setHandledate(xrOpinion.getHandelDate().atStartOfDay());
                    }
                    tsOpinion.setIsagree(xrOpinion.getAgree());
                    tsOpinion.setAreaCode(xrOpinion.getAreaCode());
                    tsOpinion.setLauptime(xrOpinion.getUpdateTime());
                    tsOpinionList.add(tsOpinion);
                }
            }

            result.setOpinionList(tsOpinionList);
            result.setRegno(inv);
            result.setEname(inv);
            if (list != null && !list.isEmpty()) {
                result.setDecorgString(list.get(0).getDecOrgCn());
                if ("enter".equals(dto.getType())) {
                    result.setLostCreditExplain(list.get(0).getSerillReaString());
                } else if ("remove".equals(dto.getType())) {
                    // 移出类型可能需要从其他字段获取
                }
            }
        }

        return RestResult.ok(result);
    }

    /**
     * 作废待办
     */
    @Transactional
    @ApiOperation("作废待办")
    @PostMapping("/nullify")
    public RestResult<XrTaskList> nullify(HttpServletRequest request,
                                          @ApiParam("bizSeqNo") @RequestParam String bizSeqNo,
                                          @ApiParam("作废原因") @RequestParam String reason) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 查询待办
        XrTaskList taskListModel = iXrTaskListService.lambdaQuery().eq(XrTaskList::getBizSeqNo, bizSeqNo).last("limit 1").one();
        if (taskListModel == null) {
            throw new BusinessException("待办记录不存在");
        }

        // 校验当前用户是否为待办创建人
        if (StringUtils.notEquals(user.getName(), taskListModel.getCreateBy())) {
            throw new BusinessException("非待办创建人无权作废待办");
        }

        // 保存作废意见
        XrOpinion opinion = new XrOpinion();
        opinion.setTaskListId(taskListModel.getTaskLikeId());
        opinion.setOpinionType(BaseDataConstant.OPINION_TYPE_ENTER);
        opinion.setHandler(user.getName());
        opinion.setHandlerId(user.getPrimaryKey());
        opinion.setHandelDate(LocalDate.now());
        opinion.setOpinionContent("作废原因：" + reason);
        iXrOpinionService.save(opinion);

        // 作废工作流
        iXrTaskListService.updateWorkFlow(opinion, taskListModel, FlowUtil.SERIOUS_ILLEGAL_NULLIFY,
                new String[]{user.getPrimaryKey()}, null);

        return RestResult.ok(taskListModel);
    }
}
