
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.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.secure.utils.SecureUtil;
import org.sky.core.tool.api.R;
import org.sky.core.tool.utils.Charsets;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.mapper.DepartmentMapper;
import org.sky.scientific.mapper.TechnicianMapper;
import org.sky.scientific.mapper.XmJdxbgMapper;
import org.sky.scientific.pojo.entity.XmEntity;
import org.sky.scientific.pojo.entity.XmJdxbgEntity;
import org.sky.scientific.pojo.vo.XmJdxbgVO;
import org.sky.scientific.service.IXmJdxbgService;
import org.sky.scientific.utils.TemplateService;
import org.sky.system.cache.DictCache;
import org.sky.system.feign.ISysClient;
import org.sky.system.pojo.entity.Tenant;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 科研项目-项目实施-阶段性报告 服务实现类
 *
 * @author Kd
 * @since 2025-07-01
 */
@Service
@AllArgsConstructor
public class XmJdxbgServiceImpl extends BaseServiceImpl<XmJdxbgMapper, XmJdxbgEntity> implements IXmJdxbgService {

	private final TechnicianMapper technicianMapper;
	private final DepartmentMapper departmentMapper;
	private final TemplateService templateService;
	private final ISysClient sysClient;

	@Override
	public IPage<XmJdxbgVO> selectByCondition(IPage<XmJdxbgVO> page, XmJdxbgEntity entity) {
		entity.setTenantId(SecureUtil.getTenantId());
		List<XmJdxbgVO> list = baseMapper.selectByCondition(page, entity);
		for (XmJdxbgVO vo : list) {
			vo.getXmEntity().setXmsqdw(departmentMapper.getFullNameById(vo.getXmEntity().getXmsqdwid()));
		}
		return page.setRecords(list);
	}

	@Override
	public boolean submit(XmJdxbgEntity xmJdxbg) {
		if (xmJdxbg.getXmId() == null) {
			throw new ServiceException("请选择科研项目");
		}
		return this.saveOrUpdate(xmJdxbg);
	}

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

	@Override
	public XmJdxbgVO selectById(Long id) {

		XmJdxbgVO vo = baseMapper.selectByPrimaryKey(id);
		vo.getXmEntity().setXmfzrxm(technicianMapper.getNameById(vo.getXmEntity().getXmfzr()));
		vo.getXmEntity().setXmsqdw(departmentMapper.getFullNameById(vo.getXmEntity().getXmsqdwid()));
		return vo;
	}

	@SneakyThrows
	@Override
	public void exportXmJdxbg(HttpServletResponse response, XmJdxbgVO dto) {

		XmJdxbgEntity xmEntity = new XmJdxbgEntity();
		xmEntity.setXmId(dto.getXmId());
		xmEntity.setTenantId(SecureUtil.getTenantId());
		List<XmJdxbgVO> list = this.selectByCondition(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), xmEntity).getRecords();
		AtomicInteger index = new AtomicInteger(1);

		List<JSONObject> results = new ArrayList<>();
		list.forEach(temp -> {
			JSONObject obj = new JSONObject();
			obj.put("xh", index.getAndIncrement() + "");
			obj.put("xmbh", temp.getXmEntity().getXmbh());
			obj.put("xmmc", temp.getXmEntity().getXmmc());
			obj.put("typeStr", DictCache.getValue("项目实施-阶段性报告-附件类型", temp.getType()));
			obj.put("xmsqdw", temp.getXmEntity().getXmsqdw());
			obj.put("xmfzrxm", temp.getXmEntity().getXmfzrxm());
			obj.put("fillDateStr", DateUtil.format(temp.getFillDate(), DateUtil.PATTERN_DATE));
			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 exportXmJdxbgDoc(FileOutputStream outputStream, XmJdxbgVO vo) {

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

		XmEntity xm = vo.getXmEntity();
		map.put("xmmc", xm.getXmmc());
		map.put("xmfzrxm", Func.notNull(xm.getXmfzrxm())?xm.getXmfzrxm(): "");
		map.put("xmsqdw", Func.notNull(xm.getXmsqdw())?xm.getXmsqdw(): "");
		map.put("xmkssjStr", DateUtil.format(xm.getXmkssj(), "yyyy年MM月dd日"));
		map.put("xmjssjStr", DateUtil.format(xm.getXmjssj(), "yyyy年MM月dd日"));
		map.put("fillDateStr", DateUtil.format(vo.getFillDate(), "yyyy年MM月dd日"));
		map.put("yjlx", Func.notNull(xm.getYjlx())?xm.getYjlx(): "");
		map.put("xmly", Func.notNull(xm.getXmly())?xm.getXmly(): "");
		map.put("xmkzxs", Func.notNull(xm.getXmkzxs())?xm.getXmkzxs(): "");
		map.put("yqcgxs", Func.notNull(xm.getYqcgxs())?xm.getYqcgxs(): "");
		map.put("xmjsjjmb", Func.notNull(xm.getXmjsjjmb())?xm.getXmjsjjmb(): "");
		map.put("typeStr", DictCache.getValue("项目实施-阶段性报告-附件类型", vo.getType()));

		R<Tenant> tenant = sysClient.getTenant(SecureUtil.getTenantId());
		map.put("enterpriseName", "");
		if (tenant.isSuccess()) {
			map.put("enterpriseName", tenant.getData().getTenantName());
		}

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

}
