/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.plugin.excel.vo.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TCustomerInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmpChangeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpChangeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TCustomerInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpChangeInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeProjectService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TEmpChangeInfoVO;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.*;

/**
 * 档案划转日志表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@Service
@RequiredArgsConstructor
public class TEmpChangeInfoServiceImpl extends ServiceImpl<TEmpChangeInfoMapper, TEmpChangeInfo> implements TEmpChangeInfoService {

	private final TEmployeeProjectService tEmployeeProjectService;

	private final TCustomerInfoService tCustomerInfoService;

	private final TSettleDomainService tSettleDomainService;

	/**
	 * @Author huyc
	 * @Description  档案划转
	 * @Date 2022/6/22
	 **/
	@Override
	public R changeEmpProArc(TEmpChangeInfo tEmpChangeInfo) {

		//待划转员工已在目标结算主体下不可划转
		TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard, tEmpChangeInfo.getEmpIdcard()).eq(TEmployeeProject::getDeptId,tEmpChangeInfo.getDepartId())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
		if (Common.isNotNull(tEmployeeProject)) {
			return R.failed("待划转员工已在目标项目下不可划转");
		}
		//TODO
		//划转+已产生未结算金额划转，并且选择了划转月份
		//社保公积金派单处需要直接修改为最新的项目
		//社保预估库、缴费库、对比库、代理差额库，需要同步修改未结算（并且满足这个条件：数据 生成月≥此处划转起始月）的数据，已结算数据不变更；

		//划转,更新项目信息
		TEmployeeProject updateTEmployeeProject = tEmployeeProjectService.getById(tEmpChangeInfo.getProId());
		if (Common.isNotNull(updateTEmployeeProject)) {
			updateTEmployeeProject.setDeptNo(tEmpChangeInfo.getDeptNo());
			updateTEmployeeProject.setDeptId(tEmpChangeInfo.getDeptId());
			updateTEmployeeProject.setDeptName(tEmpChangeInfo.getNewDept());
			updateTEmployeeProject.setUnitId(tEmpChangeInfo.getUnitId());
			updateTEmployeeProject.setUnitNo(tEmpChangeInfo.getUnitNo());
			updateTEmployeeProject.setUnitName(tEmpChangeInfo.getNewDept());
			tEmployeeProjectService.updateById(updateTEmployeeProject);
		}
		//保存档案划转记录
		this.save(tEmpChangeInfo);
		return R.ok();
	}

	@Override
	public R<List<ErrorMessage>> batchChangeArc(List<TEmpChangeInfoVO> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
		Map<Long,ErrorMessage> errorMsgMap = new HashMap<>();
		if (Common.isNotNull(errorMessageList)){
			errorMessageList.stream().forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(),errorMessage));
		}

		Set<String> errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get(i+2))){
				continue;
			}
			errorMsg = new HashSet<>();
			TEmpChangeInfoVO excel = excelVOList.get(i);

			//待划转员工已在目标结算主体下不可划转
			TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,excel.getNewSettleCode())
					.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
			if (Common.isNotNull(tEmployeeProject)) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_CHANGE_EMP_PROJECT, excel.getNewSettleCode()));
			}
			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				//划转,更新项目信息
				TEmployeeProject updateTEmployeePro = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,excel.getOldSettleCode())
						.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
				if (Common.isNotNull(updateTEmployeePro)) {
					TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
							.eq(TSettleDomain::getDepartNo,updateTEmployeePro.getDeptNo()).eq(TSettleDomain::getDeleteFlag,CommonConstants.STATUS_NORMAL));
					if (Common.isNotNull(tSettleDomain)) {
						updateTEmployeePro.setDeptNo(tSettleDomain.getDepartNo());
						updateTEmployeePro.setDeptId(tSettleDomain.getId());
						updateTEmployeePro.setDeptName(tSettleDomain.getDepartName());
						TCustomerInfo tCustomerInfo = tCustomerInfoService.getById(tSettleDomain.getCustomerId());
						if(Common.isNotNull(tCustomerInfo)) {;
							updateTEmployeePro.setUnitId(tCustomerInfo.getId());
							updateTEmployeePro.setUnitNo(tCustomerInfo.getCustomerCode());
							updateTEmployeePro.setUnitName(tCustomerInfo.getCustomerName());
						}
						tEmployeeProjectService.updateById(updateTEmployeePro);
					}
				}
			} else {
				// 数据不合法
				errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok();
	}

	/**
	 * 获取所有项目名称
	 * @return R
	 * @Author huyc
	 * @Date 2022-06-22
	 */
	@Override
	public R<List<TSettleDomain>> getAllDept() {
		List<TSettleDomain> list = tSettleDomainService.list(Wrappers.<TSettleDomain>query().lambda().eq(TSettleDomain::getDeleteFlag, CommonConstants.STATUS_NORMAL));
		return R.ok(list);
	}

	/**
	 * 获取所有单位名称
	 * @return R
	 * @Author huyc
	 * @Date 2022-06-22
	 */
	@Override
	public R<List<TCustomerInfo>> getAllUint() {
		List<TCustomerInfo> list = tCustomerInfoService.list(Wrappers.<TCustomerInfo>query().lambda().eq(TCustomerInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));
		return R.ok(list);
	}
}
