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

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.revoke.entity.TsCase;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.AttachmentWritDto;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.util.MapUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.ZipUtil;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.redis.RedisService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * @author Lee
 * @since 2021/6/8 15:20
 */
@Slf4j
@RestController
@Transactional
@RequestMapping("/revokeDownload")
public class DownloadController extends BaseController {

    private static final String REDIS_KEY_PREFIX = "REVOKE_DOWNLOAD:";
    private static final int CACHE_EXPIRE_TIME = 20 * 60;

    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private RedisService redisService;

    @GetMapping("downZip")
    public void downZip(String bizseq, String attachtype, String batchNo,String batchSize, HttpServletResponse response) {
        Long timeMilles = System.currentTimeMillis();
        if("13".equals(attachtype) || "14".equals(attachtype)){
            String cacheKey = REDIS_KEY_PREFIX + bizseq;
            String cacheValue = redisService.get(cacheKey);
            if(cacheValue == null){
                redisService.set(cacheKey, "true", CACHE_EXPIRE_TIME);
            }else {
                boolean flag = "true".equals(cacheValue);
                if(!flag) {
                    redisService.set(cacheKey, "true", CACHE_EXPIRE_TIME);
                }else {
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                    return;
                }
            }
            HashMap<String, String> map = null;
            try {
                map = valid(bizseq, batchNo, batchSize,attachtype);
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                redisService.set(cacheKey, "false", CACHE_EXPIRE_TIME);
                e.printStackTrace();
                return;
            }
            if(MapUtils.isNotEmpty(map)){
                String zipName = "附件.zip";
                ZipUtil.downloadZipFiles(response, map, zipName);
                redisService.set(cacheKey, "false", CACHE_EXPIRE_TIME);
            }
        }else {
            LambdaQueryWrapper<TSAttachment> wrapper = new LambdaQueryWrapper<>();
            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");
            List<TSAttachment> fileList = attachmentService.list(wrapper);
//        if(fileList.size() == 0){
//            return RestResult.error(ResultCode.DATA_NONE.setMessage("找不到指定文件"));
//        }else {
            if(fileList.size() > 0){
                String zipName = new File(fileList.get(0).getTemppath()).getParentFile().getName() + ".zip";
                // key 文件路径，value 文件名
                HashMap<String, String> map = new HashMap<>();

                for (TSAttachment tsAttachment : fileList) {
                    map.put(tsAttachment.getTemppath(),tsAttachment.getFilename());
                }
                ZipUtil.downloadZipFiles(response, map, zipName);
            }else {
                throw new BusinessException("找不到指定文件");
            }
        }
        log.info("》》》》》》》》》》》》批量下载附件耗时(毫秒):{}《《《《《《《《《",System.currentTimeMillis()-timeMilles);
    }

    private HashMap<String, String> valid(String bizseq,String batchNo,String batchSize,String attachtype) throws Exception{
        int batchNoNum = Integer.parseInt(batchNo);
        int batchSizeNum = Integer.parseInt(batchSize);
        AttachmentWritDto dto = new AttachmentWritDto();
        dto.setBizseq(bizseq);
        dto.setAttachtype(attachtype);
        IPage<AttachmentWritDto> page = attachmentService.selectWritsList(new Page<>(batchNoNum, batchSizeNum), dto);
        List<AttachmentWritDto> records = page.getRecords();
        HashMap<String, String> map = new HashMap<>();
        if(CollectionUtils.isEmpty(records)){
            throw new BusinessException("找不到指定文件");
        }else {
            for (AttachmentWritDto record : records) {
                if(StringUtils.isEmpty(record.getTemppath())){
                    map.clear();
                    throw new BusinessException("系统后台正在生成文书，请耐心等候，稍后再尝试下载");
                }else {
                    map.put(record.getTemppath(),record.getFilename());
                }
            }
        }
        return map;
    }
}
