
package org.sky.scientific.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.mapper.YfzdMapper;
import org.sky.scientific.pojo.entity.YfzdEntity;
import org.sky.scientific.service.IYfzdService;
import org.sky.scientific.utils.ZipDownloadUtils;
import org.sky.scientific.utils.ZipFileRef;
import org.sky.scientific.utils.ZipDir;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.Deflater;

/**
 * 研发制度 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
@AllArgsConstructor
public class YfzdServiceImpl extends BaseServiceImpl<YfzdMapper, YfzdEntity> implements IYfzdService {

	@Override
	public boolean editYfzd(YfzdEntity yfzd) {
		return this.saveOrUpdate(yfzd);
	}

	@Override
	public Map<String, List<YfzdEntity>> selectYfzd(YfzdEntity yfzd) {
		if (StringUtil.isBlank(yfzd.getYearAndMonth())) {
			throw new ServiceException("请选择年份");
		}
		List<String> wjlxTypeList = baseMapper.selectWJLXType();
		LambdaQueryWrapper<YfzdEntity> queryWrapper = Wrappers.<YfzdEntity>lambdaQuery().eq(YfzdEntity::getYearAndMonth, yfzd.getYearAndMonth());
		List<YfzdEntity> yfzdList = baseMapper.selectList(queryWrapper);
		Map<String, List<YfzdEntity>> collected = yfzdList.stream().collect(Collectors.groupingBy(YfzdEntity::getWjlx));
		if (collected.isEmpty()) {
			collected = new HashMap<>();
		}
		for (String wjlxType : wjlxTypeList) {
			if (!collected.keySet().contains(wjlxType)) {
				collected.put(wjlxType, new ArrayList<YfzdEntity>());
			}
		}
		return collected;
	}

	@Override
	public boolean physicalDeleteByIds(List<Long> ids) {
		return baseMapper.physicalDeleteByIds(ids);
	}

	@Override
	public void downloadZipFiles(HttpServletRequest request, HttpServletResponse response, String year) {
		List<ZipDir> data = new ArrayList<>();

		YfzdEntity yfzd = new YfzdEntity();
		yfzd.setYearAndMonth(year);
		Map<String, List<YfzdEntity>> map = selectYfzd(yfzd);
		for (String type : map.keySet()) {
			ZipDir group = new ZipDir();
			group.setDirName(type);

			List<YfzdEntity> list = map.get(type);
			//企业制度
			ZipDir qiyezhiduDir = new ZipDir();
			qiyezhiduDir.setDirName("企业制度");
			qiyezhiduDir.setFileRefs(new ArrayList<>());
			//实施证明
			ZipDir shishizhengmDir = new ZipDir();
			shishizhengmDir.setDirName("企业制度实施证明");
			shishizhengmDir.setFileRefs(new ArrayList<>());

			for (YfzdEntity entity : list) {
				List<JSONObject> zdwjdz = JSON.parseArray(entity.getZdwjdz(), JSONObject.class);
				for (JSONObject obj : zdwjdz) {
					ZipFileRef ref = new ZipFileRef();
					ref.setName(obj.getString("label"));
					ref.setHttpUrl(obj.getString("value"));
					qiyezhiduDir.getFileRefs().add(ref);
				}

				List<JSONObject> zdszm = JSON.parseArray(entity.getZdsszm(), JSONObject.class);
				for (JSONObject obj : zdszm) {
					ZipFileRef ref = new ZipFileRef();
					ref.setName(obj.getString("label"));
					ref.setHttpUrl(obj.getString("value"));
					shishizhengmDir.getFileRefs().add(ref);
				}
			}
			group.setSubDirs(Arrays.asList(qiyezhiduDir, shishizhengmDir));
			data.add(group);
		}

		try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(bos)) {
			String fileName = year + "年研发制度" + ".zip";
			ZipDownloadUtils.setResponse(request, response, fileName);
			// 快速压缩
			zipOut.setLevel(Deflater.BEST_SPEED);
			for (ZipDir group : data) {
				String groupDir = ZipDownloadUtils.safeName(group.getDirName()) + "/";
				List<ZipDir> subDirs = group.getSubDirs();
				if (subDirs == null || subDirs.isEmpty()) {
					ZipDownloadUtils.writeEmptyDirToZip(zipOut, groupDir);
					continue;
				}
				for (ZipDir subDir : subDirs) {
					String subDirPath = groupDir + ZipDownloadUtils.safeName(subDir.getDirName()) + "/";
					List<ZipFileRef> fileRefs = subDir.getFileRefs();
					if (fileRefs == null || fileRefs.isEmpty()) {
						ZipDownloadUtils.writeEmptyDirToZip(zipOut, subDirPath);
						continue;
					}
					for (ZipFileRef fileRef : fileRefs) {
						if (fileRef.getLocalPath() != null && !fileRef.getLocalPath().isEmpty()) {
							ZipDownloadUtils.writeLocalFileToZip(zipOut, fileRef.getLocalPath(), subDirPath + ZipDownloadUtils.safeName(fileRef.getName()));
						} else if (fileRef.getHttpUrl() != null && !fileRef.getHttpUrl().isEmpty()) {
							ZipDownloadUtils.writeHttpFileToZip(zipOut, fileRef.getHttpUrl(), subDirPath + ZipDownloadUtils.safeName(fileRef.getName()));
						}
					}
				}
			}
			zipOut.finish();
			zipOut.flush();
			response.flushBuffer();
		} catch (Exception e) {
			throw new RuntimeException("打包下载失败", e);
		}
	}

}
