package com.chinaweal.aiccs.aiccs.abnormal.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizSpeList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.Toincludeabn;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizSpeListService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.abnormal.service.ToincludeabnService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.revoke.service.BizRevEntService;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.aiccs.revoke.service.CreateFileService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
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.StringUtils;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aicorg.model.AICUser;
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 com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 附件相关业务接口
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/26 14:05
 **/
@RestController
@RequestMapping("/attachment")
@Slf4j
public class AttachmentController extends BaseController {

    @Autowired
    private TSAttachmentService attachmentService;

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private ToincludeabnService toincludeabnService;
    @Resource
    private TSBizSpeListService bizSpeListService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Resource
    private TswrittemplateService tswrittemplateService;
    @Resource
    private CaseService caseService;
    @Resource
    private CreateFileService createFileService;
    @Resource
    private TsbizrevlistService tsbizrevlistService;

    @Autowired
    private TSTaskListService taskListService;

    /**
     * 附件预上传
     *
     * @param file    文件id
     * @param bizseq 业务id
     * @param request 请求信息
     * @return 上传文件的信息
     * @author lroyia
     * @since 2021年2月5日 14:23:30
     */
    @PostMapping("uploadAdvance")
    public RestResult<?> uploadFileAdvance(MultipartFile file, String bizseq, String attachtype, HttpServletRequest request) {
        // 获得上传目录
        AICUser curUser = getLoginUser(request);
        String realPath = CommonConfig.getUploadPathByDate();
        String fileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(Constant.DOT) > -1 ? fileName.substring(fileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String contentType = file.getContentType();//文件的类型（MIME）、内容类型
        String tempPath = realPath + File.separator + fileName;

        try {
//            file.transferTo(newFile);
            fileStorageService.writeFromStream(realPath,fileName,file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            throw new RuntimeException(e.getMessage());
        }
        /*
         * D:/aiccs_upload/2015-05-28/adfjlkfj-dfdfjl-dfdf-dffdfd.doc
         * File.separator
         */
//        Date date = new Date();
//        String dateFamt = DateUtil.dateToString(date, "yyyy-MM-dd");
        AICUser user = getLoginUser(request);
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setPripid(StringUtils.EMPTY);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(fileName);
        tsAttachmentModel1.setTemppath(tempPath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(user.getPrimaryKey());
        tsAttachmentModel1.setUsername(user.getName());
        if(StringUtils.isNotEmpty(attachtype)){
            tsAttachmentModel1.setAttachtype(attachtype);
        }
        attachmentService.save(tsAttachmentModel1);
        return RestResult.ok(tsAttachmentModel1);
    }

    /**
     * 业务中区分环节附件预上传
     *
     * @param file    文件id
     * @param bizseq 业务id
     * @param request 请求信息
     * @return 上传文件的信息
     * @author Lee
     * @since 2021年5月31日 11点00分
     */
    @PostMapping("uploadAdvanceWithAttachtype")
    public RestResult<?> uploadFileAdvance(MultipartFile file, TSAttachment tsAttachmentModel, String bizseq, HttpServletRequest request) {
        // 获得上传目录
        AICUser curUser = getLoginUser(request);
        if(curUser == null )return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        String realPath = CommonConfig.getUploadPathByDate();
        String fileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(Constant.DOT) > -1 ? fileName.substring(fileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String contentType = file.getContentType();//文件的类型（MIME）、内容类型

        String tempPath = realPath + File.separator + fileName;

        try {
            fileStorageService.writeFromStream(realPath,fileName,file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            throw new RuntimeException(e.getMessage());
        }
        /*
         * D:/aiccs_upload/2015-05-28/adfjlkfj-dfdfjl-dfdf-dffdfd.doc
         * File.separator
         */
//        Date date = new Date();
//        String dateFamt = DateUtil.dateToString(date, "yyyy-MM-dd");
        AICUser user = getLoginUser(request);
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setPripid(StringUtils.EMPTY);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(fileName);
        tsAttachmentModel1.setTemppath(tempPath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(user.getPrimaryKey());
        tsAttachmentModel1.setUsername(user.getName());
        tsAttachmentModel1.setFiletype(tsAttachmentModel.getFiletype());// 区分业务
        tsAttachmentModel1.setAttachtype(tsAttachmentModel.getAttachtype());// 区分环节
        attachmentService.save(tsAttachmentModel1);
        return RestResult.ok(tsAttachmentModel1);
    }


    /**
     * 上传文件
     *
     * @param request           请求
     * @param file              上传的文件对象
     * @param tsAttachmentModel 附件信息
     * @param pripids           企业pripid
     * @param filename          文件名
     * @return 上传结果
     * @throws IOException io异常
     * @author lroyia
     * @since 2021年1月26日 14:58:51
     */
    @PostMapping("/saveTCLawFile.do")
    public RestResult<?> saveTCLawFile(HttpServletRequest request, MultipartFile file,
                                       TSAttachment tsAttachmentModel, String pripids, String filename) throws IOException {

        String oldFileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(oldFileName) && oldFileName.lastIndexOf(Constant.DOT) > -1 ? oldFileName.substring(oldFileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String contentType = file.getContentType();//文件的类型（MIME）、内容类型

        String fileName = UUID.randomUUID() + ext;

        // 不再存到根目录
        String path = CommonConfig.getUploadPathByDate();
        path = path + File.separator + "xyxf";
        //其他文件
        try(InputStream is = file.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            Boolean success = false;
            if (StringUtils.containsIgnoreCase(contentType, "image")
                    && file.getSize() >= 500 * 1024 ) { // 改成大于500k压缩
                //压缩图片
                TimeInterval timer = DateUtil.timer();
//                Thumbnails.of(is).scale(1f).outputQuality(0.5f).toOutputStream(bos);

                byte[] imageBytes = file.getBytes();
                int fileSize = imageBytes.length; // 原长度
                int i = 0;
                float piz = (float) 0.5; // 压缩品质
                while (imageBytes.length > 500 * 1024) {
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                    Thumbnails.of(inputStream).scale(1f).outputQuality(piz).outputFormat("jpg").toOutputStream(outputStream);
//                    Thumbnails.of(inputStream).scale(1f).outputQuality(piz).toOutputStream(outputStream); // png 不压缩
                    imageBytes = outputStream.toByteArray();
                    inputStream.close();
                    outputStream.close();
                    piz = (float) (piz - 0.2);
                    if (piz < (float) 0.1) break;
                    if (imageBytes.length == fileSize) break; // 不可由Thumbnails压缩图片
                    if (i > 3 ) break; // 超过4次循环退出
                    i++;
                }
                log.debug("图片压缩耗时： {} ms", timer.interval());
                success = fileStorageService.writeFromStream(path, fileName, new ByteArrayInputStream(imageBytes));
            } else {
                success = fileStorageService.writeFromStream(path, fileName, is);
            }
            // 存在上传失败，不抛异常的情况
            if (!success) {
                throw new RuntimeException("文件上传失败" + path);
            }
        } catch (Exception e) {
            log.error("上传出错", e);
            throw new RuntimeException(e.getMessage());
        }

        String filePath = path + File.separator + fileName;
        AICUser user = getLoginUser(request);

        List<TSAttachment> result = new ArrayList<>();
        if (StringUtils.isNotBlank(pripids)) {
            String[] pripid = pripids.split(";");
            for (int i = 0; i < pripid.length; i++) {
                TSAttachment tsAttachmentModel1 = new TSAttachment();
                tsAttachmentModel1.setBizseq(tsAttachmentModel.getBizseq());
                tsAttachmentModel1.setFiletype(tsAttachmentModel.getFiletype());
                tsAttachmentModel1.setFileext(ext);
                tsAttachmentModel1.setAttachtype(tsAttachmentModel.getAttachtype());
                tsAttachmentModel1.setPripid(pripid[i]);
                tsAttachmentModel1.setFilename(oldFileName);
                tsAttachmentModel1.setTemppath(filePath);
                tsAttachmentModel1.setUploaddate(LocalDate.now());
                if (user != null) {
                    tsAttachmentModel1.setUserid(user.getPrimaryKey());
                    tsAttachmentModel1.setUsername(user.getName());
                }
                attachmentService.saveOrUpdate(tsAttachmentModel1);
                result.add(tsAttachmentModel1);
            }
        }
        return RestResult.ok(result);
    }

    /**
     * 文件下载
     */
    @RequestMapping("/downloadWrit.do")
    public RestResult<?> downloadWrit(HttpServletRequest request, String attachmentid, @RequestHeader("User-Agent") String userAgent) throws IOException {
        boolean isMSIE = StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident");
        String fileName;
        byte[] bytes;
        TSAttachment tsAttachmentModel = attachmentService.getById(attachmentid);
        if (tsAttachmentModel == null) {
            throw new BusinessException("otherBizWritInfoModel 为 null，请检查数据库表：TCOtherBizWritInfo。otherbizwritinfoid：" + attachmentid);
        }
        String realPath = CommonConfig.getUploadPath() + "/" + tsAttachmentModel.getTemppath();
        String suffix = realPath.substring(realPath.lastIndexOf("."));

        File file = new File(realPath);
        if (!file.exists()) {
            throw new BusinessException("文件 " + file.getAbsolutePath() + " 不存在。otherbizwritinfoid：" + attachmentid);
        }
        fileName = tsAttachmentModel.getFilename() + suffix;
        //为了解决中文名称乱码问题
        fileName = isMSIE ? URLEncoder.encode(fileName, "UTF-8") : new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        bytes = FileUtils.readFileToByteArray(file);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return OK;
    }

    /**
     * 通用文件下载
     */
    @GetMapping("/download")
    public void download(String id, HttpServletResponse response) throws IOException {
        TSAttachment tsAttachmentModel = attachmentService.getById(id);
        if (tsAttachmentModel == null) {
            throw new BusinessException("文件无法找到" + id);
        }
        response.setHeader("Content-Disposition", "attachment;  filename=\"" + new String(tsAttachmentModel.getFilename().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");
        fileStorageService.writeToStream(tsAttachmentModel.getFileurl(), response.getOutputStream());
    }


    /**
     * 下载系统模板文件
     *
     * @param request
     * @param filePath
     * @param userAgent
     * @return
     * @throws IOException
     */
    @RequestMapping("/downloadTemplate.do")
    public RestResult<?> downloadTemplate(HttpServletRequest request, String filePath, @RequestHeader("User-Agent") String userAgent) throws IOException, URISyntaxException {
        boolean isMSIE = StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident");

        byte[] bytes;

        String classesRoot = this.getClass().getClassLoader().getResource("/").toURI().getPath();
        String realPath = classesRoot + "/" + filePath;

        File file = new File(realPath);
        if (!file.exists()) {
            throw new BusinessException("文件 " + file.getAbsolutePath() + " 不存在");
        }

        String fileName = file.getName();
        //为了解决中文名称乱码问题
        fileName = isMSIE ? URLEncoder.encode(fileName, "UTF-8") : new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        bytes = FileUtils.readFileToByteArray(file);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return OK;
    }

    /**
     * 删除上传文件
     *
     * @param id 附件记录id
     * @return
     */
    @PostMapping("/delLawFile.do")
    public RestResult<?> delLawFile(String id) {
        TSAttachment tsAttachmentModel = attachmentService.getById(id);
        String realPath = CommonConfig.getUploadPath() + File.separator + tsAttachmentModel.getTemppath();
        File file = new File(realPath);
        if (file.exists()) {
            file.delete();
        }
        attachmentService.removeById(id);
        return OK;
    }

    /**
     * 上传材料回显
     */
    @RequestMapping(value = "/selectwritByPage.do", method = RequestMethod.POST)
    public List<TSAttachment> selectwritByPage(TSAttachment tsWritModel) {
        List<TSAttachment> tsAttachments = attachmentService.selectwritByPage(tsWritModel);
        for (TSAttachment tsAttachment : tsAttachments) {
            if(StringUtils.isBlank(tsAttachment.getTemppath())){
                tsAttachment.setTemppath(tsAttachment.getFileurl());
            }
        }
        return tsAttachments;
    }
    /**
     * 上传材料回显
     */
    @RequestMapping(value = "/getAttachmentList", method = RequestMethod.POST)
    public List<TSAttachment> getAttachmentList(@RequestBody TSAttachment tsAttachmentModel) {
        AssertUtils.isNotBlank(tsAttachmentModel.getBizseq());
        LambdaQueryWrapper<TSAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSAttachment::getBizseq,tsAttachmentModel.getBizseq())
                .eq(StringUtils.isNotBlank(tsAttachmentModel.getFiletype()),TSAttachment::getFiletype,tsAttachmentModel.getFiletype())
                .eq(StringUtils.isNotBlank(tsAttachmentModel.getAttachtype()),TSAttachment::getAttachtype,tsAttachmentModel.getAttachtype());
        List<TSAttachment> list = attachmentService.list(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            for (TSAttachment tsAttachment : list) {
                if(StringUtils.isBlank(tsAttachment.getTemppath())){
                    tsAttachment.setTemppath(tsAttachment.getFileurl());
                }
            }
        }
        return list;
    }

    /**
     * 上传材料回显
     */
    @RequestMapping(value = "/getAttachmentList_app", method = RequestMethod.POST)
    public List<TSAttachment> getAttachmentList_app(@RequestBody TSAttachment tsAttachmentModel) {
        AssertUtils.isNotBlank(tsAttachmentModel.getBizseq());
        LambdaQueryWrapper<TSAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSAttachment::getBizseq,tsAttachmentModel.getBizseq())
                .eq(StringUtils.isNotBlank(tsAttachmentModel.getFiletype()),TSAttachment::getFiletype,tsAttachmentModel.getFiletype())
                .eq(StringUtils.isNotBlank(tsAttachmentModel.getPripid()),TSAttachment::getPripid,tsAttachmentModel.getPripid())
                .eq(StringUtils.isNotBlank(tsAttachmentModel.getAttachtype()),TSAttachment::getAttachtype,tsAttachmentModel.getAttachtype());
        return attachmentService.list(wrapper);
    }

    @ApiOperation(value = "文件下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true),
            @ApiImplicitParam(name = "fileName", value = "文件名", required = true)
    })
    @GetMapping("/down")
    public void downFile(@RequestParam("filePath") String filePath, @RequestParam("fileName") String fileName,HttpServletRequest request, HttpServletResponse response) {
//        String url = filePath + File.separator + fileName;
        AICUser loginUser = getLoginUser(request);
        if (loginUser == null) throw new BusinessException("登录超时，请重新登录");
        String ext = filePath.substring(filePath.lastIndexOf(Constant.DOT));
        try {
            if(".xlsx".equals(ext)){
                response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/msexcel;charset=UTF-8");//设置类型
                response.setHeader("Pragma", "No-cache");//设置头
                response.setHeader("Cache-Control", "no-cache");//设置头
                response.setDateHeader("Expires", 0);//设置日期头
            }else {
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            }
//            response.setHeader("Content-Disposition", "attachment;  filename=\"" + fileName + "\"");
            ServletOutputStream os = response.getOutputStream();
            fileStorageService.writeToStream(filePath,os);
        } catch (IOException e) {
            log.error("下载文件发生错误，" + e.getMessage());
            throw new BusinessException("下载文件错误");
        }

    }
    @ApiOperation(value = "批吊业务的听证告知书、处罚决定书文件预下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true),
            @ApiImplicitParam(name = "fileName", value = "文件名", required = true)
    })
    @GetMapping("/revokeDown")
    public void revokeDown(@RequestParam("filePath") String filePath, @RequestParam("fileName") String fileName,
                                         @RequestParam("bizseq") String bizseq,@RequestParam("pripid") String pripid,
                           @RequestParam("attachtype") String attachtype, HttpServletRequest request,HttpServletResponse response) {
        if(StringUtils.isEmpty(filePath) || filePath.equals("null")) {
            // 获取pdf文件流
            try {
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
                ServletOutputStream os = response.getOutputStream();
                if("13".equals(attachtype)) {// 听证告知书
                    tsbizrevlistService.createHearingPdf(bizseq,pripid, fileName, os);
                }else if("14".equals(attachtype)){
                    tsbizrevlistService.createPunishDecPdf(bizseq,pripid, fileName, os);
                }

            } catch (Exception e) {
                log.error("下载文件发生错误，" + e.getMessage());
                throw new BusinessException("下载文件错误");
            }
        }else {
            downFile(filePath, fileName, request,response);
        }
    }



    @PostMapping("uploadFileByBizseq")
    public RestResult<?> uploadFileByBizseq(MultipartFile file, TSAttachment tsAttachment, HttpServletRequest request) {
        // 获得上传目录
        String bizseq = tsAttachment.getBizseq();
        String attachtype = tsAttachment.getAttachtype();
        if (StringUtils.isBlank(bizseq)) {
            bizseq = request.getParameter("bizSeqNo");
        }
        if (StringUtils.isBlank(attachtype)) {
            attachtype = request.getParameter("attachType");
        }
        AICUser curUser = getLoginUser(request);
        String realPath = CommonConfig.getUploadPathByDate();
        // 判断对应模块加上文件夹区分
        List<TSTaskList> taskLists = taskListService.list(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizseq).ne(TSTaskList::getBusstatus, "4"));
        if (taskLists.size()>0) {
            String busyType = taskLists.get(0).getBustype();
            if (BaseDataConstant.SERILLEGAL_TYPE_ENTERSERILLEGAL.equals(busyType)
                    || BaseDataConstant.SERILLEGAL_TYPE_INCLUDEDILLEGAL.equals(busyType)
                    || BaseDataConstant.SERILLEGAL_TYPE_OBJECTION.equals(busyType)) { //严重违法 /seriousillegal
                realPath += File.separator + "seriousillegal";
            } else if (BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP.equals(busyType)
                    || BaseDataConstant.EXPTLIST_TYPE_OBJECTION.equals(busyType)
                    || BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG.equals(busyType)
                    || BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_OBJECTION.equals(busyType)
                    || BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD.equals(busyType)
                    || BaseDataConstant.EXPTLIST_TYPE_FARMER_OBJECTION.equals(busyType)) { //经营异常 /abnormal
                realPath += File.separator + "abnormal";
            }
            // 其他模块，未补上
        }
        String fileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(Constant.DOT) > -1 ? fileName.substring(fileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        // 拼接路劲时文件名称是否带特殊字符，有则转义
        String filenameStr = fileName.replace("%","%25")
                .replace("#","%23");
        String tempPath = realPath + File.separator + filenameStr;
        try {
            fileStorageService.writeFromStream(realPath,fileName,file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        AICUser user = getLoginUser(request);
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setPripid(StringUtils.EMPTY);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(fileName);
        tsAttachmentModel1.setTemppath(tempPath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(user.getPrimaryKey());
        tsAttachmentModel1.setUsername(user.getName());
        tsAttachmentModel1.setFileurl(tempPath);
        tsAttachmentModel1.setLauptime(LocalDateTime.now());
        tsAttachmentModel1.setAttachtype(attachtype);  // 文件类型
        tsAttachmentModel1.setCreatetype("0"); // 生成类型 "0"手动上传 "1"系统生成
        attachmentService.save(tsAttachmentModel1);
        return RestResult.ok(tsAttachmentModel1);
    }

    @PostMapping("/delFile")
    public RestResult<?> delFile(String id) {
        TSAttachment tsAttachmentModel = attachmentService.getById(id);
        try {
            fileStorageService.delFile(tsAttachmentModel.getFileurl());
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        attachmentService.removeById(id);
        return OK;
    }

    @Transactional
    @PostMapping("uploadFileAicods")
    public RestResult<?> uploadFileAicods(MultipartFile file, String bizseq){

        AssertUtils.isNotEmpty(bizseq);
        // 上传前先删除原来的附件 bizseq接收datafromId
        Toincludeabn toincludeabn = toincludeabnService.getByDataFromId(bizseq);
        if(toincludeabn == null) {
            log.info("{}业务号线索列异上传文件，找不到线索",bizseq);
            return RestResult.error(ResultCode.DATA_NONE,"上传失败");
        }
        TSBizSpeList bizSpeList = bizSpeListService.getByToIncludeId(toincludeabn.getToIncludeId());
        if(bizSpeList == null) {
            log.info("{}业务号线索列异上传文件，找不到业务信息",bizseq);
            return RestResult.error(ResultCode.DATA_NONE,"上传失败");
        }
        // 更新附件列表
        TSAttachment tsAttachment = new TSAttachment();
        tsAttachment.setBizseq(bizSpeList.getBizseq());
        tsAttachment.setAttachtype("1");
        List<TSAttachment> attachments = attachmentService.selectwritByPage(tsAttachment);
        if (CollectionUtils.isNotEmpty(attachments)) {
            for (TSAttachment attachment : attachments) {
                attachmentService.removeById(attachment.getAttachmentid());
            }
        }
        String realPath = CommonConfig.getUploadPathByDate();
        realPath += File.separator + "aicodsNM" + File.separator + bizseq;
        String fileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(fileName) && fileName.lastIndexOf(Constant.DOT) > -1 ? fileName.substring(fileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String contentType = file.getContentType();//文件的类型（MIME）、内容类型
        String tempPath = realPath + File.separator + fileName;

        try {
            fileStorageService.writeFromStream(realPath,fileName,file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("业务号"+ bizseq +"线索列异上传文件,上传FTP出错"+e);
            throw new BusinessException("上传失败");
        }
        TSAttachment tsAttachmentModel = new TSAttachment();
        tsAttachmentModel.setBizseq(bizseq);
        tsAttachmentModel.setPripid(StringUtils.EMPTY);
        tsAttachmentModel.setFileext(ext);
        tsAttachmentModel.setFilename(fileName);
        tsAttachmentModel.setTemppath(tempPath);
        tsAttachmentModel.setUploaddate(LocalDate.now());
        boolean save = attachmentService.save(tsAttachmentModel);
        if(save){
            return RestResult.ok(save);
        }else {
            log.info("{}业务号线索列异上传文件,保存文件信息失败",bizseq);
            throw new BusinessException("上传失败");
        }
    }

    @RequestMapping("queryFileByHistory")
    public RestResult<?> queryFileByHistory(String bizseq) {
        return RestResult.ok(attachmentService.queryFileByHistory(bizseq));
    }

    @ApiOperation(value = "6.业务号查询附件", position = 6)
    @PostMapping("/listByBizSepNo")
    public RestResult<List<TSAttachment>> listXrattachment(@RequestBody TSAttachment query) {
        LambdaQueryWrapper<TSAttachment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSAttachment::getBizseq, query.getBizseq())
                .eq(StringUtils.isNotBlank(query.getAttachtype()), TSAttachment::getAttachtype, query.getAttachtype());
        List<TSAttachment> data = attachmentService.list(queryWrapper);
        return RestResult.ok(data);
    }

    @GetMapping("/getMaterial")
    @ApiOperation(value = "预览上传材料", produces = "application/octet-stream")
    public void getMaterial(HttpServletResponse response, String id, String bizSeqNo, String attachType) {
        if ((StringUtils.isBlank(bizSeqNo) || StringUtils.isBlank(attachType)) && StringUtils.isBlank(id)) {
            throw new RuntimeException("参数异常");
        }
        try {
            attachmentService.getMaterial(response, id, bizSeqNo, attachType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
