/*
 *    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.archives.entity.TDepartSettlementInfo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
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.dapr.config.DaprSocialProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.ekp.util.EkpSalaryUtil;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpSalaryParam;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpSalaryParamVo;
import com.yifu.cloud.plus.v1.yifu.salary.entity.MSalaryEstimate;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TApprovalRecord;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryStandard;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryStandardMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.MSalaryEstimateService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TApprovalRecordService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAccountService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryStandardService;
import com.yifu.cloud.plus.v1.yifu.salary.util.SalaryConstants;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

	@Autowired
	private TApprovalRecordService approvalRecordService;

	@Autowired
	private TSalaryAccountService salaryAccountService;

	@Autowired
	private MSalaryEstimateService mSalaryEstimateService;

	@Autowired
	private DaprSocialProperties socialProperties;

	@Autowired
	private EkpSalaryUtil ekpSalaryUtil;

	/**
	 * 标准薪酬工资表简单分页查询
	 *
	 * @param tSalaryStandard 标准薪酬工资表
	 * @return
	 */
	@Override
	public IPage<TSalaryStandard> getTSalaryStandardPageApply(Page<TSalaryStandard> page, TSalaryStandardSearchVo tSalaryStandard) {
		return baseMapper.getTSalaryStandardPageApply(page, tSalaryStandard);
	}
	/**
	 * 标准薪酬工资表简单分页查询
	 *
	 * @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(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.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,Common.getList(searchVo.getIds()));
	}

	private int noPageCountDiy(TSalaryStandardSearchVo searchVo) {
		return baseMapper.getSalaryStandardExportCount(searchVo,Common.getList(searchVo.getIds()));
	}

	@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);
				tApprovalRecord.setNodeId("审核通过");
			} else {
				tSalaryStandard.setStatus(CommonConstants.FIVE_INT);
				tApprovalRecord.setApprovalResult(CommonConstants.ONE_STRING);
				tApprovalRecord.setNodeId("审核不通过");
			}
			if (Common.isNotNull(auditRemark)) {
				tSalaryStandard.setAuditRemark(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);
					salaryEstimate.setType(CommonConstants.ZERO_INT);
					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);

					salaryEstimate.setType(CommonConstants.ONE_INT);
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//缴费库公积金
					List<MSalaryEstimate> forecastFundList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);

					salaryEstimate.setIsSocial(SalaryConstants.IS_SOCIAL_ZERO);
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//缴费库公积金
					List<MSalaryEstimate> forecastSocialList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);

					List<String> stringList;
					if (socialList != null && !socialList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : socialList) {
							stringList.add(s.getEstimateId());
						}
						//更新社保状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tpaymentinfo/inner/updatePaymentSocialStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}
					if (fundList != null && !fundList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : fundList) {
							stringList.add(s.getEstimateId());
						}
						//更新公积金状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tpaymentinfo/inner/updatePaymentFundStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}
					if (forecastSocialList != null && !forecastSocialList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : forecastSocialList) {
							stringList.add(s.getEstimateId());
						}
						//更新社保状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tforecastlibrary/inner/updateForecastSocialStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}
					if (forecastFundList != null && !forecastFundList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : forecastFundList) {
							stringList.add(s.getEstimateId());
						}
						//更新公积金状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tforecastlibrary/inner/updateForecastFundStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}

				}
			}
			//6：删除工资表
			sf.setDeleteFlag(SalaryConstants.DELETED);
			this.updateById(sf);
			return R.ok("级联删除工资表成功");
		}
		return R.failed("id 不可为空");
	}

	@Override
	public R<String> doSend(String id) {
		TSalaryStandard s = this.getById(id);
		if (s == null) {
			return R.failed("未找到工资表");
		} else if (s.getStatus() == SalaryConstants.STATUS[2] || s.getStatus() == SalaryConstants.STATUS[10]) {
			//报账表
			List<EkpSalaryParamVo> ekpList = salaryAccountService.getEkpSalaryParamList(id);
			YifuUser user = SecurityUtils.getUser();
			if (user != null && ekpList != null && !ekpList.isEmpty()) {
				boolean sendStatus = true;
				String sendBack;
				List<TSalaryAccount> accountList = new ArrayList<>();
				TSalaryAccount account;
				Date sendTime = new Date();
				String nowMonth = DateUtil.addMonth(0);
				EkpSalaryParam sendParam;
				for (EkpSalaryParamVo sendParamVo : ekpList) {
					// 转化报账表的参数
					account = new TSalaryAccount();
					account.setId(sendParamVo.getSalaryAccountId());
					sendParam = new EkpSalaryParam();
					BeanUtils.copyProperties(sendParamVo, sendParam);
					sendBack = ekpSalaryUtil.sendToEKP(sendParam);
					account.setSendTime(sendTime);
					account.setSendUser(user.getId());
					account.setSendUserName(user.getNickname());
					if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
						account.setSendStatus(CommonConstants.ONE_STRING);
						account.setSendMonth(nowMonth);
						account.setEkpId(sendBack);
					} else {
						sendStatus = false;
					}
					accountList.add(account);
				}
				salaryAccountService.updateBatchById(accountList);
				if (sendStatus) {
					s.setSendTime(new Date());
					s.setSendMonth(DateUtil.addMonth(0));
					s.setStatus(SalaryConstants.STATUS[3]);
					this.updateById(s);
					return R.ok("发送成功！");
				} else {
					s.setStatus(SalaryConstants.STATUS[10]);
					this.updateById(s);
					return R.ok("发送失败！");
				}
			} else {
				return R.failed("请登录！");
			}
		} else {
			return R.failed("请刷新后检查薪资表状态！");
		}
	}

}
