package com.chinaweal.aiccs.aiccs.punishment.controller;

import cn.hutool.core.util.IdUtil;
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.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.punishment.entity.QgCasePubNbaseinfo;
import com.chinaweal.aiccs.aiccs.punishment.entity.TBizRemPunishment;
import com.chinaweal.aiccs.aiccs.punishment.service.ICrECaseService;
import com.chinaweal.aiccs.aiccs.punishment.service.IQgCasePubNbaseinfoService;
import com.chinaweal.aiccs.aiccs.punishment.service.ITBizRemPunishmentService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 外省行政处罚修复控制器
 * </p>
 *
 * @author developer
 * @since 2026-03-30
 */
@Api(tags = "外省行政处罚修复控制器")
@ApiSort(1)
@RestController
@RequestMapping("/punishment/tBizRemPunishmentN")
@Slf4j
public class TBizRemPunishmentNController extends BaseController {

    @Resource
    private ITBizRemPunishmentService iTBizRemPunishmentService;
    @Resource
    private IQgCasePubNbaseinfoService qgCasePubNbaseinfoService;
    @Resource
    private ICrECaseService crECaseService;
    @Resource
    private TSTaskListService taskListService;
    @Resource
    private TSAttachmentService attachmentService;
    @Resource
    private TswrittemplateService tswrittemplateService;
    @Resource
    private FileStorageService fileStorageService;

    @ApiOperation(value = "1.新增外省行政处罚修复业务", position = 1)
    @PostMapping("/save")
    public RestResult<TBizRemPunishment> saveTBizRemPunishment(@RequestBody @Valid TBizRemPunishment tBizRemPunishment, BindingResult bindingResult) {
        AssertUtils.isBndingValidit(bindingResult);
        tBizRemPunishment = iTBizRemPunishmentService.saveTBizRemPunishment(tBizRemPunishment);
        return RestResult.ok(tBizRemPunishment);
    }

    @ApiOperation(value = "2.删除外省行政处罚修复业务", position = 2)
    @PostMapping("/delete")
    public RestResult<String> removeTBizRemPunishment(@RequestParam @ApiParam("id") Serializable id) {
        iTBizRemPunishmentService.removeById(id);
        return RestResult.ok();
    }

    @ApiOperation(value = "3.修改外省行政处罚修复业务", position = 3)
    @PostMapping("/update")
    public RestResult<String> updateTBizRemPunishment(@RequestBody @Valid TBizRemPunishment tBizRemPunishment, BindingResult bindingResult) {
        AssertUtils.isBndingValidit(bindingResult);
        iTBizRemPunishmentService.updateTBizRemPunishment(tBizRemPunishment);
        return RestResult.ok();
    }

    @ApiOperation(value = "4.查询外省行政处罚修复业务", position = 4)
    @GetMapping("/get")
    public RestResult<?> getTBizRemPunishment(@RequestParam @ApiParam("id") Serializable id) {
        TBizRemPunishment tBizRemPunishment = iTBizRemPunishmentService.getById(id);
        QgCasePubNbaseinfo qgCasePubNbaseinfo = qgCasePubNbaseinfoService.findById(tBizRemPunishment.getPunishmentId());
        TSTaskList task = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>()
                .eq(TSTaskList::getBizseqid, tBizRemPunishment.getBizSeq()));
        return RestResult.ok(new HashMap<String, Object>() {{
            put("punishInfo", tBizRemPunishment);
            put("qgPunInfo", qgCasePubNbaseinfo);
            put("task", task);
        }});
    }

    @ApiOperation(value = "5.分页查询外省行政处罚修复业务", position = 5)
    @PostMapping("/list")
    public RestResult<IPage<TBizRemPunishment>> listTBizRemPunishment(@RequestBody BaseQuery<TBizRemPunishment> query) {
        IPage<TBizRemPunishment> data = iTBizRemPunishmentService.listTBizRemPunishment(query);
        return RestResult.ok(data);
    }

    @ApiOperation(value = "6.查询外省行政处罚记录", position = 6)
    @PostMapping("/punishmentList")
    public RestResult<IPage<?>> punishmentList(@RequestBody PageRequestDto pageRequestDto) {
        // 获取当前用户所在辖区
        AICUser curUser = SSOUtil.getUser();
        
        // 设置查询参数，排除已修复的数据
        pageRequestDto.getParamMap().put("excludeRepaired", true);
        
        // 外省数据查询
        IPage<QgCasePubNbaseinfo> iPage = qgCasePubNbaseinfoService.searchByPage(
                new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), 
                pageRequestDto.getParamMap());
        return RestResult.ok(iPage);
    }

    @ApiOperation(value = "7.启动外省行政处罚修复待办", position = 7)
    @PostMapping("/startTask")
    public RestResult<?> startTask(@RequestBody TBizRemPunishment tBizRemPunishment) {
        // 检查是否已有修复业务
        Integer count = iTBizRemPunishmentService.lambdaQuery()
                .eq(TBizRemPunishment::getPunishmentId, tBizRemPunishment.getPunishmentId()).count();
        if (count > 0) {
            throw new BusinessException("该行政处罚记录已有修复业务");
        }
        
        AICUser loginUser = SSOUtil.getUser();
        Map<String, String> resultMap = new HashMap<>();
        
        // 从跨省表获取处罚信息
        QgCasePubNbaseinfo qgCasePubNbaseinfo = qgCasePubNbaseinfoService.findById(tBizRemPunishment.getPunishmentId());
        if (qgCasePubNbaseinfo == null) {
            throw new BusinessException("未找到对应的行政处罚记录");
        }

        // 生成业务号
        String bizSeq = IdUtil.simpleUUID();
        tBizRemPunishment.setId(bizSeq);
        tBizRemPunishment.setUserId(loginUser.getPrimaryKey());
        tBizRemPunishment.setStatus("0");
        tBizRemPunishment.setLinkType("1");
        tBizRemPunishment.setBizSeq(bizSeq);
        // 跨省主体的pripid从QG表获取
        tBizRemPunishment.setPripid(qgCasePubNbaseinfo.getPripid());
        this.iTBizRemPunishmentService.save(tBizRemPunishment);

        // 启动工作流
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizSeq);
        tsTaskList.setBustype(BaseDataConstant.BUSINESS_TYPE_REM_PUNISH);
        tsTaskList.setBusname(qgCasePubNbaseinfo.getEntname());
        // 新待办设置待办信息
        tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, loginUser);
        // 开始工作流
        taskListService.startWorkFlow(tsTaskList, loginUser, FlowUtil.REM_PUNISH_WORKFLOW);

        // 返回结果
        resultMap.put("taskId", tsTaskList.getTasklistid());
        resultMap.put("bizSeq", bizSeq);
        resultMap.put("workflowId", tsTaskList.getWorkflowid());
        return RestResult.ok(resultMap);
    }

    @ApiOperation(value = "8.提交外省行政处罚修复待办", position = 8)
    @PostMapping("/submitTask")
    public RestResult<?> submitTask(@RequestBody TBizRemPunishment tBizRemPunishment) {
        List<TSTaskList> listTask = taskListService.selectByBizSeqID(tBizRemPunishment.getBizSeq());
        AssertUtils.isTrue(!listTask.isEmpty(), ResultCode.DATA_NONE);
        
        // 意见不能为空
        if (StringUtils.isEmpty(tBizRemPunishment.getOpinion())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }

        // 业务不是处于审批状态时，需要有下一步操作人
        if (!StringUtils.equals(tBizRemPunishment.getLinkType(), "2")
                && StringUtils.isEmpty(tBizRemPunishment.getNextPerformerids())) {
            // 除非是不予受理或者是回退操作
            if (!StringUtils.equals(tBizRemPunishment.getIsAccept(), "0")
                    && !"returnRemPunish".equals(tBizRemPunishment.getNextNodeId())) {
                return RestResult.error(ResultCode.PARAM_IS_BLANK);
            }
        }

        // 判断文书模板是否有数据，除非是不予受理
        Tswrittemplate tswrittemplate = null;
        if (!StringUtils.equals(tBizRemPunishment.getIsAccept(), "0")) {
            List<Tswrittemplate> tswrittemplateList = tswrittemplateService.list(new LambdaQueryWrapper<Tswrittemplate>()
                    .eq(Tswrittemplate::getIsTemplate, "0")
                    .eq(Tswrittemplate::getBizseq, tBizRemPunishment.getBizSeq()));
            if (tswrittemplateList.isEmpty()) {
                return RestResult.error(ResultCode.DATA_NONE);
            }
            tswrittemplate = tswrittemplateList.get(0);
        }

        // 调用提交处理
        iTBizRemPunishmentService.submitTaskN(tBizRemPunishment, listTask.get(0), tswrittemplate, qgCasePubNbaseinfoService, crECaseService);
        return RestResult.ok();
    }

    @ApiOperation(value = "9.上传附件", position = 9)
    @PostMapping("/upload")
    public RestResult<?> upload(MultipartFile[] files, String attachType, String id) throws IOException {
        AICUser curUser = SSOUtil.getUser();
        // 获得上传目录
        String realPath = CommonConfig.getRemPunishmentPath() + File.separator + id;

        for (MultipartFile multipartFile : files) {
            String fileName = multipartFile.getOriginalFilename();
            String ext = StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(Constant.DOT) > -1 ? fileName.substring(fileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
            String virtualFileName = IdUtil.simpleUUID() + ext;
            fileStorageService.writeFromStream(realPath, virtualFileName, multipartFile.getInputStream());

            TSAttachment tsAttachment = new TSAttachment();
            tsAttachment.setBizseq(id);
            tsAttachment.setPripid(StringUtils.EMPTY);
            tsAttachment.setFileext(ext);
            tsAttachment.setFilename(fileName);
            tsAttachment.setFileurl(realPath + File.separator + virtualFileName);
            tsAttachment.setUploaddate(LocalDate.now());
            tsAttachment.setUserid(curUser.getPrimaryKey());
            tsAttachment.setUsername(curUser.getName());
            tsAttachment.setAttachtype(attachType); // 1-信用修复决定审批表 2-准予信用修复决定文书 3-补充材料
            attachmentService.save(tsAttachment);
        }

        return RestResult.ok();
    }

    @ApiOperation(value = "10.附件回显", position = 10)
    @GetMapping(value = "/listFile")
    public RestResult<List<TSAttachment>> listFile(@RequestParam String id) {
        AssertUtils.isNotBlank(id);
        return RestResult.ok(attachmentService.lambdaQuery().eq(TSAttachment::getBizseq, id).list());
    }

    @ApiOperation(value = "11.材料文件下载", position = 11)
    @GetMapping("/downloadFile")
    public void uploadFile(@RequestParam String fileId, HttpServletResponse response) throws IOException {
        TSAttachment tsAttachment = attachmentService.getById(fileId);
        if (tsAttachment == null) {
            throw new BusinessException("文件无法找到" + fileId);
        }
        response.setHeader("Content-Disposition", "attachment;  filename=\"" + new String(tsAttachment.getFilename().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");
        fileStorageService.writeToStream(tsAttachment.getFileurl(), response.getOutputStream());
    }

    @ApiOperation(value = "12.附件删除", position = 12)
    @GetMapping("/delFile")
    public RestResult<?> delFile(@RequestParam String id) {
        TSAttachment tsAttachmentModel = attachmentService.getById(id);
        if (tsAttachmentModel == null) return RestResult.error(ResultCode.DATA_NONE);
        String realPath = CommonConfig.getUploadPath() + File.separator + tsAttachmentModel.getTemppath();
        try {
            Files.delete(Paths.get(realPath));
        } catch (IOException e) {
            log.error("删除文件异常", e);
        }
        attachmentService.removeById(id);
        return RestResult.ok();
    }

}
