
package org.sky.scientific.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.secure.utils.SecureUtil;
import org.sky.core.tool.api.R;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.e.XmStatusEnum;
import org.sky.scientific.mapper.*;
import org.sky.scientific.pojo.dto.XmJtbDTO;
import org.sky.scientific.pojo.entity.XmBgrzEntity;
import org.sky.scientific.pojo.entity.XmEntity;
import org.sky.scientific.pojo.entity.XmJtbEntity;
import org.sky.scientific.pojo.vo.XmJtbVO;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.service.IXmJtbService;
import org.sky.scientific.utils.TemplateService;
import org.sky.system.feign.ISysClient;
import org.sky.system.pojo.entity.Tenant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Objects;

/**
 * 科研项目-项目结题表 服务实现类
 *
 * @author Kd
 * @since 2025-07-01
 */
@Service
@AllArgsConstructor
public class XmJtbServiceImpl extends BaseServiceImpl<XmJtbMapper, XmJtbEntity> implements IXmJtbService {

	private final TechnicianMapper technicianMapper;
	private final DepartmentMapper departmentMapper;
	private final TemplateService templateService;
	private final XmMapper xmMapper;
	private final XmBgrzMapper xmBgrzMapper;
	private final ISysClient sysClient;

	@Override
	public XmJtbVO selectByCondition(XmJtbDTO xmJtb) {
		if (Objects.isNull(xmJtb.getXmId())) {
			throw new ServiceException("请选择研发项目");
		}
		XmJtbVO vo = baseMapper.selectByCondition(xmJtb);
		if (!Func.isNull(vo)) {
			vo.getXmEntity().setXmfzrxm(technicianMapper.getNameById(vo.getXmEntity().getXmfzr()));
			vo.getXmEntity().setXmsqdw(departmentMapper.getFullNameById(vo.getXmEntity().getXmsqdwid()));
		}
		return vo;
	}

	@Override
	@Transactional
	public boolean submit(XmJtbEntity xmJtb) {
		if (Objects.isNull(xmJtb.getXmId())) {
			throw new ServiceException("请选择科研项目");
		}

		XmVO xmVO = xmMapper.selectByXmId(xmJtb.getXmId());
		if (Func.isNull(xmVO)) {
			throw new ServiceException("研发项目不存在");
		}

		if (!Func.equals(xmJtb.getStatus(), XmStatusEnum.暂存.getCode())) {
			if (Func.notNull(xmJtb.getTbsj()) && !cn.hutool.core.date.DateUtil.isSameDay(xmVO.getXmjssj(), xmJtb.getTbsj())) {
				throw new ServiceException("填报时间与项目结束时间不一致");
			}
		}

		if (xmJtb.getStatus() == XmStatusEnum.已结题.getCode()) {
			//往变更表插入一条项目状态变更为 已结题的 变更记录
			LambdaQueryWrapper<XmBgrzEntity> queryWrapper = Wrappers.<XmBgrzEntity>lambdaQuery()
				.eq(XmBgrzEntity::getXmId, xmJtb.getXmId())
				.eq(XmBgrzEntity::getZdmc, "STATUS")
				.eq(XmBgrzEntity::getBghdz, XmStatusEnum.已结题.getCode());
			if (xmBgrzMapper.selectCount(queryWrapper) > 0) {
				xmBgrzMapper.deleteBgrzByJtb(xmJtb.getXmId());
			}
			XmBgrzEntity bgrz = new XmBgrzEntity();
			bgrz.setXmId(xmJtb.getXmId());
			bgrz.setZdmc("STATUS");
			bgrz.setBghdz(String.valueOf(XmStatusEnum.已结题.getCode()));
			bgrz.setBgyy("项目结题");
			bgrz.setBgsxsj(xmJtb.getTbsj());
			bgrz.setTenantId(SecureUtil.getTenantId());
			xmBgrzMapper.insert(bgrz);

			XmEntity xmEntity = new XmEntity();
			xmEntity.setId(xmJtb.getXmId());
			xmEntity.setStatus(XmStatusEnum.已结题.getCode());
			xmMapper.updateById(xmEntity);
		} else {
			XmEntity xmEntity = new XmEntity();
			xmEntity.setId(xmJtb.getXmId());
			xmEntity.setStatus(XmStatusEnum.开展中.getCode());
			xmMapper.updateById(xmEntity);
			xmBgrzMapper.deleteBgrzByJtb(xmJtb.getXmId());
		}
		xmJtb.setId(null);
		boolean result = false;
		if (this.isFieldDuplicate(XmJtbEntity::getXmId, xmJtb.getXmId())) {
			result = this.update(xmJtb, Wrappers.<XmJtbEntity>lambdaUpdate().eq(XmJtbEntity::getXmId, xmJtb.getXmId()));
		} else {
			result = this.save(xmJtb);
		}
		return result;
	}

	@SneakyThrows
	@Override
	public void exportXmJtbDoc(FileOutputStream outputStream, XmJtbVO 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("kssjStr", DateUtil.format(xm.getXmkssj(), "yyyy年MM月dd日"));
		map.put("jssjStr", DateUtil.format(xm.getXmjssj(), "yyyy年MM月dd日"));
		map.put("tbsjStr", DateUtil.format(vo.getTbsj(), "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("xmysze", Func.notNull(xm.getXmysze()) ? xm.getXmysze() : "");

		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));
	}

}
