/*
 *    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.admin.api.entity.SysArea;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AllUserNaVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AreaVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TCutsomerDataPermisson;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TCutsomerDataPermissonMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TSettleDomainMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.ProjectSetInfoVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.SetInfoVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo;
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.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目表
 *
 * @author hgw
 * @date 2022-06-20 10:02:28
 */
@Service
@RequiredArgsConstructor
public class TSettleDomainServiceImpl extends ServiceImpl<TSettleDomainMapper, TSettleDomain> implements TSettleDomainService {
	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	private final TCutsomerDataPermissonMapper permissonMapper;

	@Override
	public IPage<TSettleDomain> getPage(Page<TSettleDomain> page, TSettleDomain tSettleDomain) {
		return baseMapper.getPage(page, tSettleDomain);
	}

	/**
	 * @Author fxj
	 * @Description 清除项目缓存
	 * @Date 17:08 2022/7/11
	 * @Param
	 * @return
	**/
	@Override
	public void removeSettleCache(YifuUser user, List<String> userIdList) {
		try{
			for(String userId : userIdList){
				redisUtil.remove(CacheConstants.WXHR_SETTLE_DOMAIN_VOS_BY_USERID +"_"+userId);
			}
		} catch (Exception e) {
			log.error("清除缓存错误：",e);
		}
	}

	@Override
	public List<String> getSettleDomainIdsByUserId(String userId) {
		List<String> domainIds = new ArrayList<>();
		String userKey = CacheConstants.WXHR_SETTLE_DOMAIN_VOS_BY_USERID + "_" + userId;
		Object settleDomainVoR = redisUtil.get(userKey);
		if (settleDomainVoR != null) {
			return (List<String>) settleDomainVoR;
		} else {
			List<TCutsomerDataPermisson>  permissonList = permissonMapper.selectAllSettleDomainPermissionByUserId(userId);
			if (Common.isNotNull(permissonList)) {
				domainIds = permissonList.stream().map(TCutsomerDataPermisson::getSettleDomainId).collect(Collectors.toList());
				redisUtil.set(userKey, domainIds);
			}
		}
		return domainIds;
	}

	/**
	 * @param settleDomainSelectVo
	 * @Author: wangan
	 * @Date: 2019/10/18
	 * @Description: dataCheckDepart
	 * @return: com.yifu.cloud.v1.hrms.api.vo.TSettleDomainSelectVo
	 **/
	@Override
	public TSettleDomainSelectVo selectSettleDomainSelectVosById(TSettleDomainSelectVo settleDomainSelectVo) {
		return baseMapper.selectSettleDomainSelectVosById(settleDomainSelectVo.getDepartNo());
	}

	@Override
	public TSettleDomainSelectVo getSettleDomainVoById(String id) {
		return baseMapper.getSettleDomainVoById(id);
	}

	@Override
	public List<TSettleDomainSelectVo> selectAllSettleDomainSelectVos() {
		return baseMapper.selectAllSettleDomainSelectVos();
	}

	@Transactional
	@Override
	public R updateProjectInfo(List<TSettleDomain> list) {
		if (Common.isNotNull(list)) {
			R<AreaVo> areaListR;
			TSettleDomain tSettleDomainInfo;
			AreaVo areaList;
			for (TSettleDomain tSettleDomain:list) {
				areaListR = upmsDaprUtils.getAreaListR();
				if (null == areaListR || areaListR.getCode() != CommonConstants.SUCCESS) {
					return R.failed("获取区域数据失败！");
				}
				areaList = areaListR.getData();
				if (null != areaList && !areaList.getSysAreaList().isEmpty()) {
					for (SysArea area : areaList.getSysAreaList()) {
						if (Common.isNotNull(tSettleDomain.getEProvince()) && area.getAreaName().equals(tSettleDomain.getEProvince())) {
							tSettleDomain.setProvince(area.getId());
						}
						if (Common.isNotNull(tSettleDomain.getECity()) && area.getAreaName().equals(tSettleDomain.getECity())) {
							tSettleDomain.setCity(area.getId());
						}
						if (Common.isNotNull(tSettleDomain.getETown()) && area.getAreaName().equals(tSettleDomain.getETown())) {
							tSettleDomain.setTown(area.getId());
						}
					}
				}
				tSettleDomainInfo = baseMapper.selectOne(Wrappers.<TSettleDomain>query().lambda()
						.eq(TSettleDomain::getDeleteFlag,CommonConstants.ZERO_STRING)
						.eq(TSettleDomain::getDepartNo,tSettleDomain.getDepartNo())
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(tSettleDomainInfo)) {
					tSettleDomain.setId(tSettleDomainInfo.getId());
				}
				// 处理服务团队数据权限 2022-09-19 fxj
				if (Common.isNotNull(tSettleDomain.getServiceTeam())){
					R<AllUserNaVo>  res = upmsDaprUtils.getUserIdsByUserNames(tSettleDomain.getServiceTeam());
					if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotNull(res.getData().getUserIds())){
						// 先清理缓存
						this.removeSettleCache(null,res.getData().getUserIds());
						saveForEkp(res.getData().getUserIds(),tSettleDomain.getId());
					}
				}
				if (Common.isNotNull(tSettleDomainInfo)) {
					baseMapper.updateById(tSettleDomain);
				} else {
					baseMapper.insert(tSettleDomain);
				}
			}
			return R.ok();
		} else {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
	}

	@Override
	public SetInfoVo getSetInfoByCodes(List<String> codes) {
		List<ProjectSetInfoVo> voList = baseMapper.getSetInfoByCodes(codes);
		SetInfoVo setMap = new SetInfoVo();
		if (Common.isNotNull(voList)){
			setMap.setProjectSetInfoVoMap(voList.stream().collect(Collectors.toMap(k->k.getDepartNo(),k->k)));
		}
		return setMap;
	}

	/**
	 * @Author fxj
	 * @Description 更新EKP对应MVP 项目权限，已有权限不做删除处理
	 * @Date 17:17 2022/9/19
	 * @Param
	 * @return
	 **/
	public  boolean saveForEkp(List<String> userIds, String domainId){
		// 1. 先清除现有的这些认的项目权限
		permissonMapper.delete(Wrappers.<TCutsomerDataPermisson>query().lambda()
				.in(TCutsomerDataPermisson::getBePermissonUser,userIds)
				.eq(TCutsomerDataPermisson::getSettleDomainId,domainId));
		// 2.新增新的项目人员权限
		TCutsomerDataPermisson pm;
		if (Common.isNotNull(userIds)){
			for (String uId:userIds){
				pm = new TCutsomerDataPermisson();
				pm.setIsCustomerService(CommonConstants.ZERO_STRING);
				pm.setIsOwner(CommonConstants.ONE_STRING);
				pm.setPermissonSrc("EKP服务团队");
				pm.setPermissonLevel(CommonConstants.ONE_INT);
				pm.setBePermissonUser(uId);
				pm.setBePermissionTime(LocalDateTime.now());
				pm.setSettleDomainId(domainId);
				pm.setPermissionUser(CommonConstants.ONE_STRING);
				pm.setType(CommonConstants.TWO_STRING);
				permissonMapper.insert(pm);
			}
		}
		return true;
	}
}
