package com.hotent.project.manager.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.project.dao.CostProjectApprovalDao;
import com.hotent.project.dao.CostProjectMemoDao;
import com.hotent.project.manager.CostNoticeManager;
import com.hotent.project.manager.CostProjectApprovalManager;
import com.hotent.project.manager.CostProjectMemoManager;
import com.hotent.project.model.CostNotice;
import com.hotent.project.model.CostProjectApproval;
import com.hotent.project.model.CostProjectMemo;
import com.hotent.project.req.CostProjectMemoQueryReq;
import com.hotent.project.req.CostProjectMemoUpdateReq;
import com.hotent.project.resp.CostProjectMemoDetailResp;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import com.hotent.util.CopyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * 监审项目备忘录表 服务实现类
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-25
 */
@Service
public class CostProjectMemoManagerImpl extends BaseManagerImpl<CostProjectMemoDao, CostProjectMemo> implements CostProjectMemoManager {

	@Autowired
	private CostProjectMemoDao costProjectMemoDao;
	@Resource
	private CostProjectApprovalDao costProjectApprovalDao;

	@Autowired
	private UserManager userService;

	@Autowired
	private CostProjectApprovalManager projectApprovalManager;

	@Autowired
	private CostNoticeManager costNoticeManager;

	@Override
	public CostProjectMemoDetailResp getDetail(String id) {

    	CostProjectMemo costProjectMemo = this.get(id);
		CostProjectMemoDetailResp costProjectMemoDetailResp = CopyUtil.copy(costProjectMemo, CostProjectMemoDetailResp.class);
		//获取成本项目
		CostProjectApproval  CostProjectApproval = costProjectApprovalDao.selectById(costProjectMemo.getProjectId());
		if ( CostProjectApproval != null){
			costProjectMemoDetailResp.setTask( CostProjectApproval.getProjectName());
		}else {
			costProjectMemoDetailResp.setTask("");
		}

		return costProjectMemoDetailResp;
	}
	@Override
	@Transactional
	public void createOrUpdate(CostProjectMemo costProjectMemo) {
		//更新
		this.saveOrUpdate(costProjectMemo);
	}

@Override
	public IPage<CostProjectMemo> pageList(CostProjectMemoQueryReq req){
		// 检查pageNum和pageSize是否合理
		/*if (req.getPageNum() <= 0 || req.getPageSize() <= 0) {
			throw new IllegalArgumentException("pageNum和pageSize必须大于0");
		}*/

		/*LambdaQueryWrapper<CostProjectMemo> qw = new LambdaQueryWrapper<>();
		if (req.getProjectId() != null) {
			qw.eq(CostProjectMemo::getProjectId, req.getProjectId());
		}
		if (req.getStartTime() != null && req.getEndTime() != null) {
			qw.between(CostProjectMemo::getCreateTime, req.getStartTime(), req.getEndTime());
		}
		if (StringUtil.isNotEmpty(req.getContent())) {
			qw.like(CostProjectMemo::getContent, req.getContent());
		}

		if(ObjectUtil.isNotEmpty(req.getYear())){
			qw.like(CostProjectMemo::getCreateTime, req.getYear());
		}
		qw.orderByDesc(CostProjectMemo::getId);*/

		// 使用MyBatis Plus分页查询
		/*Page<CostProjectMemo> page = new Page<>(req.getPageNum(), req.getPageSize());
		IPage<CostProjectMemo> costProjectMemoIPage = this.page(page, qw);

		// 查询年度计划项目名称
		List<CostProjectMemo> costProjectMemos = costProjectMemoIPage.getRecords();
		List<String> planNameIds = costProjectMemos.stream()
				.map(CostProjectMemo::getProjectId)
				.filter(java.util.Objects::nonNull)
				.distinct()
				.collect(Collectors.toList());

		Map<String,  CostProjectApproval> planNameMap;
		if (!planNameIds.isEmpty()) {
			LambdaQueryWrapper< CostProjectApproval> qwPlan = new LambdaQueryWrapper<>();
			qwPlan.in( CostProjectApproval::getProjectId, planNameIds);
			List< CostProjectApproval> planNameList = costProjectApprovalDao.selectList(qwPlan);
			planNameMap = planNameList.stream()
					.collect(Collectors.toMap(
							 CostProjectApproval::getProjectId,
							Function.identity(),
							(existing, replacement) -> existing
					));
		} else {
            planNameMap = new HashMap<>();
        }

    // 转换为响应对象
		List<CostProjectMemoQueryResp> costProjectMemoQueryResps = costProjectMemos.stream().map(item -> {
			CostProjectMemoQueryResp resp = CopyUtil.copy(item, CostProjectMemoQueryResp.class);
			resp.setId(item.getId());
			 CostProjectApproval planName = planNameMap.get(String.valueOf(item.getProjectId()));
			if (planName != null) {
				resp.setProjectName(planName.getProjectName());
			} else {
				resp.setProjectName("");
			}
			return resp;
		}).collect(Collectors.toList());

		// 构造返回的分页对象
		Page<CostProjectMemoQueryResp> respPage = new Page<>(req.getPageNum(), req.getPageSize(), costProjectMemoIPage.getTotal());
		respPage.setRecords(costProjectMemoQueryResps);*/

		//return respPage;



	IUser iUser = ContextUtil.getCurrentUser();
	User user = null;
	try {
		user = userService.getByAccount(iUser.getAccount());
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	req.setDataScope(user.getDataScope());
	req.setProvinceCode(user.getProvinceCode());
	req.setCityCode(user.getCityCode());
	req.setCountyCode(user.getCountyCode());
	Page<CostProjectMemo> objectPage = new Page<>(req.getPageNum(),req.getPageSize());
	//Page<CostSurveyTemplate> page =baseMapper.getCostSurveyTemplatePage(objectPage,params);
	Page<CostProjectMemo> page =baseMapper.getCostProjectMemoPage(objectPage
			,req.getDataScope()
			,req.getProvinceCode()
			,req.getCityCode()
			,req.getCountyCode()
			,req.getProjectId()
			,req.getYear()
			,req.getContent()
			,req.getMemoDate()
			,req.getStartTime()
			,req.getEndTime());
	return page;
	}

	@Override
	public int updateMemo(CostProjectMemoUpdateReq req) {

		if (req.getId() == null){
			throw new IllegalArgumentException("id不能为空");
		}
		if (req.getProjectId() == null){
			throw new IllegalArgumentException("项目id不能为空");
		}

		CostProjectMemo copy = CopyUtil.copy(req, CostProjectMemo.class);
		costProjectMemoDao.updateMemo(copy);
		return 0;
	}

    @Override
    public Boolean saveData(CostProjectMemo t) {
		boolean save = this.save(t);
		if (save){
			String projectId = t.getProjectId();
			CostProjectApproval projectApproval = projectApprovalManager.getById(projectId);
			if (projectApproval != null) {
				Map<String,String> rMap = new HashMap<>();
				List<CostNotice> noticeList = new ArrayList<>();
				String leaderId = projectApproval.getLeaderId();
				if(StringUtils.isNotBlank(leaderId)){
					CostNotice costNotice = new CostNotice();
					costNotice.setNoticeTitle(t.getTitle());
					costNotice.setProjectId(t.getProjectId());
					costNotice.setStatus("0");
					costNotice.setNoticeType("1");
					costNotice.setNoticeContent(t.getContent());
					costNotice.setEnterpriseId(projectApproval.getAuditedUnitId());
					costNotice.setNoticeSource("备忘录");
					costNotice.setSendTarget(leaderId);
					noticeList.add(costNotice);
					rMap.put(costNotice.getSendTarget(),"");
				}
				String auditGroup = projectApproval.getAuditGroup();
				if(StringUtils.isNotBlank(auditGroup)){
					String[] split = auditGroup.split(",");
					for (String s : split) {
						if(rMap.containsKey(s)){
							continue;
						}
						CostNotice costNotice = new CostNotice();
						costNotice.setNoticeTitle(t.getTitle());
						costNotice.setProjectId(t.getProjectId());
						costNotice.setStatus("0");
						costNotice.setNoticeType("1");
						costNotice.setNoticeContent(t.getContent());
						costNotice.setEnterpriseId(projectApproval.getAuditedUnitId());
						costNotice.setNoticeSource("备忘录");
						costNotice.setSendTarget(s);
						noticeList.add(costNotice);
					}
				}
				costNoticeManager.saveBatch(noticeList);
			}
		}
		return true;
    }

	@Override
	public IPage<CostProjectMemo> pageIndexList(CostProjectMemoQueryReq req) {
		IUser iUser = ContextUtil.getCurrentUser();
		String userId = iUser.getUserId();
		Page<CostProjectMemo> objectPage = new Page<>(req.getPageNum(),req.getPageSize());
		Page<CostProjectMemo> page =baseMapper.getIndexList(objectPage,userId,req.getContent(),req.getMemoDate());
		return page;
	}

    @Override
    public Map<String, List<CostProjectMemo>> getDataMonth(String month) {
		// 获取本月的所有项目，装到Map，key为日期，value为项目
		IUser iUser = ContextUtil.getCurrentUser();
		User user = null;
		try {
			user = userService.getByAccount(iUser.getAccount());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		List<CostProjectMemo> costProjectMemos = baseMapper.getDataMonth(user.getDataScope()
				,user.getProvinceCode()
				,user.getCityCode()
				,user.getCountyCode()
				,month);
		Map<String, List<CostProjectMemo>> planNameMap = new HashMap<>();
		if (costProjectMemos != null && costProjectMemos.size() > 0) {
			//填充到planNameMap中,key为日期，value为项目、
			for (CostProjectMemo costProjectMemo : costProjectMemos) {
				CostProjectApproval  CostProjectApproval = costProjectApprovalDao.selectById(costProjectMemo.getProjectId());
				if ( CostProjectApproval != null){
					costProjectMemo.setTask( CostProjectApproval.getProjectName());
				}else {
					costProjectMemo.setTask("");
				}
				if(planNameMap.containsKey(costProjectMemo.getMemoDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))){
					planNameMap.get(costProjectMemo.getMemoDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).add(costProjectMemo);
				}else{
					List<CostProjectMemo> list = new ArrayList<>();
					list.add(costProjectMemo);
					planNameMap.put(costProjectMemo.getMemoDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),list);
				}
			}
		}
		// 再为map排下序，按日期
		Map<String, List<CostProjectMemo>> sortedPlanNameMap = new TreeMap<>(planNameMap);
		return sortedPlanNameMap;
    }

	@Override
	public Map<String, List<CostProjectMemo>> getIndexDataMonth(String month) {
		IUser iUser = ContextUtil.getCurrentUser();
		String userId = iUser.getUserId();
		List<CostProjectMemo> costProjectMemos = baseMapper.getIndexDataMonth(userId,month);
		Map<String, List<CostProjectMemo>> planNameMap = new HashMap<>();
		if (costProjectMemos != null && costProjectMemos.size() > 0) {
			//填充到planNameMap中,key为日期，value为项目、
			for (CostProjectMemo costProjectMemo : costProjectMemos) {
				CostProjectApproval  CostProjectApproval = costProjectApprovalDao.selectById(costProjectMemo.getProjectId());
				if ( CostProjectApproval != null){
					costProjectMemo.setTask( CostProjectApproval.getProjectName());
				}else {
					costProjectMemo.setTask("");
				}
				if(planNameMap.containsKey(costProjectMemo.getMemoDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))){
					planNameMap.get(costProjectMemo.getMemoDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).add(costProjectMemo);
				}else{
					List<CostProjectMemo> list = new ArrayList<>();
					list.add(costProjectMemo);
					planNameMap.put(costProjectMemo.getMemoDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),list);
				}
			}
		}
		// 再为map排下序，按日期
		Map<String, List<CostProjectMemo>> sortedPlanNameMap = new TreeMap<>(planNameMap);
		return sortedPlanNameMap;
	}
}
