/*
 *    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.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.common.core.util.ExcelUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
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.entity.TStatisticsTaxSalary;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TStatisticsTaxSalaryRule;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TStatisticsTaxSalaryMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TStatisticsTaxSalaryRuleService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TStatisticsTaxSalaryService;
import com.yifu.cloud.plus.v1.yifu.salary.util.DoStatisticsTask;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsTaxSalarySearchVo;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

/**
 * 统计-工资薪金
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@Log4j2
@Service
@AllArgsConstructor
public class TStatisticsTaxSalaryServiceImpl extends ServiceImpl<TStatisticsTaxSalaryMapper, TStatisticsTaxSalary> implements TStatisticsTaxSalaryService {

	private final TStatisticsTaxSalaryRuleService tStatisticsTaxSalaryRuleService;

	@Lazy
	private final DoStatisticsTask doStatisticsTask;

	/**
	 * 统计-工资薪金简单分页查询
	 *
	 * @param tStatisticsTaxSalary 统计-工资薪金
	 * @return
	 */
	@Override
	public IPage<TStatisticsTaxSalary> getTStatisticsTaxSalaryPage(Page<TStatisticsTaxSalary> page, TStatisticsTaxSalarySearchVo tStatisticsTaxSalary) {
		return baseMapper.getTStatisticsTaxSalaryPage(page, tStatisticsTaxSalary);
	}

	/**
	 * 统计-工资薪金批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TStatisticsTaxSalarySearchVo searchVo) {
		String fileName = "工资薪金批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TStatisticsTaxSalary> 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, TStatisticsTaxSalary.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				ExcelUtil<TStatisticsTaxSalary> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(TStatisticsTaxSalary.class);
						for (TStatisticsTaxSalary vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						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);
			}
		}
	}

	private List<TStatisticsTaxSalary> noPageDiy(TStatisticsTaxSalarySearchVo searchVo) {
		LambdaQueryWrapper<TStatisticsTaxSalary> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TStatisticsTaxSalary::getId, idList);
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
			wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
		}
		return baseMapper.selectList(wrapper);
	}

	private Long noPageCountDiy(TStatisticsTaxSalarySearchVo searchVo) {
		LambdaQueryWrapper<TStatisticsTaxSalary> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TStatisticsTaxSalary::getId, idList);
		}
		return baseMapper.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TStatisticsTaxSalarySearchVo entity) {
		LambdaQueryWrapper<TStatisticsTaxSalary> wrapper = Wrappers.lambdaQuery();
		return wrapper;
	}

	/**
	 * @param declareMonth 申报月
	 * @Description: 手动刷新-年度报账+工资薪金+本期申报
	 * @Author: hgw
	 * @Date: 2022/8/19 17:18
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> doRefreshStatisticsTaxAll(String declareMonth) {

		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed("获取登录信息失败！请重新登录！");
		}
		// 查询操作记录
		String yearMonthDay = DateUtil.getCurrentDateString("yyyyMMdd");
		TStatisticsTaxSalaryRule rules = tStatisticsTaxSalaryRuleService.getTStatisticsTaxSalaryRule(yearMonthDay);
		if (rules != null) {
			if (rules.getCanRefreshNums() == 0) {
				return R.failed("当日刷新次数已达上限，请联系管理员，处理TStatisticsTaxSalaryRule表！");
			} else if (rules.getCreateTime().isAfter(LocalDateTime.now().plusMinutes(-5L))) {
				return R.failed(rules.getCreateTime() + "才刷新的，5分钟后可以刷新！");
			}
			rules.setCreateTime(LocalDateTime.now());
			rules.setCanRefreshNums(rules.getCanRefreshNums() - 1);
			tStatisticsTaxSalaryRuleService.updateById(rules);
		} else {
			rules = new TStatisticsTaxSalaryRule();
			rules.setCanRefreshNums(10);
			rules.setCreateTime(LocalDateTime.now());
			rules.setCreateBy(String.valueOf(user.getId()));
			rules.setSettleMonth(declareMonth);
			rules.setYearMonthDay(yearMonthDay);
			tStatisticsTaxSalaryRuleService.save(rules);
		}

		// 异步执行
		doStatisticsTask.doRefreshCore(declareMonth);

		return R.ok("正在生成中，请稍后查看！");
	}
}
