/*
 *    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.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDictItem;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysOutEmpCategorizeFormInfo;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysOutEmpFormInfo;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysOutRelDictItem;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysOutEmpCategorizeFormInfoVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysOutEmpFormInfoVo;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysDictItemMapper;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysOutEmpFormInfoMapper;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysOutRelDictItemMapper;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysOutEmpCategorizeFormInfoService;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysOutEmpFormInfoService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
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 lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;


/**
 * 瓜子采集字段配置表（前端用配置进行展示）
 *
 * @author chenyx
 * @date 2025-06-11 15:57:30
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class SysOutEmpFormInfoServiceImpl extends ServiceImpl<SysOutEmpFormInfoMapper, SysOutEmpFormInfo> implements SysOutEmpFormInfoService {

	private final SysOutEmpCategorizeFormInfoService categorizeFormInfoService;

	private final SysDictItemMapper dictItemMapper;

	private final SysOutRelDictItemMapper outRelDictItemMapper;

	/**
	 * 瓜子C端采集配置列表
	 *
	 * @return List<SysOutEmpCategorizeFormInfoVo>
	 */
	@Override
	public List<SysOutEmpCategorizeFormInfoVo> getConfigList(String isLookToc) {

		List<SysOutEmpCategorizeFormInfoVo> categorizeFormInfoVoList = categorizeFormInfoService.getCategorizeVoList(isLookToc);
		if(Common.isEmpty(categorizeFormInfoVoList)){
			return categorizeFormInfoVoList;
		}

		Map<String,List<SysOutEmpFormInfo>> formListMap = new HashMap<>();

		LambdaQueryWrapper<SysOutEmpFormInfo> formQuery = Wrappers.<SysOutEmpFormInfo>lambdaQuery()
				.eq(SysOutEmpFormInfo::getDelFlag, CommonConstants.ZERO_STRING)
				.orderByAsc(SysOutEmpFormInfo::getSort).orderByDesc(SysOutEmpFormInfo::getId);
		List<SysOutEmpFormInfo> formInfoList = this.list(formQuery);
		if(Common.isEmpty(formInfoList)){
			return categorizeFormInfoVoList;
		}

		for(SysOutEmpFormInfo formInfo : formInfoList){
			// 获取指定分类下的配置字段
			List<SysOutEmpFormInfo> formInfoListByCategorize = formListMap.get(formInfo.getCategorizeId());
			if(Common.isEmpty(formInfoListByCategorize)) {
				// 关联的模块列表
				formInfoListByCategorize = new ArrayList<>();
			}
			formInfoListByCategorize.add(formInfo);
			formListMap.put(formInfo.getCategorizeId(), formInfoListByCategorize);
		}

		for(SysOutEmpCategorizeFormInfoVo categorizeFormInfoVo : categorizeFormInfoVoList){
			if(Common.isNotNull(formListMap.get(categorizeFormInfoVo.getId()))){
				categorizeFormInfoVo.setSysOutEmpFormInfoList(formListMap.get(categorizeFormInfoVo.getId()));
			}
		}

		return categorizeFormInfoVoList;
	}

	/**
	 * 瓜子&HRO映射关系表-分页查询
	 * @param sysOutEmpFormInfo 查询信息
	 * @return IPage<SysOutEmpFormInfoVo>
	 */
	@Override
	public IPage<SysOutEmpFormInfoVo> getSysOutEmpFormInfoPage(Page<SysOutEmpFormInfo> page, SysOutEmpFormInfoVo sysOutEmpFormInfo) {
		IPage<SysOutEmpFormInfoVo> formInfoVoIPage = baseMapper.getSysOutEmpFormInfoPage(page, sysOutEmpFormInfo);

		handleCommonFormInfoVoList(formInfoVoIPage.getRecords());

		return formInfoVoIPage;
	}

	@Override
	public List<SysOutEmpFormInfoVo> noPageDiy(SysOutEmpFormInfoVo sysOutEmpFormInfo) {

		List<SysOutEmpFormInfoVo> formInfoVoList = baseMapper.getSysOutEmpFormInfoList(sysOutEmpFormInfo);

		handleCommonFormInfoVoList(formInfoVoList);

		return formInfoVoList;
	}

	/**
	 * 处理分页和导出组装数据信息
	 */
	private void handleCommonFormInfoVoList(List<SysOutEmpFormInfoVo> formInfoVoList){
		if(Common.isNotNull(formInfoVoList)){
			// 赋值所属分类
			Set<String> categorizeIdSet = formInfoVoList.stream().map(SysOutEmpFormInfoVo::getCategorizeId).collect(Collectors.toSet());
			Map<String, String> categorizeMap = new HashMap<>();
			// 拼分类信息
			List<SysOutEmpCategorizeFormInfo> categorizeList = categorizeFormInfoService.list(
					Wrappers.<SysOutEmpCategorizeFormInfo>query().lambda()
							.in(SysOutEmpCategorizeFormInfo::getId,categorizeIdSet)
							.eq(SysOutEmpCategorizeFormInfo::getDelFlag, CommonConstants.ZERO_STRING));
			if (Common.isNotNull(categorizeList)){
				categorizeMap = categorizeList.stream().collect(Collectors.toMap(SysOutEmpCategorizeFormInfo::getId, SysOutEmpCategorizeFormInfo::getName));
			}
			// 处理字典值展示
			Set<String> gzDictTypeSet = formInfoVoList.stream().map(SysOutEmpFormInfoVo::getDictType).collect(Collectors.toSet());
			// 获取瓜子的字典值内容
			Map<String,List<String>> gzDictMap = new HashMap<>();
			// 获取瓜子映射的皖信字典值内容
			Map<String,List<String>> relWxDictMap = new HashMap<>();
			if(Common.isNotNull(gzDictTypeSet)){
				List<SysDictItem> gzDictList = dictItemMapper.selectList(Wrappers.<SysDictItem>query().lambda()
						.eq(SysDictItem::getDelFlag, CommonConstants.ZERO_STRING)
						.eq(SysDictItem::getDisable, CommonConstants.ZERO_STRING)
						.in(SysDictItem::getType, gzDictTypeSet)
						.eq(SysDictItem::getClientId, ClientNameConstants.CLIENT_GZ)
						.orderByAsc(SysDictItem::getSortOrder).orderByAsc(SysDictItem::getId)
				);
				// 获取瓜子的字典值内容，组成Map
				if(Common.isNotNull(gzDictList)){
					for(SysDictItem dictInfo : gzDictList){
						List<String> dictList = gzDictMap.get(dictInfo.getType());
						if(Common.isEmpty(dictList)) {
							dictList = new ArrayList<>();
						}
						dictList.add(dictInfo.getLabel());
						gzDictMap.put(dictInfo.getType(), dictList);
					}
				}

				// 获取瓜子映射的皖信字典值内容，组成Map
				List<SysOutRelDictItem> outRelDictItemList = outRelDictItemMapper.selectList(Wrappers.<SysOutRelDictItem>query().lambda()
						.in(SysOutRelDictItem::getDictType, gzDictTypeSet)
						.eq(SysOutRelDictItem::getClientId, ClientNameConstants.CLIENT_GZ));

				if(Common.isNotNull(outRelDictItemList)){
					Set<String> wxDictTypeSet = new HashSet<>();
					Map<String,String> outRelDictMap = new HashMap<>();
					for(SysOutRelDictItem outRelDictItem : outRelDictItemList){
						wxDictTypeSet.add(outRelDictItem.getSysDictType());
						outRelDictMap.put(outRelDictItem.getSysDictType(),outRelDictItem.getDictType());
					}

					List<SysDictItem> wxDictList = dictItemMapper.selectList(Wrappers.<SysDictItem>query().lambda()
							.eq(SysDictItem::getDelFlag, CommonConstants.ZERO_STRING)
							.eq(SysDictItem::getDisable, CommonConstants.ZERO_STRING)
							.in(SysDictItem::getType, wxDictTypeSet)
							.eq(SysDictItem::getClientId, ClientNameConstants.CLIENT_MVP)
							.orderByAsc(SysDictItem::getSortOrder).orderByAsc(SysDictItem::getId)
					);

					// 获取瓜子映射的皖信字典值内容，组成Map
					if(Common.isNotNull(wxDictList)){
						for(SysDictItem wxDictInfo : wxDictList){
							// 获取皖信字典对应的瓜子字典
							String gzDictType = outRelDictMap.get(wxDictInfo.getType());
							if(Common.isNotNull(gzDictType)){
								// 将皖信的字典值列表，放到瓜子字典映射Map里
								List<String> wxDictInfoList = relWxDictMap.get(gzDictType);
								if(Common.isEmpty(wxDictInfoList)) {
									wxDictInfoList = new ArrayList<>();
								}
								wxDictInfoList.add(wxDictInfo.getLabel());
								relWxDictMap.put(gzDictType, wxDictInfoList);
							}
						}

					}

				}
			}

			// 赋值 分类名称、字典内容数据
			for(SysOutEmpFormInfoVo outEmpFormInfoVo : formInfoVoList){
				if(Common.isNotNull(outEmpFormInfoVo.getDictType())){
					// 赋值瓜子字典项字符串
					List<String> gzDictOneList = gzDictMap.get(outEmpFormInfoVo.getDictType());
					if(Common.isNotNull(gzDictOneList)){
						outEmpFormInfoVo.setDictItemStrs(String.join(",", gzDictOneList));
					}
					// 赋值映射皖信的字典项字符串
					List<String> wxDictOneList = relWxDictMap.get(outEmpFormInfoVo.getDictType());
					if(Common.isNotNull(wxDictOneList)){
						outEmpFormInfoVo.setWxDictItemStrs(String.join(",", wxDictOneList));
					}
				}
				// 赋值所属分类名称
				if(Common.isNotNull(outEmpFormInfoVo.getCategorizeId())){
					outEmpFormInfoVo.setCategorizeName(categorizeMap.get(outEmpFormInfoVo.getCategorizeId()));
				}

			}
		}
	}

	/**
	 * 瓜子&HRO映射关系表-下拉列表
	 * @return List<SysOutEmpFormInfo>
	 */
	@Override
	public List<SysOutEmpFormInfo> getSysOutEmpFormSelect() {
		return this.list(Wrappers.<SysOutEmpFormInfo>query().lambda()
				.eq(SysOutEmpFormInfo::getDelFlag, CommonConstants.ZERO_STRING)
				.eq(SysOutEmpFormInfo::getFieldStatus, CommonConstants.ZERO_STRING)
				.orderByAsc(SysOutEmpFormInfo::getSort).orderByAsc(SysOutEmpFormInfo::getId)
		);

	}

	/**
	 * 通过id查询瓜子采集字段配置
	 *
	 * @param id 主键
	 * @return SysOutEmpFormInfoVo
	 */
	@Override
	public SysOutEmpFormInfoVo getDataById(String id) {

		SysOutEmpFormInfoVo formInfoVo = this.getInfoVoCommon(id);

		// 拼分类信息
		SysOutEmpCategorizeFormInfo categorizeInfo = categorizeFormInfoService.getOne(
				Wrappers.<SysOutEmpCategorizeFormInfo>query().lambda()
				.eq(SysOutEmpCategorizeFormInfo::getId,formInfoVo.getCategorizeId())
				.eq(SysOutEmpCategorizeFormInfo::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(categorizeInfo)){
			formInfoVo.setCategorizeName(categorizeInfo.getName());
		}

		// 拼字典列表
		if(Common.isNotNull(formInfoVo.getDictType())){
			List<SysDictItem> sysDictList = dictItemMapper.selectList(Wrappers.<SysDictItem>query().lambda()
					.eq(SysDictItem::getDelFlag, CommonConstants.ZERO_STRING)
					.eq(SysDictItem::getDisable, CommonConstants.ZERO_STRING)
					.eq(SysDictItem::getType, formInfoVo.getDictType())
					.eq(SysDictItem::getClientId, ClientNameConstants.CLIENT_GZ)
					.orderByAsc(SysDictItem::getSortOrder).orderByAsc(SysDictItem::getId)
			);
			formInfoVo.setDictItemList(sysDictList);
		}

		return formInfoVo;
	}

	/**
	 * 通过id查询瓜子和皖信映射关系配置详情
	 *
	 * @param id 主键
	 * @return SysOutEmpFormInfoVo
	 */
	@Override
	public SysOutEmpFormInfoVo getRelWxDataById(String id) {
		SysOutEmpFormInfoVo formInfoVo = this.getInfoVoCommon(id);

		// 有字典并且有映射皖信字典的
		if(Common.isNotNull(formInfoVo.getDictType()) && CommonConstants.ONE_STRING.equals(formInfoVo.getWanxinMappingType())){
			// 瓜子的值 对应的 皖信的值
			Map<String,String> relDictValueByTypeMap = new HashMap<>();
			// 皖信的值 对应的 皖信的标识
			Map<String,String> wxDictLabelByValueMap = new HashMap<>();

			// 获取瓜子映射的皖信字典值内容，组成Map
			List<SysOutRelDictItem> outRelDictItemList = outRelDictItemMapper.selectList(Wrappers.<SysOutRelDictItem>query().lambda()
					.eq(SysOutRelDictItem::getDictType, formInfoVo.getDictType())
					.eq(SysOutRelDictItem::getClientId, ClientNameConstants.CLIENT_GZ));

			if(Common.isNotNull(outRelDictItemList)){
				String wxDictType = outRelDictItemList.get(0).getSysDictType();
				// 收集瓜子的字典值
				//Set<String> gzDictValueSet = new HashSet<>();

				for(SysOutRelDictItem outRelDictItem : outRelDictItemList){
					// 收集瓜子的字典值
					//gzDictValueSet.add(outRelDictItem.getValue());
					// 瓜子的值 对应的 皖信的值
					relDictValueByTypeMap.put(outRelDictItem.getValue(), outRelDictItem.getSysDictValue());
				}
				// 获取瓜子的字典值和标签
				List<SysDictItem> gzDictItemList = dictItemMapper.selectList(Wrappers.<SysDictItem>query().lambda()
						.eq(SysDictItem::getDelFlag, CommonConstants.ZERO_STRING)
						.eq(SysDictItem::getDisable, CommonConstants.ZERO_STRING)
						.eq(SysDictItem::getType, formInfoVo.getDictType())
						.eq(SysDictItem::getClientId, ClientNameConstants.CLIENT_GZ)
						.orderByAsc(SysDictItem::getSortOrder).orderByAsc(SysDictItem::getId)
				);
				if(Common.isNotNull(gzDictItemList)){

					// 获取皖信的字典值和标签
					List<SysDictItem> wxDictItemList = dictItemMapper.selectList(Wrappers.<SysDictItem>query().lambda()
							.eq(SysDictItem::getDelFlag, CommonConstants.ZERO_STRING)
							.eq(SysDictItem::getDisable, CommonConstants.ZERO_STRING)
							.eq(SysDictItem::getType, wxDictType)
							.eq(SysDictItem::getClientId, ClientNameConstants.CLIENT_MVP)
					);
					if(Common.isNotNull(wxDictItemList)){
						for(SysDictItem wxDictInfo : wxDictItemList){
							wxDictLabelByValueMap.put(wxDictInfo.getValue(),wxDictInfo.getLabel());
						}
					}
					// 定义瓜子字典标签和皖信字典标签的映射关系
					List<Map<String,String>> relDictLabelMapList = new ArrayList<>();
					for(SysDictItem gzDictInfo : gzDictItemList){
						Map<String,String> relDictLabelMap = new HashMap<>();
						String gzLabel = gzDictInfo.getLabel();

						String relWxValue = relDictValueByTypeMap.get(gzDictInfo.getValue());
						if(Common.isNotNull(relWxValue)){
							relDictLabelMap.put(gzLabel,wxDictLabelByValueMap.get(relWxValue));
						}

						relDictLabelMapList.add(relDictLabelMap);
					}

					formInfoVo.setRelDictMapList(relDictLabelMapList);

				}

			}

		}

		return formInfoVo;
	}

	private SysOutEmpFormInfoVo getInfoVoCommon(String id){
		SysOutEmpFormInfoVo formInfoVo = new SysOutEmpFormInfoVo();
		SysOutEmpFormInfo formInfo = this.getOne(Wrappers.<SysOutEmpFormInfo>query().lambda()
				.eq(SysOutEmpFormInfo::getId,id)
				.eq(SysOutEmpFormInfo::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(formInfo)){
			return formInfoVo;
		}
		BeanUtils.copyProperties(formInfo, formInfoVo);
		return formInfoVo;
	}

	/**
	 * 修改瓜子采集字段配置
	 *
	 * @param sysOutEmpFormInfo 字典
	 * @return R<String>
	 */
	@Override
	public R<String> updateOutEmpFormInfo(SysOutEmpFormInfo sysOutEmpFormInfo) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		SysOutEmpFormInfo formInfo = this.getOne(Wrappers.<SysOutEmpFormInfo>query().lambda()
				.eq(SysOutEmpFormInfo::getId,sysOutEmpFormInfo.getId())
				.eq(SysOutEmpFormInfo::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(formInfo)){
			return R.failed(CommonConstants.ERROR_NO_DOMAIN);
		}

		sysOutEmpFormInfo.setUpdateBy(user.getId());
		sysOutEmpFormInfo.setUpdateTime(LocalDateTime.now());
		this.updateById(sysOutEmpFormInfo);

		return R.ok(CommonConstants.RESULT_DATA_SUCESS);
	}
}
