/*
 *    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 com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ResultConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 员工合同
 *
 * @author hgw
 * @date 2022-06-29 20:45:22
 */
@Service
@RequiredArgsConstructor
public class TEmployeeContractInfoServiceImpl extends ServiceImpl<TEmployeeContractInfoMapper, TEmployeeContractInfo> implements TEmployeeContractInfoService {

	private static final String ID_NOT_EMPTY = "ID,EMP_ID不可为空";
	private static final String EMPID_NOT_EMPTY = "员工ID、项目ID不可为空";

	private static final String EMPINFO_IS_NOT_EXITS_BYID = "未找到人员档案与项目档案！";

	private final TEmployeeInfoService tEmployeeInfoService;
	private final TEmployeeProjectService tEmployeeProjectService;
	private final TSettleDomainService tSettleDomainService;
	private final TCustomerInfoService tCustomerInfoService;
	private final TAttaInfoService tAttaInfoService;
	private final TEmployeeContractAuditService tEmployeeContractAuditService;
	// 缓存信息
	private final CacheManager cacheManager;

	/**
	 * 员工合同信息表简单分页查询
	 *
	 * @param tEmployeeContractInfo 员工合同信息表
	 * @return
	 */
	@Override
	public IPage<TEmployeeContractInfo> getTEmployeeContractInfoPage(Page<TEmployeeContractInfo> page, TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractInfoPage(page, tEmployeeContractInfo);
	}

	@Override
	public R<List<ErrorMessage>> saveNewContract(TEmployeeContractInfo tEmployeeContractInfo) {
		try {
			if (Common.isEmpty(tEmployeeContractInfo.getEmpId()) || Common.isEmpty(tEmployeeContractInfo.getSettleDomain())) {
				return R.failed(EMPID_NOT_EMPTY);
			}
			// 获取人员档案
			TEmployeeInfo tEmployeeInfo = tEmployeeInfoService.getById(tEmployeeContractInfo.getEmpId());
			// 获取项目
			TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
					.lambda().eq(TEmployeeProject::getEmpId, tEmployeeContractInfo.getEmpId())
					.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.last(CommonConstants.LAST_ONE_SQL));
			if (null == tEmployeeInfo || tEmployeeProject == null) {
				return R.failed(EMPINFO_IS_NOT_EXITS_BYID);
			}
			YifuUser user = SecurityUtils.getUser();
			if (user == null || Common.isEmpty(user.getId())) {
				return R.failed(CommonConstants.PLEASE_LOG_IN);
			}
			// 初始化
			this.initEmployeeContract(tEmployeeContractInfo, tEmployeeInfo, tEmployeeProject, user);

			//是否归档：否
			tEmployeeContractInfo.setIsFile(CommonConstants.ONE_STRING);

			//是否在用：是
			tEmployeeContractInfo.setInUse(CommonConstants.ZERO_STRING);

			ExcelAttributeValidityUtil<TEmployeeContractInfo> validity = new ExcelAttributeValidityUtil<>(TEmployeeContractInfo.class);
			validity.ValidityObj(tEmployeeContractInfo);
			if (null != validity.getErrorInfo() && !validity.getErrorInfo().isEmpty()) {
				return R.failed(validity.getErrorInfo(), ResultConstants.VALIDITY_FAIL);
			}

			if (this.saveContractAndAtta(tEmployeeContractInfo)) {
				return R.ok();
			} else {
				return R.failed();
			}
		} catch (Exception e) {
			log.error("员工合同保存异常：" + e.getMessage());
			return R.failed("员工合同保存系统异常！");
		}
	}

	@Override
	public R<List<ErrorMessage>> updateContract(TEmployeeContractInfo tEmployeeContractInfo) {
		try {
			if (Common.isEmpty(tEmployeeContractInfo.getId()) || Common.isEmpty(tEmployeeContractInfo.getEmpId())) {
				return R.failed(ID_NOT_EMPTY);
			}
			YifuUser user = SecurityUtils.getUser();
			if (user == null || Common.isEmpty(user.getId())) {
				return R.failed(CommonConstants.PLEASE_LOG_IN);
			}
			// 初始化
			tEmployeeContractInfo.setUpdateBy(user.getId());
			tEmployeeContractInfo.setUpdateTime(LocalDateTime.now());

			//是否在用：是
			tEmployeeContractInfo.setInUse(CommonConstants.ZERO_STRING);

			ExcelAttributeValidityUtil<TEmployeeContractInfo> validity = new ExcelAttributeValidityUtil<>(TEmployeeContractInfo.class);
			validity.ValidityObj(tEmployeeContractInfo);
			if (null != validity.getErrorInfo() && !validity.getErrorInfo().isEmpty()) {
				return R.failed(validity.getErrorInfo(), ResultConstants.VALIDITY_FAIL);
			}

			if (this.saveContractAndAtta(tEmployeeContractInfo)) {
				return R.ok();
			} else {
				return R.failed();
			}
		} catch (Exception e) {
			log.error("员工合同保存异常：" + e.getMessage());
			return R.failed("员工合同保存系统异常！");
		}
	}


	private void initEmployeeContract(TEmployeeContractInfo tEmployeeContractInfo, TEmployeeInfo tEmployeeInfo
			, TEmployeeProject tEmployeeProject, YifuUser user) {
		tEmployeeContractInfo.setEmpId(tEmployeeInfo.getId());
		tEmployeeContractInfo.setEmpIdcard(tEmployeeInfo.getEmpIdcard());
		tEmployeeContractInfo.setEmpName(tEmployeeInfo.getEmpName());
		tEmployeeContractInfo.setEmpNo(tEmployeeInfo.getEmpCode());
		if (Common.isEmpty(tEmployeeContractInfo.getCreateBy())) {
			tEmployeeContractInfo.setCreateBy(null == user ? "" : user.getId());
			tEmployeeContractInfo.setCreateName(null == user ? "" : user.getNickname());
			tEmployeeContractInfo.setCreateTime(LocalDateTime.now());
		}
		tEmployeeContractInfo.setUpdateBy(null == user ? "" : user.getId());
		tEmployeeContractInfo.setUpdateTime(LocalDateTime.now());
		tEmployeeContractInfo.setSettleDomain(tEmployeeProject.getDeptId());
		tEmployeeContractInfo.setCustomerId(tEmployeeProject.getUnitId());
		tEmployeeContractInfo.setSubjectUnit(tEmployeeProject.getUnitName());
		tEmployeeContractInfo.setUnitNo(tEmployeeProject.getUnitNo());
		tEmployeeContractInfo.setSubjectDepart(tEmployeeProject.getDeptName());
		tEmployeeContractInfo.setDeptNo(tEmployeeProject.getDeptNo());
		tEmployeeContractInfo.setFileProvince(tEmployeeInfo.getFileProvince());
		tEmployeeContractInfo.setFileCity(tEmployeeInfo.getFileCity());
		tEmployeeContractInfo.setFileTown(tEmployeeInfo.getFileTown());
		tEmployeeContractInfo.setWorkFlag(String.valueOf(tEmployeeInfo.getFileStatus()));
		tEmployeeContractInfo.setWorkingStatusSub(CommonConstants.ZERO_STRING);
		//是否作废：否
		tEmployeeContractInfo.setIsObsolete(CommonConstants.ZERO_STRING);
		tEmployeeContractInfo.setDeleteFlag(CommonConstants.ZERO_INT);
		if (Common.isEmpty(tEmployeeContractInfo.getApplyNo())) {
			tEmployeeContractInfo.setApplyNo(this.getCode());
		}
	}

	/**
	 * @param
	 * @Description: 获取 申请编码
	 * @Author: hgw
	 * @Date: 2022/6/22 17:52
	 * @return: java.lang.String
	 **/
	private synchronized String getCode() {
		String nowDay = DateUtil.getThisDay();
		Cache cache = cacheManager.getCache(CacheConstants.EVERYDAY_EMP_CONTRACT_CODE);
		Object nowNumObj = cache.get(nowDay);
		int nowNums = 1;
		if (Common.isNotNull(nowNumObj)) {
			SimpleValueWrapper value = (SimpleValueWrapper) nowNumObj;
			nowNums = (Integer) value.get() + 1;
		}
		cache.put(nowDay, nowNums);
		return "HT" + nowDay + this.getFourNum(String.valueOf(nowNums));
	}

	/**
	 * @param nowNums 数字
	 * @Description: 获取四位字符型数字
	 * @Author: hgw
	 * @Date: 2022-6-30 16:05:25
	 * @return: 五位字符型数字
	 **/
	private String getFourNum(String nowNums) {
		if (nowNums.length() >= 4) {
			return nowNums.substring(0, 4);
		}
		String[] zeroArr = {"0", "00", "000"};
		int num = 3 - nowNums.length();
		return zeroArr[num] + nowNums;
	}

	/**
	 * 保存员工合同表及附件关系表
	 *
	 * @param tEmployeeContractInfo
	 * @return
	 * @Author fxj
	 * @Date 2019-09-09
	 **/
	@Transactional
	@Override
	public boolean saveContractAndAtta(TEmployeeContractInfo tEmployeeContractInfo) {
		//档案柜存在就自动归档
		if (Common.isNotNull(tEmployeeContractInfo.getAttaList())) {
			tEmployeeContractInfo.setIsFile(CommonConstants.ZERO_STRING);
		}
		if (null != tEmployeeContractInfo.getSettleDomain()
				&& (Common.isEmpty(tEmployeeContractInfo.getSubjectUnit())
				|| Common.isEmpty(tEmployeeContractInfo.getSubjectDepart()))) {
			TSettleDomain settleDomain = tSettleDomainService.getById(tEmployeeContractInfo.getSettleDomain());
			if (null != settleDomain) {
				if (Common.isEmpty(tEmployeeContractInfo.getSubjectDepart())) {
					tEmployeeContractInfo.setSubjectDepart(settleDomain.getDepartName());
					tEmployeeContractInfo.setDeptNo(settleDomain.getDepartNo());
				}
				if (null != settleDomain.getCustomerId() && Common.isEmpty(tEmployeeContractInfo.getSubjectUnit())) {
					TCustomerInfo customerInfo = tCustomerInfoService.getById(settleDomain.getCustomerId());
					if (null != customerInfo) {
						tEmployeeContractInfo.setSubjectUnit(customerInfo.getCustomerName());
						tEmployeeContractInfo.setUnitNo(customerInfo.getCustomerCode());
					}
				}
			}
		}
		if (Common.isEmpty(tEmployeeContractInfo.getId())) {
			baseMapper.insert(tEmployeeContractInfo);
			if (Common.isNotNull(tEmployeeContractInfo.getAttaList()) && Common.isNotNull(tEmployeeContractInfo.getId())) {
				List<String> attaList = tEmployeeContractInfo.getAttaList();
				if (null != attaList && !attaList.isEmpty()) {
					TAttaInfo contractAtta;
					for (String attaId : attaList) {
						contractAtta = tAttaInfoService.getById(attaId);
						if (contractAtta != null) {
							contractAtta.setDomainId(tEmployeeContractInfo.getId());
							tAttaInfoService.updateById(contractAtta);
						}
					}
				}
			}
		} else {
			baseMapper.updateById(tEmployeeContractInfo);
		}
		// 不是待提交，记录审核记录
		if (Common.isNotNull(tEmployeeContractInfo.getAuditStatus())
				&& CommonConstants.ZERO_INT != tEmployeeContractInfo.getAuditStatus()) {
			TEmployeeContractAudit audit = new TEmployeeContractAudit();
			audit.setAuditStatus(tEmployeeContractInfo.getAuditStatus());
			audit.setLinkId(tEmployeeContractInfo.getId());
			audit.setLinkType(CommonConstants.ONE_INT);
			audit.setRemark(tEmployeeContractInfo.getAuditRemark());
			tEmployeeContractAuditService.save(audit);
		}
		//先停用所有在用的员工合同
		baseMapper.updateInUseStatusById(tEmployeeContractInfo.getEmpId(), tEmployeeContractInfo.getId(), CommonConstants.ONE_STRING);

		// 更新档案合同状态
		this.updateEmployeeContractStatus(tEmployeeContractInfo.getEmpId());
		return true;
	}

	private void updateEmployeeContractStatus(String empId) {
		//查看未作废合同数
		TEmployeeInfo employeeInfo = tEmployeeInfoService.getById(empId);
		if (employeeInfo != null) {
			employeeInfo.setContractStatus(CommonConstants.ONE_INT);
		}
	}


}
