/*
 *    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.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.common.core.constant.CommonConstants;
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.ekp.vo.EkpSalaryParamVo;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.EkpSocialViewVo;
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.SalaryAccountAndItemVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.SettlementFormVo;
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 = EasyExcelFactory.write(out, TSalaryAccount.class).includeColumnFiledNames(searchVo.getExportFields()).build();
			int index = 0;
			WriteSheet writeSheet;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT_3) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT_3);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcelFactory.writerSheet("工资报账主表（工资条）" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						list.clear();
					}
				}
			} else {
				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);
			}
		}
	}

	/**
	 * @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());
	}

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

	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);
	}

	@Override
	public void backSalaryBySalaryId(String salaryId) {
		baseMapper.backSalaryBySalaryId(salaryId);
	}

	@Override
	public Boolean updateSalarySettleStatus(List<EkpSocialViewVo> viewVoList) {
		TSalaryAccount account;
		try {
			if (!viewVoList.isEmpty()) {
				for (EkpSocialViewVo viewVo : viewVoList) {
					//根据明细id更新结算状态
					account = baseMapper.selectById(viewVo.getId());
					if (Common.isNotNull(account)) {
						if (CommonConstants.ZERO_STRING.equals(viewVo.getPayFlag())) {
							account.setIncomeSettleFlag(viewVo.getIncomeSettleFlag());
							account.setIncomeCollectFlag(viewVo.getIncomeCollectFlag());
						} else {
							account.setPaySettleFlag(viewVo.getPaySettleFlag());
							account.setPayCollectFlag(viewVo.getPayCollectFlag());
						}
						baseMapper.updateById(account);
					}
				}
			}
		} catch (Exception e) {
			log.error("更新薪资结算状态失败", e);
			return false;
		}
		return true;
	}

	/**
	 * @param page 分页
	 * @param settlementFormVo 结算单Vo
	 * @Description: B端薪酬第一个统计列表
	 * @Author: hgw
	 * @Date: 2020/8/21 11:38
	 * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.yifu.cloud.v1.hrms.api.vo.SettlementFormVo>
	 **/
	@Override
	public IPage<SettlementFormVo> getSettlementFormVoPage(Page<SettlementFormVo> page
			, SettlementFormVo settlementFormVo, List<String> settleDepartIdList){
		return baseMapper.getSettlementFormVoPage(page,settlementFormVo, settleDepartIdList);
	}

	/**
	 * @param salaryFormId 结算单id
	 * @Description: 工资详情-上面的统计
	 * @Author: hgw
	 * @Date: 2020-8-21 17:55:24
	 * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.yifu.cloud.v1.hrms.api.vo.SettlementFormVo>
	 **/
	@Override
	public SettlementFormVo getSettlementFormVoBySalaryFormId(String salaryFormId) {
		return baseMapper.getSettlementFormVoBySalaryFormId(salaryFormId);
	}

	/**
	 * @param page
	 * @param salaryAccountAndItemVo
	 * @Description:  获取报账以及薪资
	 * @Author: hgw
	 * @Date: 2020/8/21 15:32
	 * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.yifu.cloud.v1.hrms.api.vo.SalaryAccountAndItemVo>
	 **/
	@Override
	public IPage<SalaryAccountAndItemVo> getSalaryAccountAndItemVoPage(Page<SalaryAccountAndItemVo> page
			, SalaryAccountAndItemVo salaryAccountAndItemVo) {
		return baseMapper.getSalaryAccountAndItemVoPage(page, salaryAccountAndItemVo);
	}

	/**
	 * @param idList
	 * @Description: 根据idList获取报账信息
	 * @Author: hgw
	 * @Date: 2023/2/2 17:41
	 * @return: java.util.List<com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount>
	 **/
	@Override
	public List<TSalaryAccount> getListByIdList(List<String> idList) {
		return baseMapper.getListByIdList(idList);
	}
}
