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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.constants.SalaryConstants;
import com.yifu.cloud.plus.v1.yifu.salary.entity.*;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryStandardMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.*;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryStandardExportVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryStandardSearchVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryStandardVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 标准薪酬工资表
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@Log4j2
@Service
public class TSalaryStandardServiceImpl extends ServiceImpl<TSalaryStandardMapper, TSalaryStandard> implements TSalaryStandardService {

	@Autowired
	private TApprovalRecordService approvalRecordService;

	@Autowired
	private TSalaryAccountService salaryAccountService;

	@Autowired
	private MSalaryEstimateService mSalaryEstimateService;

	@Autowired
	private MSalaryPaymentResService salaryPaymentResService;

	/**
	 * 标准薪酬工资表简单分页查询
	 *
	 * @param tSalaryStandard 标准薪酬工资表
	 * @return
	 */
	@Override
	public IPage<TSalaryStandard> getTSalaryStandardPage(Page<TSalaryStandard> page, TSalaryStandardSearchVo tSalaryStandard) {
		return baseMapper.getTSalaryStandardPage(page, tSalaryStandard);
	}

	/**
	 * 标准薪酬工资表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TSalaryStandardSearchVo searchVo) {
		String fileName = "项目薪酬查询导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TSalaryStandardExportVo> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TSalaryStandardExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TSalaryStandardExportVo> util = new ExcelUtil<>(TSalaryStandardExportVo.class);
						for (TSalaryStandardExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcel.writerSheet("项目薪酬表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.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);
			}
		}
	}

	@Override
	public List<TSalaryStandardExportVo> noPageDiy(TSalaryStandardSearchVo searchVo) {
		return baseMapper.getSalaryStandardExport(searchVo);
	}

	private int noPageCountDiy(TSalaryStandardSearchVo searchVo) {
		return baseMapper.getSalaryStandardExportCount(searchVo);
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TSalaryStandardVo> util1 = new ExcelUtil<>(TSalaryStandardVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TSalaryStandardVo.class, new ReadListener<TSalaryStandardVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TSalaryStandardVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TSalaryStandardVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessageList.add(errorMessage);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importTSalaryStandard(cachedDataList, errorMessageList);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}

	private void importTSalaryStandard(List<TSalaryStandardVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TSalaryStandardVo excel = excelVOList.get(i);
			// 数据合法情况 TODO

			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TSalaryStandardVo excel) {
		TSalaryStandard insert = new TSalaryStandard();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}

	@Override
	public IPage<TSalaryStandard> getTSalaryStandardAuditPage(Page<TSalaryStandard> page, TSalaryStandardSearchVo tSalaryStandard) {
		return baseMapper.getTSalaryStandardAuditPage(page, tSalaryStandard);
	}

	@Override
	public R salaryStandardAudit(String auditFlag, String auditRemark, String id) {
		YifuUser user = SecurityUtils.getUser();
		TSalaryStandard tSalaryStandard = baseMapper.selectById(id);
		if (Common.isNotNull(tSalaryStandard)) {
			//新增流程进展明细
			TApprovalRecord tApprovalRecord = new TApprovalRecord();

			if (CommonConstants.ZERO_STRING.equals(auditFlag)) {
				tSalaryStandard.setStatus(CommonConstants.TWO_INT);
				tApprovalRecord.setApprovalResult(CommonConstants.ZERO_STRING);
			} else {
				tSalaryStandard.setStatus(CommonConstants.FIVE_INT);
				tApprovalRecord.setApprovalResult(CommonConstants.ONE_STRING);
			}
			if (Common.isNotNull(auditRemark)) {
				tSalaryStandard.setRemark(auditRemark);
				tApprovalRecord.setApprovalOpinion(auditRemark);
			}
			tSalaryStandard.setAuditUser(user.getId());
			tSalaryStandard.setAuditTime(DateUtil.getCurrentDateTime());
			baseMapper.updateById(tSalaryStandard);

			tApprovalRecord.setSalaryId(tSalaryStandard.getId());
			tApprovalRecord.setApprovalMan(user.getId());
			tApprovalRecord.setApprovalManName(user.getNickname());
			tApprovalRecord.setApprovalTime(DateUtil.getCurrentDateTime());
			approvalRecordService.save(tApprovalRecord);
		}
		return R.ok();

	}

	@Override
	public R<String> deleteSalaryById(String id) {
		if (id != null) {
			TSalaryStandard sf = this.getById(id);
			if (sf != null && Common.isNotNull(sf.getId())) {
				if (sf.getStatus() != null && !SalaryConstants.AUDIT_STATUS[0].equals(sf.getStatus())
						&& !SalaryConstants.AUDIT_STATUS[5].equals(sf.getStatus())
						&& !SalaryConstants.AUDIT_STATUS[7].equals(sf.getStatus())) {
					return R.failed("状态为：【" + SalaryConstants.AUDIT_STATUS_STRING[sf.getStatus()] + "】，不可删除");
				}
			} else {
				return R.failed("删除失败：未找到工资表！");
			}
			String deptId = sf.getDeptId();
			YifuUser user = SecurityUtils.getUser();
			if (null == user || null == user.getId()) {
				return R.failed("删除工资表失败-获取登录人信息为空");
			}
			//查询结算单：T_SETTLEMENTH_FORM
			if (sf.getType() == null || sf.getType() != CommonConstants.ONE_INT) {
				//4：删除报账
				TSalaryAccount querySalaryAccountEntity = new TSalaryAccount();
				querySalaryAccountEntity.setSalaryFormId(id);
				QueryWrapper<TSalaryAccount> querySalaryAccountWrapper = new QueryWrapper<>();
				querySalaryAccountWrapper.setEntity(querySalaryAccountEntity);
				List<TSalaryAccount> salaryAccountList = salaryAccountService.list(querySalaryAccountWrapper);
				if (salaryAccountList != null && salaryAccountList.size() > CommonConstants.ZERO_INT) {
					for (TSalaryAccount entity : salaryAccountList) {
						entity.setDeleteFlag(SalaryConstants.DELETED);
					}
					salaryAccountService.updateBatchById(salaryAccountList);
					//5：更新预估库结算标识为0
					MSalaryEstimate salaryEstimate = new MSalaryEstimate();
					salaryEstimate.setSalaryId(id);
					salaryEstimate.setIsSocial(SalaryConstants.IS_SOCIAL_ZERO);
					QueryWrapper<MSalaryEstimate> salaryEstimateQueryWrapper = new QueryWrapper<>();
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//社保
					List<MSalaryEstimate> socialList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);
					salaryEstimate.setIsSocial(SalaryConstants.IS_FUND_ONE);
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//公积金
					List<MSalaryEstimate> fundList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);
					if ((socialList != null && !socialList.isEmpty())
							|| (fundList != null && !fundList.isEmpty())) {
						MSalaryPaymentRes res;
						Map<String, MSalaryPaymentRes> saveResMap = new HashMap<>();
						if (socialList != null && !socialList.isEmpty()) {
							for (MSalaryEstimate est : socialList) {
								res = saveResMap.get(est.getEstimateId());
								if (res == null) {
									res = new MSalaryPaymentRes();
									res.setId(est.getEstimateId());
									res.setDeptId(deptId);
								}
								res.setSalarySocialFlag(CommonConstants.ZERO_STRING);
								saveResMap.put(est.getEstimateId(), res);
							}
						}
						if (fundList != null && !fundList.isEmpty()) {
							for (MSalaryEstimate est : fundList) {
								res = saveResMap.get(est.getEstimateId());
								if (res == null) {
									res = new MSalaryPaymentRes();
									res.setId(est.getEstimateId());
									res.setDeptId(deptId);
								}
								res.setSalaryFundFlag(CommonConstants.ZERO_STRING);
								saveResMap.put(est.getEstimateId(), res);
							}
						}
						// 开始更新res
						if (!saveResMap.isEmpty()) {
							Iterator<MSalaryPaymentRes> iter = saveResMap.values().iterator();
							while (iter.hasNext()) {
								res = iter.next();
								salaryPaymentResService.saveOrUpdate(res);
							}
						}
					}
				}
			}
			//6：删除工资表
			sf.setDeleteFlag(SalaryConstants.DELETED);
			this.updateById(sf);
			return R.ok("级联删除工资表成功");
		}
		return R.failed("id 不可为空");
	}

}
