/*
 *    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 com.alibaba.excel.EasyExcel;
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.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.BigDecimalUtils;
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.ExcelUtil;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpSalaryParamVo;
import com.yifu.cloud.plus.v1.yifu.salary.entity.THaveSalaryNosocial;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryAccountMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAccountService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.AccountCheckVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryAccountSearchVo;
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.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工资报账主表（工资条）
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@Log4j2
@Service
public class TSalaryAccountServiceImpl extends ServiceImpl<TSalaryAccountMapper, TSalaryAccount> implements TSalaryAccountService {
	/**
	 * 工资报账主表（工资条）简单分页查询
	 *
	 * @param tSalaryAccount 工资报账主表（工资条）
	 * @return
	 */
	@Override
	public IPage<TSalaryAccount> getTSalaryAccountPage(Page<TSalaryAccount> page, TSalaryAccountSearchVo tSalaryAccount) {
		return baseMapper.getTSalaryAccountPage(page, tSalaryAccount);
	}

	/**
	 * 工资报账主表（工资条）批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TSalaryAccountSearchVo searchVo) {
		String fileName = "员工报账查询批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TSalaryAccount> 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, TSalaryAccount.class).includeColumnFiledNames(searchVo.getExportFields()).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<TSalaryAccount> util = new ExcelUtil<>(TSalaryAccount.class);
						for (TSalaryAccount vo : list) {
							if (CommonConstants.THREE_STRING.equals(vo.getFormType())){
								vo.setRelaySalary(vo.getRelaySalaryUnit());
								vo.setSalaryTax(BigDecimalUtils.safeAdd(vo.getSalaryTax(),vo.getSalaryTaxUnit()));
							}
							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);
			}
		}
	}

	/**
	 * @Description: 根据工资id，返回报账明细（字段较少且有计算，其他地方勿用）
	 * @Author: hgw
	 * @Date: 2022/9/2 17:07
	 * @return: java.util.List<com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount>
	 **/
	@Override
	public List<TSalaryAccount> getListByIncome(String salaryId) {
		return baseMapper.getListByIncome(salaryId);
	}

	@Override
	public List<TSalaryAccount> noPageDiy(TSalaryAccountSearchVo searchVo) {
		return baseMapper.noPageDiy(searchVo,searchVo.getIdList());
	}

	private int noPageCountDiy(TSalaryAccountSearchVo searchVo) {
		return baseMapper.noPageCountDiy(searchVo,searchVo.getIdList());
	}

	@Override
	public Map<String, Integer> getAccountCheckMap(String settleId, String settleMonth, String salaryType) {
		List<AccountCheckVo> list = new ArrayList<>();
		if (CommonConstants.ZERO_STRING.equals(salaryType)) {
			list = baseMapper.getAccountCheckList(settleId, settleMonth);
		} else {
			list = baseMapper.getAccountCheckListLabor(settleId, settleMonth);
		}
		Map<String, Integer> map = new HashMap<>();
		if (list != null && !list.isEmpty()) {
			for (AccountCheckVo str : list) {
				map.put(str.getTitle() + CommonConstants.DOWN_LINE_STRING + str.getRelaySalary().setScale(2, BigDecimal.ROUND_HALF_UP), 1);
			}
		}
		return map;
	}

	@Override
	public Map<String, BigDecimal> getAccountSpecialMap(String invoiceTitle, String unitId, String salaryMonth) {
		List<AccountCheckVo> list = baseMapper.getAccountSpecialList(invoiceTitle, unitId, salaryMonth);
		Map<String, BigDecimal> map = new HashMap<>();
		if (list != null && !list.isEmpty()) {
			for (AccountCheckVo str : list) {
				map.put(str.getTitle(), str.getRelaySalary());
			}
		}
		return map;
	}

	/**
	 * @param empIdCard
	 * @param nowYear
	 * @Description: 获取当前年最小计税月
	 * @Author: hgw
	 * @Date: 2022/1/19 17:57
	 * @return: java.lang.String
	 **/
	@Override
	public String getMinTaxMonthByNowYear(String empIdCard, int nowYear) {
		return baseMapper.getMinTaxMonthByNowYear(empIdCard, nowYear);
	}

	/**
	 * @Author fxj
	 * @Description 获取有工资无社保数据
	 * @Date 17:22 2022/8/16
	 * @Param
	 * @return
	**/
	@Override
	public List<THaveSalaryNosocial> getLastMonthTHaveSalaryNosocial(String month) {
		return baseMapper.getLastMonthTHaveSalaryNosocial(month,
				DateUtil.getYearAndMonth(month,-CommonConstants.ONE_INT),
				DateUtil.getYearAndMonth(month,-CommonConstants.TWO_INT));
	}

	@Override
	public List<String> getAccountYearCheckMap() {
		return baseMapper.getAccountYearCheckList();
	}

	@Override
	public List<EkpSalaryParamVo> getEkpSalaryParamList(String salaryId) {
		return baseMapper.getEkpSalaryParamList(salaryId);
	}

}
