
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 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.XmDesignCostExcel;
import org.sky.scientific.mapper.XmDesignCostMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.XmDesignCostQuery;
import org.sky.scientific.pojo.entity.XmDesignCostEntity;
import org.sky.scientific.pojo.vo.XmDesignCostVO;
import org.sky.scientific.service.IXmDesignCostService;
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 XmDesignCostServiceImpl extends BaseServiceImpl<XmDesignCostMapper, XmDesignCostEntity> implements IXmDesignCostService {

	private final XmMapper xmMapper;
	private final IXmService xmService;

	@Override
	public IPage<XmDesignCostVO> selectXmDesignCostPage(IPage<XmDesignCostVO> page, XmDesignCostQuery param) {
		if (Func.isBlank(param.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		param.setTenantId(SecureUtil.getTenantId());
		List<XmDesignCostVO> list = null;
		if (param.getYearAndMonth().length() == 4) {
			list = baseMapper.selectXmDesignCostPageByYear(page, param);
		} else if (param.getYearAndMonth().length() == 6) {
			list = baseMapper.selectXmDesignCostPageByYearAndMonth(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<XmDesignCostExcel> dataList = ExcelUtil.read(file, 0, 2, XmDesignCostExcel.class);
		if (CollectionUtil.isEmpty(dataList)) {
			throw new ServiceException("导入数据为空");
		}

		List<XmDesignCostEntity> insertList = new ArrayList<>();
		for (XmDesignCostExcel data : dataList) {

			String judged = DateUtil.judgeDate(data.getRecordDate(), yearAndMonth);
			if (judged != null) {
				throw new ServiceException(judged);
			}

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

			xmService.judgeXmIsOver(xmId, DateUtil.format(data.getRecordDate(), DateUtil.PATTERN_YYYYMMDD),true);

			XmDesignCostEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(data, XmDesignCostEntity.class));
			entity.setXmId(xmId);
			entity.setYearAndMonth(yearAndMonth);

			insertList.add(entity);
		}

		this.saveBatch(insertList);
	}

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

	@SneakyThrows
	@Override
	public void exportXmDesignCost(OutputStream os, List<XmDesignCostVO> list, String yearAndMonth) {
		AtomicInteger index = new AtomicInteger(1);
		list.forEach(temp -> {
			temp.setXh(index.getAndIncrement() + "");
			temp.setRecordDateStr(Func.notNull(temp.getRecordDate()) ? DateUtil.format(temp.getRecordDate(), DateUtil.PATTERN_DATE) : null);

		});
		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(list, 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();
		}
	}

	@Override
	public boolean submit(XmDesignCostEntity xmDesignCost) {
		String judged = DateUtil.judgeDate(xmDesignCost.getRecordDate(), xmDesignCost.getYearAndMonth());
		if (judged != null) {
			throw new ServiceException(judged);
		}
		xmService.judgeXmIsOver(xmDesignCost.getXmId(), DateUtil.format(xmDesignCost.getRecordDate(), DateUtil.PATTERN_YYYYMMDD),true);
		return this.saveOrUpdate(xmDesignCost);
	}

}
