
package org.sky.scientific.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.annotation.Resource;
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.tool.utils.*;
import org.sky.scientific.excel.XmLeaseExcel;
import org.sky.scientific.mapper.XmLeaseMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.XmLeaseEntity;
import org.sky.scientific.service.IXmLeaseService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 研发项目租赁清单 服务实现类
 *
 * @author Kd
 * @since 2025-07-17
 */
@Service
public class XmLeaseServiceImpl extends BaseServiceImpl<XmLeaseMapper, XmLeaseEntity> implements IXmLeaseService {

	@Resource
	private XmMapper xmMapper;

	@Override
	public IPage<XmLeaseEntity> selectXmLeasePage(IPage<XmLeaseEntity> page, XmLeaseEntity dto) {
		if (StringUtil.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		return page.setRecords(baseMapper.selectXmLeasePage(page, dto));
	}


	@Override
	public List<XmLeaseExcel> exportXmLease(Wrapper<XmLeaseEntity> queryWrapper) {
		return baseMapper.exportXmLease(queryWrapper);
	}

	@Override
	public boolean importXmLease(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		List<XmLeaseExcel> data = ExcelUtil.read(file, 0, 2, XmLeaseExcel.class);
		if (CollectionUtil.isEmpty(data)) {
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		List<XmLeaseEntity> insertList = new ArrayList<>();
		for (XmLeaseExcel excel : data) {
			XmLeaseEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(excel, XmLeaseEntity.class));

			//租赁日期，必须时当月日期
			judgeLeaseDate(excel.getLeaseDate(), yearAndMonth);

			if (!StringUtil.isAllBlank(excel.getXmmc(), excel.getXmbh())) {
				//根据项目名称或编号查询xmId
				Long xmId = xmMapper.getXmIdByXmmcOrXmbh(yearAndMonth, excel.getXmmc(), excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("研发项目[" + (StringUtil.isNotBlank(excel.getXmmc()) ? excel.getXmmc() + "," : "") + (StringUtil.isNotBlank(excel.getXmbh()) ? excel.getXmbh() : "") + "]不存在，请检查模板数据");
				}
				entity.setXmId(xmId);
			}

			entity.setYearAndMonth(yearAndMonth);
			insertList.add(entity);
		}
		return this.saveBatch(insertList);
	}

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

	@Override
	public boolean submit(XmLeaseEntity xmLease) {
		if (StringUtil.isBlank(xmLease.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		judgeLeaseDate(xmLease.getLeaseDate(), xmLease.getYearAndMonth());
		return this.saveOrUpdate(xmLease);
	}

    @Override
    public List<JSONObject> yanfazulinzichanfeiyongfenpeibiao(XmLeaseEntity dto) {
		if(Func.isBlank(dto.getYearAndMonth())){
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		List<XmLeaseEntity> list = baseMapper.yanfazulinzichanfeiyongfenpeibiao(dto);

		List<JSONObject> result = new ArrayList<>();
		if(CollectionUtil.isEmpty(list)){
			return result;
		}
		Map<Long, List<XmLeaseEntity>> mapByXmId = list.stream().collect(Collectors.groupingBy(XmLeaseEntity::getXmId));
		for (Long xmId : mapByXmId.keySet()) {
			List<XmLeaseEntity> listByXmId = mapByXmId.get(xmId);

			for (XmLeaseEntity vo : listByXmId) {
				String key = xmId+":"+ DateUtil.format(vo.getLeaseDate(), DateUtil.PATTERN_DATE);

				if(result.isEmpty()){
					ArrayList<XmLeaseEntity> vos = new ArrayList<>();
					vos.add(vo);
					JSONObject o = new JSONObject();
					o.put(key, vos);
					result.add(o);
				}else {
					for (JSONObject o : result) {
						List<XmLeaseEntity> voList= null;
						if(o.containsKey(key)){
							voList= o.getJSONArray(key).toJavaList(XmLeaseEntity.class);
						}else {
							voList = new ArrayList<>();
						}
						voList.add(vo);
						o.put(key, voList);
					}
				}
			}
		}
		return result;
    }

    private void judgeLeaseDate(Date date, String yearAndMonth) {
		//日期，必须时当月日期
		if (date != null) {
			String format = DateUtil.format(date, DateUtil.PATTERN_YYYYMM);
			boolean equals = StringUtil.equals(format, yearAndMonth);
			if (!equals) {
				throw new ServiceException("租赁日期" + format + "必须是" + yearAndMonth + "月的一天");
			}
		}
	}

}
