/*
 *    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.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.vo.SysCspDeptVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProjectBelongDept;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeProjectBelongDeptMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeProjectBelongDeptService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmployeeProjectScpVO;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TEmployeeProjectBelongDeptSearchVo;
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.ExcelAttributeConstants;
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.DictConverter;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.UserPermissionVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 项目档案所属部门表
 *
 * @author hgw
 * @date 2025-02-28 15:03:17
 */
@Log4j2
@Service
public class TEmployeeProjectBelongDeptServiceImpl extends ServiceImpl<TEmployeeProjectBelongDeptMapper, TEmployeeProjectBelongDept> implements TEmployeeProjectBelongDeptService {
	/**
	 * 项目档案所属部门表简单分页查询
	 *
	 * @param tEmployeeProjectBelongDept 项目档案所属部门表
	 * @return
	 */
	@Override
	public IPage<EmployeeProjectScpVO> getTEmployeeProjectBelongDeptPage(Page<EmployeeProjectScpVO> page, TEmployeeProjectBelongDeptSearchVo tEmployeeProjectBelongDept) {
		this.setSearchParam(tEmployeeProjectBelongDept);
		return baseMapper.getTEmployeeProjectBelongDeptPage(page, tEmployeeProjectBelongDept);
	}

	/**
	 * @Description: 处理查询条件
	 * @Author: hgw
	 * @Date: 2025/3/3 9:47
	 * @return: void
	 **/
	private void setSearchParam(TEmployeeProjectBelongDeptSearchVo tEmployeeProjectBelongDept) {
		if (Common.isEmpty(tEmployeeProjectBelongDept.getDeptId())) {
			// 没传项目id，置为-1，不给查询
			tEmployeeProjectBelongDept.setDeptId("-1");
		}
		// empDeptId == -1,则查项目下所有 所属部门 为空的（逻辑在XML的where里）
		// 2025-3-3 11:52:18 倩倩与宇茜沟通后确定的，宇茜说 所属部门树的顶级的数字，是底下加上的，所以没有 包含空的
		if (Common.isNotNull(tEmployeeProjectBelongDept.getEmpDeptId()) && !"-1".equals(tEmployeeProjectBelongDept.getEmpDeptId())) {
			tEmployeeProjectBelongDept.setEmpDeptIdArray(tEmployeeProjectBelongDept.getEmpDeptId().split(","));
		}
		if (Common.isEmpty(tEmployeeProjectBelongDept.getEmpDeptId())) {
			tEmployeeProjectBelongDept.setEmpDeptId("不查数据");
		}
	}

	/**
	 * @Description: CSP导出花名册
	 * @Author: hgw
	 * @Date: 2025/3/3 9:54
	 * @return: void
	 **/
	@Override
	public void listExport(HttpServletResponse response, TEmployeeProjectBelongDeptSearchVo searchVo) {
		String fileName = "人员花名册批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<EmployeeProjectScpVO> list = new ArrayList<>();
		// 处理查询条件
		this.setSearchParam(searchVo);
		long count = baseMapper.getTEmployeeProjectBelongDeptCount(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			Map<String, String> nameAndDicTypeMap = new HashMap<>();
			nameAndDicTypeMap.put("contractStatus", ExcelAttributeConstants.PERSONNEL_STATE);
			nameAndDicTypeMap.put("insuranceStatus", ExcelAttributeConstants.COMMERCIAL_SATTE);
			Map<String, String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			ExcelWriter excelWriter = EasyExcelFactory.write(out, EmployeeProjectScpVO.class).registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap)).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.getTEmployeeProjectBelongDeptList(searchVo);
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcelFactory.writerSheet("花名册" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcelFactory.writerSheet("花名册" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * 获取部门下花名册总数
	 *
	 * @param tEmployeeProjectBelongDept 花名册查询
	 * @return Integer 花名册总数
	 */
	@Override
	public Integer getDeptCount(TEmployeeProjectBelongDeptSearchVo tEmployeeProjectBelongDept) {
		return baseMapper.getDeptCount(tEmployeeProjectBelongDept);
	}

	/**
	 * 根据权限获取对应部门ID下的花名册总数Map
	 *
	 * @param tEmployeeProjectBelongDept 花名册查询
	 * @return Map<String, Integer> 对应部门ID下的花名册总数Map
	 */
	@Override
	public Map<String, Integer> getDeptCountMap(TEmployeeProjectBelongDeptSearchVo tEmployeeProjectBelongDept, UserPermissionVo authority) {
		Map<String, Integer> deptCountMap = new HashMap<>();
		Set<String> departIdSet = authority.getDepartIdSet();
		// 有全部权限
		if(authority.isHaveAll()){
			departIdSet = new HashSet<>();
		}
		List<TEmployeeProjectBelongDeptSearchVo> sysDeptList = baseMapper.getDeptCountMap(tEmployeeProjectBelongDept.getDeptId(),departIdSet);
		if(Common.isNotNull(sysDeptList)) {
			for (TEmployeeProjectBelongDeptSearchVo deptVo : sysDeptList) {
				deptCountMap.put(deptVo.getEmpDeptId(),deptVo.getEmpNum());
			}
		}
		return deptCountMap;
	}

	/**
	 * 没有关联部门的花名册总数
	 *
	 * @param tEmployeeProjectBelongDept 花名册查询
	 * @return Integer 花名册总数
	 */
	@Override
	public Integer getNoneDeptCount(TEmployeeProjectBelongDeptSearchVo tEmployeeProjectBelongDept) {
		return baseMapper.getNoneDeptCount(tEmployeeProjectBelongDept);
	}

	@Override
	public Boolean saveOrDeleteDeptRelation(SysCspDeptVo vo) {
		if (Common.isNotNull(vo.getDepartName())) {
			TEmployeeProjectBelongDept dept = new TEmployeeProjectBelongDept();
			dept.setId(vo.getProjectId());
			dept.setEmpDeptid(vo.getDepartId().toString());
			dept.setEmpDeptname(vo.getDepartName());
			this.saveOrUpdate(dept);
		} else {
			this.removeById(vo.getProjectId());
		}
		return true;
	}
}
