
package org.sky.scientific.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.mp.support.Condition;
import org.sky.core.mp.support.Query;
import org.sky.core.tool.utils.Charsets;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.e.XmStatusEnum;
import org.sky.scientific.mapper.DepartmentMapper;
import org.sky.scientific.mapper.TechnicianMapper;
import org.sky.scientific.mapper.XmBgrzMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.XmBgrzEntity;
import org.sky.scientific.pojo.vo.XmBgrzVO;
import org.sky.scientific.service.IXmBgrzService;
import org.sky.scientific.service.IXmService;
import org.sky.scientific.utils.TemplateService;
import org.sky.system.cache.DictCache;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目-变更记录 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
@AllArgsConstructor
public class XmBgrzServiceImpl extends BaseServiceImpl<XmBgrzMapper, XmBgrzEntity> implements IXmBgrzService {

	private final DepartmentMapper departmentMapper;
	private final TechnicianMapper technicianMapper;
	private final TemplateService templateService;
	private final IXmService xmService;
	private final XmMapper xmMapper;

	@Override
	public boolean saveBgrz(XmBgrzEntity xmBgrz) {
		if (xmBgrz.getXmId() == null) {
			throw new ServiceException("请选择需要变更的项目");
		}
		JSONObject byXmId = xmMapper.getXmStatusByXmId(xmBgrz.getXmId());
		Integer status = byXmId.getInteger("status");
		if (Func.equals(status, XmStatusEnum.已结题.getCode())) {
			throw new ServiceException("项目已结题，不可操作");
		}
		xmBgrz.setBghdz(StringUtil.trimAllWhitespace(xmBgrz.getBghdz()));
		return this.save(xmBgrz);
	}

	@Override
	public IPage<XmBgrzVO> selectBgrzPage(XmBgrzEntity xmBgrz, IPage<XmBgrzVO> page) {
		List<XmBgrzVO> voList = baseMapper.selectBgrzPage(page, xmBgrz);
		for (XmBgrzVO vo : voList) {
			if ("XMSQDWID".equalsIgnoreCase(vo.getZdmc())) {
				// 项目申请单位
				vo.setBgqdz(departmentMapper.getFullNameById(Long.parseLong(vo.getBgqdz())));
				vo.setBgqdzStr(vo.getBgqdz());
				vo.setBghdz(departmentMapper.getFullNameById(Long.parseLong(vo.getBghdz())));
				vo.setBghdzStr(vo.getBghdz());
			} else if ("XMFZR".equalsIgnoreCase(vo.getZdmc())) {
				vo.setBgqdz(technicianMapper.getNameById(Long.parseLong(vo.getBgqdz())));
				vo.setBgqdzStr(vo.getBgqdz());
				vo.setBghdz(technicianMapper.getNameById(Long.parseLong(vo.getBghdz())));
				vo.setBghdzStr(vo.getBghdz());
			} else if ("STATUS".equalsIgnoreCase(vo.getZdmc())) {
				vo.setBgqdz(vo.getBgqdz());
				vo.setBgqdzStr(DictCache.getValue("project_state", vo.getBgqdz()));
				vo.setBghdz(vo.getBghdz());
				vo.setBghdzStr(DictCache.getValue("project_state", vo.getBghdz()));
			} else if ("XMYSZEMX".equalsIgnoreCase(vo.getZdmc())) {
				if (Func.isNotBlank(vo.getBgqdz())) {
					List<JSONObject> arr = JSON.parseArray(vo.getBgqdz(), JSONObject.class);
					List<String> desc = new ArrayList<>();
					for (JSONObject tmp : arr) {
						String year = tmp.getString("year");
						String amount = tmp.getString("amount");
						desc.add(year + "年，" + amount + "万元");
					}
					vo.setBgqdzStr(String.join(";", desc));
				}
				if (Func.isNotBlank(vo.getBghdz())) {
					List<JSONObject> arr = JSON.parseArray(vo.getBghdz(), JSONObject.class);
					List<String> desc = new ArrayList<>();
					for (JSONObject tmp : arr) {
						String year = tmp.getString("year");
						String amount = tmp.getString("amount");
						desc.add(year + "年，" + amount + "万元");
					}
					vo.setBghdzStr(String.join(";", desc));
				}
			} else {
				vo.setBgqdzStr(vo.getBgqdz());
				vo.setBghdzStr(vo.getBghdz());
			}
			vo.setZdmcStr(DictCache.getValue("xm_biangeng_field", vo.getZdmc()));
		}
		return page.setRecords(voList);
	}

	@SneakyThrows
	@Override
	public void exportXmBgrz(HttpServletResponse response, XmBgrzEntity dto) {
		List<XmBgrzVO> list = this.selectBgrzPage(dto, Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE))).getRecords();
		AtomicInteger index = new AtomicInteger(1);

		List<JSONObject> results = new ArrayList<>();
		for (XmBgrzVO temp : list) {
			JSONObject obj = new JSONObject();
			obj.put("xh", index.getAndIncrement() + "");
			obj.put("xmbh", temp.getXmbh());
			obj.put("xmmc", temp.getXmmc());
			obj.put("zdmcStr", DictCache.getValue("xm_biangeng_field", temp.getZdmc()));
			obj.put("xmsqdw", temp.getXmsqdw());
			obj.put("bgqdzStr", temp.getBgqdzStr());
			obj.put("bghdzStr", temp.getBghdzStr());
			obj.put("bgsxsjStr", DateUtil.format(temp.getBgsxsj(), DateUtil.PATTERN_YYYY_MM_DD));
			results.add(obj);
		}

		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发项目管理/项目变更.xls");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("项目预算-项目变更.xls", Charsets.UTF_8));
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLS)
			.build();

		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		excelWriter.fill(results, fillConfig, writeSheet);
		Map<String, Object> map = new HashMap<>();

		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@SneakyThrows
	@Override
	public void exportXmBgrzDoc(FileOutputStream outputStream, XmBgrzVO vo) {

		// 定义输出类型
		JSONObject map = new JSONObject();

		map.put("xmmc", vo.getXmmc());
		map.put("xmbh", vo.getXmbh());
		map.put("xmfzrxm", Func.notNull(vo.getXmfzrxm()) ? vo.getXmfzrxm() : "");
		map.put("xmsqdw", Func.notNull(vo.getXmsqdw()) ? vo.getXmsqdw() : "");
		map.put("zdmcStr", Func.notNull(vo.getZdmcStr()) ? vo.getZdmcStr() : "");
		map.put("bgqdz", Func.notNull(vo.getBgqdzStr()) ? vo.getBgqdzStr() : "");
		map.put("bghdz", Func.notNull(vo.getBghdzStr()) ? vo.getBghdzStr() : "");
		map.put("bgsxsjStr", DateUtil.format(vo.getBgsxsj(), "yyyy年MM月dd日"));
		map.put("bgyy", Func.notNull(vo.getBgyy()) ? vo.getBgyy() : "");

		templateService.processTemplate("项目变更表.ftl", map, new OutputStreamWriter(outputStream));
	}

}
