/*
 *    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 cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
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.archives.entity.FddSealPersonAuth;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TDepartSettlementInfo;
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.archives.vo.TPersonnelRosterVo;
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.DaprArchivesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSocialProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
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.io.InputStream;
import java.net.URLEncoder;
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({DaprArchivesProperties.class})
@Service
public class TPersonnelRosterServiceImpl extends ServiceImpl<TPersonnelRosterMapper, TPersonnelRoster> implements TPersonnelRosterService {
	private final DaprArchivesProperties daprArchivesProperties;
    /**
     * 简单分页查询
     * @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) {
        LambdaQueryWrapper<TPersonnelRoster> wrapper = buildQueryWrapper(searchVo);
        List<String> idList = Common.getList(searchVo.getIds());
        if (Common.isNotNull(idList)){
            wrapper.in(TPersonnelRoster::getId,idList);
        }
        if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0){
            wrapper.last(" limit "+ searchVo.getLimitStart() +","+ searchVo.getLimitEnd());
        }
        wrapper.orderByDesc(BaseEntity::getCreateTime);
        return baseMapper.selectList(wrapper);
    }

	@Override
	public void everyMonthUpdateRoster() {
		TPersonnelRosterSearchVo  searchVo = new TPersonnelRosterSearchVo();
		long count = baseMapper.getTPersonnelRosterCount(searchVo);
		List<TPersonnelRoster>  list;
		if (count > CommonConstants.ZERO_INT){
			R<List<TSalaryEmpRosterVo>> 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(daprArchivesProperties.getAppUrl(), daprArchivesProperties.getAppId(),
							"/tsalaryemployee/inner/getSalaryEmpRoster", list.stream()
									.map(TPersonnelRoster::getEmpIdcard).collect(Collectors.toList()),
							TSalaryEmpRosterVo.class, SecurityConstants.FROM_IN);
					if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && res.getData().size() > 0){
						for (TSalaryEmpRosterVo vo :res.getData()){
							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());
							}
						}
						this.saveBatch(list);
					}
				}

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

	}

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

    private LambdaQueryWrapper buildQueryWrapper(TPersonnelRosterSearchVo entity){
        LambdaQueryWrapper<TPersonnelRoster> wrapper = Wrappers.lambdaQuery();
        if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
            wrapper.ge(TPersonnelRoster::getCreateTime, entity.getCreateTimes()[0])
                    .le(TPersonnelRoster::getCreateTime,
                            entity.getCreateTimes()[1]);
        }
        if (Common.isNotNull(entity.getCreateName())){
            wrapper.eq(TPersonnelRoster::getCreateName,entity.getCreateName());
        }
        return wrapper;
    }

}
