
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.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.excel.util.ExcelUtil;
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.utils.*;
import org.sky.scientific.excel.XmOtherCostExcel;
import org.sky.scientific.mapper.SubjectMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.XmOtherCostMapper;
import org.sky.scientific.pojo.dto.XmOtherCostQuery;
import org.sky.scientific.pojo.entity.Subject;
import org.sky.scientific.pojo.entity.XmOtherCostEntity;
import org.sky.scientific.service.IXmOtherCostService;
import org.sky.scientific.service.IXmService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目-其他费用-基本信息台账 服务实现类
 *
 * @author Kd
 * @since 2025-07-28
 */
@Service
@AllArgsConstructor
public class XmOtherCostServiceImpl extends BaseServiceImpl<XmOtherCostMapper, XmOtherCostEntity> implements IXmOtherCostService {

	private final XmMapper xmMapper;
	private final SubjectMapper subjectMapper;
	private final IXmService xmService;

	@Override
	public IPage<XmOtherCostEntity> selectPageByCondition(IPage<XmOtherCostEntity> page, XmOtherCostQuery param) {
		if (Func.isBlank(param.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		param.setTenantId(SecureUtil.getTenantId());
		List<XmOtherCostEntity> list = null;
		if (param.getYearAndMonth().length() == 4) {
			list = baseMapper.selectXmOtherCostPageByYear(page, param);
		} else if (param.getYearAndMonth().length() == 6) {
			list = baseMapper.selectXmOtherCostPageByYearAndMonth(page, param);
		} else {
			throw new ServiceException("参数yearAndMonth格式错误，yyyyMM或yyyy");
		}
		return page.setRecords(list);
	}

	@Override
	@Transactional
	public void importData(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		List<XmOtherCostExcel> dataList = ExcelUtil.read(file, 0, 2, XmOtherCostExcel.class);
		if (CollectionUtil.isEmpty(dataList)) {
			throw new ServiceException("导入数据为空");
		}

		List<XmOtherCostEntity> insertList = new ArrayList<>();
		for (XmOtherCostExcel data : dataList) {
			XmOtherCostEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(data, XmOtherCostEntity.class));

			if (!Func.equals(yearAndMonth, DateUtil.format(data.getRecordDate(), DateUtil.PATTERN_YYYYMM))) {
				throw new ServiceException("序号[" + data.getXh() + "]的日期[" + DateUtil.format(data.getRecordDate(), DateUtil.PATTERN_YYYY_MM_DD) + "]不属于[" + yearAndMonth + "]");
			}

			if (StringUtil.isBlank(data.getXmbh())) {
				throw new ServiceException("序号[" + data.getXh() + "]的研发项目编号为空，请检查模板数据");
			}

			//根据四级科目查询科目id，且三级科目必须要其他费用，如果不存在则报错
			List<Subject> subjectList = subjectMapper.selectList(Wrappers.<Subject>lambdaQuery().eq(Subject::getAccSubject, data.getSubjectName()));
			if (Func.isEmpty(subjectList)) {
				throw new ServiceException("序号[" + data.getXh() + "]的费用内容[" + data.getSubjectName() + "]没有匹配到会计科目");
			}
			if (subjectList.size() > 1) {
				throw new ServiceException("序号[" + data.getXh() + "]的费用内容[" + data.getSubjectName() + "]匹配到了多个会计科目");
			}
			Long subjectId = subjectList.get(0).getId();

			//根据项目名称或编号查询xmId
			Long xmId = xmMapper.getXmIdByXmmcOrXmbh(null, null, data.getXmbh());
			if (xmId == null) {
				throw new ServiceException("序号[" + data.getXh() + "]的研发项目不存在，请检查模板数据");
			}

			xmService.judgeXmIsOver(xmId, true);

			entity.setXmId(xmId);
			entity.setYearAndMonth(yearAndMonth);
			entity.setSubjectId(subjectId);
			insertList.add(entity);
		}

		this.saveBatch(insertList);
	}

	@Override
	public boolean submit(XmOtherCostEntity entity) {
		if (StringUtil.isBlank(entity.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		if (Func.isNull(entity.getXmId())) {
			throw new ServiceException("参数xmId不能为空");
		}
		xmService.judgeXmIsOver(entity.getXmId(), true);

		String judged = DateUtil.judgeDate(entity.getRecordDate(), entity.getYearAndMonth());
		if (judged != null) {
			throw new ServiceException(judged);
		}
		return this.saveOrUpdate(entity);
	}

	@Override
	@Transactional
	public boolean physicalDeleteByIds(List<Long> ids) {
		for (Long id : ids) {
			XmOtherCostEntity entity = baseMapper.selectById(id);
			if (Func.notNull(entity)) {
				xmService.judgeXmIsOver(entity.getXmId(), true);
			}
		}
		return baseMapper.physicalDeleteByIds(ids);
	}

	@SneakyThrows
	@Override
	public void exportXmOtherCost(OutputStream os, List<XmOtherCostEntity> list, String yearAndMonth) {
		AtomicInteger index = new AtomicInteger(1);
		List<XmOtherCostExcel> results = new ArrayList<>();
		for (XmOtherCostEntity temp : list) {
			XmOtherCostExcel excel = BeanUtil.copyProperties(temp, XmOtherCostExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setRecordDateStr(Func.notNull(temp.getRecordDate()) ? DateUtil.format(temp.getRecordDate(), DateUtil.PATTERN_DATE) : null);
			results.add(excel);
		}
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发费用管理/其他费用/研发费用管理-其他费用.xls");
		ExcelWriter excelWriter = EasyExcel.write(os)
			.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<>();
		map.put("yearAndMonth", yearAndMonth.length() == 6 ? yearAndMonth.substring(0, 4) + "年" + yearAndMonth.substring(4) + "月" : yearAndMonth + "年");
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}
}
