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.PunishmentUnionDto;
import com.chinaweal.aiccs.aiccs.punishment.entity.TBizRemPunishment;
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.Constant;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.crgs.punish.entity.TbIlcPunInfoQuery;
import com.chinaweal.aiccs.crgs.punish.service.TbIlcPunInfoQueryService;
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.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
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.HashMap;
import java.util.List;

/**
 * <p>
 * 行政处罚修复业务表 控制器
 * </p>
 *
 * @author chinaweal
 * @since 2023-04-10
 */
@Api(tags = "行政处罚修复业务表")
@ApiSort(1)
@RestController
@RequestMapping("/punishment/tBizRemPunishment")
@Slf4j
public class TBizRemPunishmentController extends BaseController {

    @Resource
    private ITBizRemPunishmentService iTBizRemPunishmentService;
    @Resource
    private TbIlcPunInfoQueryService tbIlcPunInfoQueryService;
    @Resource
    private TSTaskListService taskListService;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private TSAttachmentService attachmentService;
    @Resource
    private TswrittemplateService tswrittemplateService;

    @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);
        TbIlcPunInfoQuery tbIlcPunInfoQuery = tbIlcPunInfoQueryService.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("IlcPunInfo", tbIlcPunInfoQuery);
            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<PunishmentUnionDto>> punishmentList(@RequestBody PageRequestDto pageRequestDto) {
        AICUser curUser = SSOUtil.getUser();
        String region = curUser.getRegionID();
        // 自治区的账号可以发起所有的行政处罚，主要是针对药监局的行政处罚
        if (!StringUtils.equals("150000", region)) {
            pageRequestDto.getParamMap().put("region", region);
        }
        IPage<PunishmentUnionDto> iPage = tbIlcPunInfoQueryService.searchUnionByPage(
                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("该行政处罚记录已有修复业务");
        }
        return RestResult.ok(iTBizRemPunishmentService.startTask(tBizRemPunishment));
    }

    @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.submitTask(tBizRemPunishment, listTask.get(0), tswrittemplate);
        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();
    }

}
