/*
 *    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.social.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.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysBaseSetInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysHouseHoldInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialfundHouseRes;
import com.yifu.cloud.plus.v1.yifu.social.mapper.SysBaseSetInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.SysHouseHoldInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.SysHouseHoldInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialfundHouseResService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 社保户公积金户数据
 *
 * @author fxj
 * @date 2022-07-12 08:53:19
 */
@Service
@RequiredArgsConstructor
public class SysHouseHoldInfoServiceImpl extends ServiceImpl<SysHouseHoldInfoMapper, SysHouseHoldInfo> implements SysHouseHoldInfoService {

	private final SysBaseSetInfoMapper baseSetInfoMapper;

	@Autowired
	private TSocialfundHouseResService tSocialfundHouseResService;

    /**
     * 社保户公积金户数据简单分页查询
     * @param sysHouseHoldInfo 社保户公积金户数据
     * @return
     */
    @Override
    public IPage<SysHouseHoldInfo> getSysHouseHoldInfoPage(Page<SysHouseHoldInfo> page, SysHouseHoldInfo sysHouseHoldInfo){
        return baseMapper.getSysHouseHoldInfoPage(page,sysHouseHoldInfo);
    }

	/**
	 * 获取所有的独立户数据
	 * @param page
	 * @return
	 */
	@Override
	public IPage<SysHouseHoldInfo> getAllSingleSocailPage(Page<SysHouseHoldInfo> page){
		return baseMapper.getAllSingleSocailPage(page);
	}

	/**
	 * 户新增
	 * @param sysHouseHoldInfo 社保户公积金户数据
	 * @return
	 */
	@Override
	public R<Boolean> saveInfo(SysHouseHoldInfo sysHouseHoldInfo) {
		//户名称去空格
		sysHouseHoldInfo.setName(sysHouseHoldInfo.getName().replace(" ",""));
		SysHouseHoldInfo info = this.getOne(Wrappers.<SysHouseHoldInfo>query().lambda()
					.eq(SysHouseHoldInfo::getType,sysHouseHoldInfo.getType())
					.eq(SysHouseHoldInfo::getName,sysHouseHoldInfo.getName())
					.last(CommonConstants.LAST_ONE_SQL));
		if (null != info){
			return R.failed("对应账户性质、户名的配置已存在！");
		}
		if (Common.isEmpty(sysHouseHoldInfo.getAuditUser()) || Common.isEmpty(sysHouseHoldInfo.getHandleUser())) {
			return R.failed("审核人或办理人必填！");
		}
		baseMapper.insert(sysHouseHoldInfo);

		// 同步审核权限、办理权限
		this.saveAuditUserOrHandleUser(sysHouseHoldInfo, CommonConstants.ZERO_STRING);
		this.saveAuditUserOrHandleUser(sysHouseHoldInfo, CommonConstants.ONE_STRING);
		return R.ok();
	}

	/**
	 * @param authType 0 审核人 1办理人
	 * @Description: 添加审核人、办理人
	 * @Author: hgw
	 * @Date: 2022/12/6 15:50
	 * @return: void
	 **/
	private void saveAuditUserOrHandleUser(SysHouseHoldInfo sysHouseHoldInfo, String authType) {
		TSocialfundHouseRes searchVo = new TSocialfundHouseRes();
		searchVo.setAuthType(authType);
		searchVo.setHouseNameType(sysHouseHoldInfo.getType());
		if (CommonConstants.ZERO_STRING.equals(sysHouseHoldInfo.getType())) {
			searchVo.setSocialHousehold(sysHouseHoldInfo.getName());
		} else {
			searchVo.setFundHousehold(sysHouseHoldInfo.getName());
		}
		if (CommonConstants.ZERO_STRING.equals(authType)) {
			searchVo.setUserId(sysHouseHoldInfo.getAuditUser());
			searchVo.setUserName(sysHouseHoldInfo.getAuditUserName());
			searchVo.setUserDeptName(sysHouseHoldInfo.getAuditUserDeptName());
		} else {
			searchVo.setUserId(sysHouseHoldInfo.getHandleUser());
			searchVo.setUserName(sysHouseHoldInfo.getHandleUserName());
			searchVo.setUserDeptName(sysHouseHoldInfo.getHandleUserDeptName());
		}
		tSocialfundHouseResService.saveSocialAuth(searchVo);
	}

	/**
	 * @Author fxj
	 * @Description 修改社保户公积金户数据
	 * @Date 16:08 2022/11/14
	**/
	@Override
	public R<Boolean> updateByIdAsso(SysHouseHoldInfo hold) {
		//户名称去空格
		if (Common.isNotNull(hold) && Common.isNotNull(hold.getName())){
			hold.setName(hold.getName().replace(" ",""));
		}
		if (Common.isEmpty(hold.getId())){
			return  R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		SysHouseHoldInfo holdInfo = baseMapper.selectById(hold.getId());
		if (Common.isEmpty(holdInfo)){
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		// 编辑标志 true：编辑；false：启用禁用（说明不需要拦截其他必填项）
		boolean isEdit = true;
		if (Common.isEmpty(hold.getType()) && Common.isNotNull(hold.getDelFlag())) {
			isEdit = false;
		}
		if (isEdit && (Common.isEmpty(hold.getAuditUser()) || Common.isEmpty(hold.getHandleUser()))) {
			return R.failed("审核人或办理人必填！");
		}
		if (CommonConstants.ONE_STRING.equals(hold.getDelFlag())
				&& baseSetInfoMapper.selectCount(Wrappers.<SysBaseSetInfo>query().lambda()
				.eq(SysBaseSetInfo::getBaseType, holdInfo.getType())
				.le(SysBaseSetInfo::getApplyStartDate, DateUtil.getCurrentDateTime())
				.in(SysBaseSetInfo::getDepartId,holdInfo.getId())
				.eq(SysBaseSetInfo::getStatus,CommonConstants.ZERO_STRING)
				.eq(SysBaseSetInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
				.and(obj-> obj.isNull(SysBaseSetInfo::getApplyEndDate).or()
						.ge(SysBaseSetInfo::getApplyEndDate,DateUtil.getCurrentDateTime()))) > CommonConstants.ZERO_INT){
			return R.failed("户下存在可用基数配置，请禁用可用基数配置后禁用户配置！");
		}
		int res = baseMapper.updateById(hold);
		if (res >= 0){
			if (isEdit) {
				// 新老数据审核人办理人不同，先删除，再添加
				if (Common.isNotNull(holdInfo.getAuditUser()) && !holdInfo.getAuditUser().equals(hold.getAuditUser())) {
					tSocialfundHouseResService.deleteAuditUser(holdInfo);
				}
				if (Common.isNotNull(holdInfo.getHandleUser()) && !holdInfo.getHandleUser().equals(hold.getHandleUser())) {
					tSocialfundHouseResService.deleteHandleUser(holdInfo);
				}
				// 同步审核权限、办理权限
				this.saveAuditUserOrHandleUser(hold, CommonConstants.ZERO_STRING);
				this.saveAuditUserOrHandleUser(hold, CommonConstants.ONE_STRING);
			}
			return  R.ok();
		}else {
			return R.failed(CommonConstants.SAVE_FAILED);
		}
	}

}
