package com.chinaweal.aiccs.aiccs.revoke.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
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.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.revoke.entity.BizRevEnt;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsbizrevlist;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.AttachmentWritDto;
import com.chinaweal.aiccs.aiccs.revoke.service.BizRevEntService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.constant.FileParamModelConstant;
import com.chinaweal.aiccs.common.util.PdfUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
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.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.itextpdf.text.DocumentException;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.velocity.runtime.directive.contrib.For;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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


import java.io.IOException;

/**
 *  批量吊销文件controller
 *
 * @Author Lee
 * @Since 2021/5/8 11:29
 */
@Slf4j
@RestController
@Transactional
@RequestMapping("/revokeUpload")
public class UploadController extends BaseController {

    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private BizRevEntService bizRevEntService;

    @ApiOperation("批量注销吊销主体名单导入excel模板检验")
    @PostMapping("templateValid")
    public RestResult<?> templateValid(@ApiParam("上传的excel文件") MultipartFile file, @ApiParam("参数模型名称") String model) {
        AssertUtils.isNotNull(file);
        AssertUtils.isNotBlank(model);
        Map<String, String> modelMap = FileParamModelConstant.getModel(model);
        if (modelMap == null) {
            return RestResult.error(ResultCode.PARAM_IS_INVALID);
        }
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        Workbook book;
        try (InputStream is = file.getInputStream()) {
            if (ext.equals(".xls")) {
                book = new HSSFWorkbook(is);
            } else {
                book = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            log.error("上传查询参数文件错误", e);
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
        }
        Sheet sheet = book.getSheetAt(0);
        // 读取文件头，获取参数名
        Row header = sheet.getRow(0);
        if (header == null) {
            log.error("导入名单模版表头为空");
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"导入名单模版表头为空");
        }
        List<String> headerNames = new ArrayList<>();
        for (int i = 0; i < header.getLastCellNum(); i++) {
            if (StringUtils.isNotBlank(header.getCell(i).getStringCellValue())) {
                headerNames.add(header.getCell(i).getStringCellValue());
            }
        }
        if (headerNames.size() == 0) {
            log.error("导入名单模版表头为空");
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"导入名单模版表头为空");
        }
        for (String headerName : headerNames) {
            if (StringUtils.isNotBlank(headerName) && modelMap.get(headerName) == null){
                log.error("导入名单模版找不到["+ headerName +"]");
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"导入名单模版错误");
            }
        }
        return RestResult.ok();
    }

    /**
     * 剔除附件预上传
     *
     * @param file      文件id
     * @param bizseq    业务号
     * @param request   请求信息
     * @return          上传文件的信息
     * @author          Lee
     * @since           2021年5月10日 14:20:30
     */
    @PostMapping("remUploadAdvance")
    public RestResult<?> remUploadAdvance(MultipartFile file, String bizseq, HttpServletRequest request) {
        // 获得上传目录
        AICUser curUser = getLoginUser(request);
        LambdaQueryWrapper<BizRevEnt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizRevEnt::getBizseq,bizseq).eq(BizRevEnt::getIsremove,"1").orderByDesc(BizRevEnt::getRemovetime);
        List<BizRevEnt> list = bizRevEntService.list(wrapper);

        String remNoStr = "remNO1";
        int remNo = 1;
        if(list.size() > 0 && list.get(0).getRemno() != null){
            remNo = list.get(0).getRemno()+ 1;
            remNoStr = "remNO" + remNo;
        }
        String oldFileName = file.getOriginalFilename();
        String filePath = "BatchRevocation" + File.separator + bizseq + File.separator + remNoStr + File.separator + System.currentTimeMillis() + oldFileName;
        String realPath = CommonConfig.getUploadPath() + File.separator + filePath;
        String ext = StringUtils.isNotBlank(oldFileName) && oldFileName.lastIndexOf(Constant.DOT) > -1 ? oldFileName.substring(oldFileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String contentType = file.getContentType();//文件的类型（MIME）、内容类型
        try(InputStream is = file.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            if (StringUtils.containsIgnoreCase(contentType, "image")
                    && file.getSize() >= 5 * 1024 * 1024) { // 小于5M不压缩
                //压缩图片
                TimeInterval timer = DateUtil.timer();
                Thumbnails.of(is).scale(1f).outputQuality(0.5f).toOutputStream(bos);
                log.debug("图片压缩耗时： {} ms", timer.interval());
                fileStorageService.writeFromStream(realPath, new ByteArrayInputStream(bos.toByteArray()));
            } else {
                fileStorageService.writeFromStream(realPath, is);
            }
        } catch (Exception e) {
            log.error("上传出错", e);
            return RestResult.error(ResultCode.MYSTERIOUS_ERROR,"上传失败");
        }

        AICUser user = getLoginUser(request);
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setRemNo(remNo);
        tsAttachmentModel1.setPripid(StringUtils.EMPTY);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(oldFileName);
        tsAttachmentModel1.setTemppath(realPath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(user.getPrimaryKey());
        tsAttachmentModel1.setUsername(user.getName());
        attachmentService.save(tsAttachmentModel1);
        return RestResult.ok(tsAttachmentModel1);
    }

//    /**
//     * 附件预上传
//     *
//     * @param file       文件id
//     * @param bizseq     业务id
//     * @param request    请求信息
//     * @return           上传文件的信息
//     * @author           Lee
//     * @since            2021年2月5日 14:23:30
//     */
//    @PostMapping("uploadAdvance")
//    public RestResult<?> uploadFileAdvance(MultipartFile file, TSAttachment tsAttachmentModel, String bizseq, HttpServletRequest request) {
//        // 获得上传目录
//        AICUser curUser = getLoginUser(request);
//        String realPath = CommonConfig.getUploadPath();
//        realPath += File.separator + curUser.getPrimaryKey() + File.separator + bizseq;
//        File dir = new File(realPath);
//        dir.mkdirs();
//        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 = curUser.getPrimaryKey() + File.separator + bizseq + File.separator + fileName;
//        File newFile = new File(realPath, fileName);
//
//        try {
//            file.transferTo(newFile);
//        } catch (IOException 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.setAttachtype(tsAttachmentModel.getAttachtype());// 区分环节："1"立案"2"调查"3"听证告知"4"决定"5"送达与结束
//        attachmentService.save(tsAttachmentModel1);
//        return RestResult.ok(tsAttachmentModel1);
//    }

    /**
     * 附件上传 优化
     *
     * @param file       文件id
     * @param bizseq     业务id
     * @param request    请求信息
     * @return           上传文件的信息
     * @author           Lee
     * @since            2021年11月22日 14:23:30
     */
    @PostMapping("uploadAdvance")
    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 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 filePath = "BatchRevocation" + File.separator + bizseq + File.separator + System.currentTimeMillis() + oldFileName;
        try(InputStream is = file.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            if (StringUtils.containsIgnoreCase(contentType, "image")
                    && file.getSize() >= 5 * 1024 * 1024) { // 小于5M不压缩
                //压缩图片
                TimeInterval timer = DateUtil.timer();
                Thumbnails.of(is).scale(1f).outputQuality(0.5f).toOutputStream(bos);
                log.debug("图片压缩耗时： {} ms", timer.interval());
                fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + filePath, new ByteArrayInputStream(bos.toByteArray()));
            } else {
                fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + filePath, is);
            }
        } catch (Exception e) {
            log.error("上传出错", e);
            return RestResult.error(ResultCode.MYSTERIOUS_ERROR,"上传失败");
        }
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setPripid(StringUtils.EMPTY);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(oldFileName);
        tsAttachmentModel1.setTemppath(CommonConfig.getUploadPath() + File.separator + filePath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(curUser.getPrimaryKey());
        tsAttachmentModel1.setUsername(curUser.getName());
        tsAttachmentModel1.setAttachtype(tsAttachmentModel.getAttachtype());// 区分环节："1"立案"2"调查"3"听证告知"4"决定"5"送达与结束
        attachmentService.save(tsAttachmentModel1);
        return RestResult.ok(tsAttachmentModel1);
    }

    /**
     * 剔除附件回显
     */
    @PostMapping("/getRemFileList")
    public List<TSAttachment> getRemFileList(TSAttachment tsWritModel) {
        LambdaQueryWrapper<TSAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSAttachment::getBizseq,tsWritModel.getBizseq())
                .eq(TSAttachment::getRemNo,tsWritModel.getRemNo());
        return attachmentService.list(wrapper);
    }

    /**
     * 上传附件按环节回显
     */
    @PostMapping("/getUploadFileList")
    public List<TSAttachment> getUploadFileList(TSAttachment tsWritModel) {
        LambdaQueryWrapper<TSAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSAttachment::getBizseq,tsWritModel.getBizseq())
                .eq(StringUtils.isNotBlank(tsWritModel.getAttachtype()),TSAttachment::getAttachtype,tsWritModel.getAttachtype())
                .eq(TSAttachment::getCreatetype,"0");
        return attachmentService.list(wrapper);
    }

    /**
     * 系统生成文书回显
     */
    @PostMapping("/getSystemFileList")
    public RestResult<?> getSystemFileList(@RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto, pageRequestDto.getCustomParamMap());// 要改
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
        String attachtype = StringUtils.tranObject(customParamMap.get("attachtype"));
        String uniscid = StringUtils.tranObject(customParamMap.get("uniscid"));
        String entname = StringUtils.tranObject(customParamMap.get("entname"));
        AssertUtils.isNotBlank(bizseq,attachtype);
        if("13".equals(attachtype) || "14".equals(attachtype)){
            AttachmentWritDto dto = new AttachmentWritDto();
            dto.setBizseq(bizseq);
            dto.setEntname(entname);
            dto.setUniscid(uniscid);
            dto.setAttachtype(attachtype);
            IPage<AttachmentWritDto> page = attachmentService.selectWritsList(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), dto);
            return RestResult.ok(page);
        }else if ("64".equals(attachtype)){
            AttachmentWritDto dto = new AttachmentWritDto();
            dto.setBizseq(bizseq);
            dto.setEntname(entname);
            dto.setUniscid(uniscid);
            dto.setAttachtype(attachtype);
            IPage<AttachmentWritDto> page = attachmentService.selectWritsListzx(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), dto);
            return RestResult.ok(page);
        }
        else {
            pageRequestDto.checkDefault(1, 10, "uploaddate");
            IPage<TSAttachment> page = attachmentService.defaultPaging(pageRequestDto, w -> {
                LambdaQueryWrapper<TSAttachment> wrapper = w.lambda();
                if("99".equals(attachtype)){// 名单附件类型
                    wrapper.in(TSAttachment::getAttachtype,"21","22","23");
                }else {
                    wrapper.eq(TSAttachment::getAttachtype,attachtype);
                }
                wrapper.eq(TSAttachment::getBizseq, bizseq)
                        .eq(TSAttachment::getCreatetype, "1");
            }, null);
            return RestResult.ok(page);
        }
    }

//    @PostMapping("word2Pdf")
//    public RestResult<?> word2Pdf(String attachmentid,String bizseq){
//        String realPath = CommonConfig.getUploadPath();
//        TSAttachment attachment = attachmentService.getById(attachmentid);
//        String wordPath = realPath + File.separator + attachment.getTemppath();
//        File file = new File(wordPath);
//        if (!file.exists()){
//            return RestResult.error(ResultCode.PARAM_IS_INVALID.setMessage("访问路径错误或文件不存在！"));
//        }
//        String fileName = wordPath.substring(wordPath.lastIndexOf(File.separator)+1, wordPath.lastIndexOf(Constant.DOT));
//        String pdfTemppath = bizseq + File.separator + "PDF" + File.separator + fileName + ".pdf";
//        String pdfPath = CommonConfig.getUploadPath() + File.separator + pdfTemppath;
//        File pdfFile = new File(pdfPath);
//
//        if(!pdfFile.exists()){
//            pdfFile.getParentFile().mkdirs();
//            PdfUtil.convertDocx2Pdf(wordPath, pdfPath);
//        }
//        return RestResult.ok(pdfTemppath);
//
//    }


    /**
     * word转pdf字节流
     * @param attachmentid
     * @param bizseq
     * @param writsid
     * @param response
     * @return
     */
    @PostMapping("word2Pdf")
    public RestResult<?> word2Pdf(String attachmentid,String bizseq, String writsid, HttpServletResponse response){
        TSAttachment attachment = attachmentService.getById(attachmentid);
        String temppath = attachment.getTemppath();
//        if(StringUtils.isBlank(temppath)){
//            String hearingPath = null;
//            try {
//                hearingPath = tsbizrevlistService.createHearingPath(writsid, attachment.getFilename());
//            } catch (Exception e) {
//                e.printStackTrace();
//                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR.setMessage("打开失败，找不到文件"));
//            }
//            attachment.setTemppath(hearingPath);
//            boolean update = attachmentService.updateById(attachment);
//            if(update){
//                temppath = hearingPath;
//            }
//        }
        String realPath = CommonConfig.getUploadPath();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        fileStorageService.writeToStream(temppath,bos);
        String fileName = temppath.substring(temppath.lastIndexOf(File.separator)+1, temppath.lastIndexOf(Constant.DOT));
        String pdfTemppath = bizseq + File.separator + "PDF" + File.separator + fileName + ".pdf";
        String pdfPath = realPath + File.separator + pdfTemppath;
        PdfUtil.convertDocx2PdfStream(bos,pdfPath,response);
        return RestResult.ok(pdfPath);
    }


}
