package com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysUserListVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysUsersVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainListVo;
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.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.insurances.constants.InsurancesConstants;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.SysConfig;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsuranceAlert;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.SysConfigMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TInsuranceWarnMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsuranceWarnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author huych
 * @description 针对表【t_insurance_alert(商险到期提醒表)】的数据库操作Service实现
 * @date 2024-08-26 14:20:16
 */
@Service
public class TInsuranceWarnServiceImpl extends ServiceImpl<TInsuranceWarnMapper, TInsuranceAlert> implements TInsuranceWarnService {
	@Autowired
	private UpmsDaprUtils upmsDaprUtils;
	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	@Autowired
	private SysConfigMapper sysConfigMapper;

	@Override
	public void createInsuranceAlert() {
		//批量删除所有未忽略的提醒数据
		baseMapper.delete(Wrappers.<TInsuranceAlert>query().lambda()
				.eq(TInsuranceAlert::getExpireIgnoreFlag, CommonConstants.ONE_STRING));
		//批量生成或者更新商险到期提醒数据
		List<TInsuranceAlert> list = baseMapper.selectInsuranceAlert();
		//获取所有在用的(未删除未锁定)MVP的用户信息
		String userIds;
		if (Common.isNotKong(list)){
			try {
				SysConfig sysConfig = sysConfigMapper.getSysConfigLimitByKey(InsurancesConstants.INSURANCE_ALERT_DEFAULT_PERSON);
				userIds = list.stream().map(BaseEntity::getCreateBy).distinct().collect(Collectors.joining(","));
				// 获取停用账号信息
				Map<String, SysUser> userMap = null;
				// 前端客服对应的账号信息
				Map<String,SysUser> sysUserMap = null;
				//账号停用的提醒对应的项目信息
				Map<String, TSettleDomain> domainHashMap = new HashMap<>();
				userMap = getStopSysUserMap(userIds, userMap);
				//获取停用账户对应的项目的前端客服信息
				if (!Common.isEmpty(userMap)) {
					Map<String, SysUser> finalUserMap = userMap;
					List<String> codes = new ArrayList<>();
					list.stream().forEach(vo -> {
						if (Common.isNotNull(finalUserMap.get(vo.getCreateBy()))) {
							codes.add(vo.getDeptNo());
						}
					});
					if (Common.isNotKong(codes)) {
						//获取对应项目信息
						R<TSettleDomainListVo> infoByCodes = archivesDaprUtil.getSettleInfoByCodes(codes);
						if (null != infoByCodes && Common.isNotNull(infoByCodes.getData()) && Common.isNotNull(infoByCodes.getData().getMapVO())) {
							domainHashMap = infoByCodes.getData().getMapVO();
						}
						// 获取项目对应的前端客服用户信息
						sysUserMap = getStringSysUserMap(sysUserMap, domainHashMap);
					}
				}
				// 停用的账号的提醒信息对应的项目信息不为空 ，遍历更新 前端客服名称及前端客服ID
				initStopInfo(list, userMap, sysUserMap, domainHashMap,sysConfig);
			}catch (Exception e){
				log.error("商险不购买提醒初始化停用客服异常：",e);
			}
			this.saveOrUpdateBatch(list);
		}
	}

	/**
	 * @Author fxj
	 * @Description 获取停用账号信息
	 * @Date 19:09 2025/3/12
	**/
	private Map<String, SysUser> getStopSysUserMap(String userIds, Map<String, SysUser> userMap) {
		if (Common.isNotKong(userIds)){
			R<SysUsersVo> res = upmsDaprUtils.getUserVoByUserIds(userIds);
			if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotNull(res.getData().getUserList())){
				userMap = res.getData().getUserList();
			}
		}
		return userMap;
	}

	/**
	 * @Author fxj
	 * @Description 更加项目编码CODES 获取项目前端客服用户信息
	 * @Date 19:07 2025/3/12
	**/
	private Map<String, SysUser> getStringSysUserMap(Map<String, SysUser> sysUserMap, Map<String, TSettleDomain> domainHashMap) {
		if (Common.isNotKong(domainHashMap)) {
			StringBuilder userNames = new StringBuilder();
			for (TSettleDomain val : domainHashMap.values()) {
				if (Common.isEmpty(userNames.toString())) {
					userNames.append(val.getCsLoginName());
				} else {
					userNames.append(CommonConstants.COMMA_STRING);
					userNames.append(val.getCsLoginName());
				}
			}
			if (!Common.isEmpty(userNames.toString())) {
				R<SysUserListVo> res = upmsDaprUtils.getUserIdsByUserNames(userNames.toString());
				List<SysUser> users = null;
				if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotNull(res.getData().getUserList())) {
					users = res.getData().getUserList();
				}
				if (Common.isNotKong(users)) {
					sysUserMap = users.stream().collect(Collectors.toMap(k -> k.getUsername(), v -> v));
				}
			}
		}
		return sysUserMap;
	}

	/**
	 * @Author fxj
	 * @Description 封装停用账号为项目前端客服账号
	 * @Date 19:05 2025/3/12
	**/
	private void initStopInfo(List<TInsuranceAlert> list,
							  Map<String, SysUser> userMap,
							  Map<String, SysUser> sysUserMap,
							  Map<String, TSettleDomain> domainHashMap,
							  SysConfig sysConfig) {
		if (Common.isNotNull(userMap) && Common.isNotKong(domainHashMap)){
			TSettleDomain domain;
			SysUser user;
			String loginName;
			String nickName;
			String userId;
			for (TInsuranceAlert alert: list){
				userId = null;
				nickName = null;
				if (Common.isNotNull(userMap.get(alert.getCreateBy()))){
					domain = domainHashMap.get(alert.getDeptNo());
					if (Common.isNotNull(domain)){
						loginName = domain.getCsLoginName();
						if (Common.isNotNull(loginName)){
							user = null==sysUserMap?null:sysUserMap.get(loginName);
							if (Common.isNotNull(user) && !CommonConstants.NINE_STRING.equals(user.getLockFlag())){
								userId = user.getUserId();
								nickName = user.getNickname();
							}
						}
					}
					// 找不到对应前端客服或前端客服停用 发给徐瑞玲
					if (Common.isEmpty(userId) && Common.isNotNull(sysConfig)){
						userId = sysConfig.getConfigValue();
						nickName= sysConfig.getConfigValue1();
					}
					if (Common.isNotNull(nickName) && Common.isNotNull(userId)){
						alert.setCreateBy(userId);
						alert.setCreateName(nickName);
					}
				}
			}
		}
	}
}
