/*
 *    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.archives.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.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.archives.entity.TPersonnelRoster;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TPersonnelRosterMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TPersonnelRosterService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TPersonnelRosterExportVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TPersonnelRosterSearchVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
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.dapr.config.DaprSalaryProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.salary.vo.SalaryEmpRosterRes;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryEmpRosterVo;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
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.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author fxj
 * @date 2023-06-13 15:42:17
 */
@Log4j2
@AllArgsConstructor
@EnableConfigurationProperties({DaprSalaryProperties.class})
@Service
public class TPersonnelRosterServiceImpl extends ServiceImpl<TPersonnelRosterMapper, TPersonnelRoster> implements TPersonnelRosterService {

	private final DaprSalaryProperties daprSalaryProperties;
    /**
     * 简单分页查询
     * @param tPersonnelRoster 
     * @return
     */
    @Override
    public IPage<TPersonnelRoster> getTPersonnelRosterPage(Page<TPersonnelRoster> page, TPersonnelRosterSearchVo tPersonnelRoster){
        return baseMapper.getTPersonnelRosterPage(page,tPersonnelRoster);
    }

    /**
     * 批量导出
     * @param searchVo
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TPersonnelRosterSearchVo searchVo){
        String fileName = "人员花名册" + DateUtil.getThisTime() + ".xlsx";
        //获取要导出的列表
        List<TPersonnelRosterExportVo> 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  , CommonConstants.UTF8));
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
            //EasyExcel.write(out, TEmpBadRecord.class).sheet("不良记录").doWrite(list);
            int index = 0;
			WriteSheet writeSheet;
			HashMap<String,String> userMap = new HashMap<>();
			ExcelUtil<TPersonnelRosterExportVo> util = new ExcelUtil<>(TPersonnelRosterExportVo.class);
			Map<String,String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			redisLabelMap.putAll(userMap);
			Map<String,String> nameAndDicTypeMap = util.getConverterDicType();
			// 获取所有字典type
			ExcelWriter excelWriter = EasyExcel.write(out, TPersonnelRosterExportVo.class)
					.registerConverter(new DictConverter(nameAndDicTypeMap,redisLabelMap)).build();
			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)){
                        writeSheet = EasyExcel.writerSheet(""+index).build();
                        excelWriter.write(list,writeSheet);
                        index++;
                    }
                    i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
                    if (Common.isNotNull(list)){
                        list.clear();
                    }
                }
            }else {
                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<TPersonnelRosterExportVo> noPageDiy(TPersonnelRosterSearchVo searchVo) {
		return baseMapper.noPageDiy(searchVo);
    }

	@Override
	public void everyMonthUpdateRoster() {
		// 清空重新生成
		String dataMonth = DateUtil.addMonth(-1);
		baseMapper.delete(Wrappers.<TPersonnelRoster>query().lambda()
				.eq(TPersonnelRoster::getDataCreateMonth, dataMonth));
		TPersonnelRosterSearchVo  searchVo = new TPersonnelRosterSearchVo();
		long count = baseMapper.getTPersonnelRosterCount(searchVo);
		List<TPersonnelRoster>  list;
		if (count > CommonConstants.ZERO_INT){
			R<SalaryEmpRosterRes> res;
			Map<String,TSalaryEmpRosterVo> voMap = new HashMap<>();
			TSalaryEmpRosterVo rosterVo;
			for (int i = 0; i <= count; ) {
				searchVo.setLimitStart(i);
				searchVo.setLimitEnd(CommonConstants.ONE_THOUSAND_INT);
				list = baseMapper.getTPersonnelRoster(searchVo);
				if (Common.isNotNull(list)){
					// 处理薪资信息
					res = HttpDaprUtil.invokeMethodPost(daprSalaryProperties.getAppUrl(), daprSalaryProperties.getAppId(),
							"/tsalaryemployee/getSalaryEmpRoster", list.stream()
									.map(TPersonnelRoster::getEmpIdcard).collect(Collectors.toList()),
							SalaryEmpRosterRes.class, SecurityConstants.FROM_IN);
					if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotEmpty(res.getData().getRosterVos())){
						for (TSalaryEmpRosterVo vo :res.getData().getRosterVos()){
							voMap.put(vo.getEmpIdcard(),vo);
						}
					}
					if (Common.isNotNull(list)){
						for (TPersonnelRoster r:list){
							if (Common.isNotNull(voMap)){
								rosterVo = voMap.get(r.getEmpIdcard());
								if (Common.isNotNull(rosterVo)){
									r.setBankNo(rosterVo.getBankNo());
									r.setBankCity(rosterVo.getBankCity());
									r.setBankName(rosterVo.getBankName());
									r.setBankNameSub(rosterVo.getBankSubName());
									r.setBankProvince(rosterVo.getBankProvince());
								}
							}
							r.setDataCreateMonth(dataMonth);
						}
						this.saveBatch(list);
					}
				}

				i = i + CommonConstants.ONE_THOUSAND_INT;
				if (Common.isNotNull(list)){
					list.clear();
				}
				if (Common.isNotNull(voMap)){
					voMap.clear();
				}
			}
		}

	}

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

}
