/*
 *    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.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.TPersonnelRosterSearchVo;
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.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.dapr.config.DaprArchivesProperties;
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<TPersonnelRoster> 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);
            ExcelWriter  excelWriter = EasyExcel.write(out, TPersonnelRoster.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<TPersonnelRoster> util = new ExcelUtil<>(TPersonnelRoster.class);
                        for (TPersonnelRoster 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<TPersonnelRoster> noPageDiy(TPersonnelRosterSearchVo searchVo) {
		return baseMapper.noPageDiy(searchVo);
    }

	@Override
	public void everyMonthUpdateRoster() {
		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.BATCH_COUNT);
				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) && Common.isNotNull(voMap)){
						for (TPersonnelRoster r:list){
							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(DateUtil.getYearAndMonth(LocalDateTime.now(),0));
						}
						this.saveBatch(list);
					}
				}

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

	}

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

}
