/*
 *    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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TStatisticsDeclarer;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsDeclarerVo;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TStatisticsDeclarerMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TStatisticsDeclarerService;
import lombok.extern.log4j.Log4j2;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Service;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsDeclarerSearchVo;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import cn.hutool.core.bean.BeanUtil;
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.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
 * 申报对象表
 *
 * @author huyc
 * @date 2022-08-11 10:56:10
 */
@Log4j2
@Service
public class TStatisticsDeclarerServiceImpl extends ServiceImpl<TStatisticsDeclarerMapper, TStatisticsDeclarer> implements TStatisticsDeclarerService {
    /**
     * 申报对象表简单分页查询
     * @param tStatisticsDeclarer 申报对象表
     * @return
     */
    @Override
    public IPage<TStatisticsDeclarer> getTStatisticsDeclarerPage(Page<TStatisticsDeclarer> page, TStatisticsDeclarerSearchVo tStatisticsDeclarer){
        return baseMapper.getTStatisticsDeclarerPage(page,tStatisticsDeclarer);
    }

    /**
     * 申报对象表批量导出
     * @param searchVo 申报对象表
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TStatisticsDeclarerSearchVo searchVo){
        String fileName = "个税申报对象" + DateUtil.getThisTime() + ".xlsx";
        //获取要导出的列表
        List<TStatisticsDeclarer> list = new ArrayList<>();
        long count = noPageCountDiy(searchVo);
        ServletOutputStream out = null;
		if (list == null || list.isEmpty()) {
			list = new ArrayList<>();
		}
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName  , "UTF-8"));
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
            ExcelWriter  excelWriter = EasyExcel.write(out, TStatisticsDeclarer.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<TStatisticsDeclarer> util = new ExcelUtil<>(TStatisticsDeclarer.class);
                        for (TStatisticsDeclarer 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<TStatisticsDeclarer> noPageDiy(TStatisticsDeclarerSearchVo searchVo) {
        LambdaQueryWrapper<TStatisticsDeclarer> wrapper = buildQueryWrapper(searchVo);
        List<String> idList = Common.getList(searchVo.getIds());
        if (Common.isNotNull(idList)){
            wrapper.in(TStatisticsDeclarer::getId,idList);
        }

        if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0){
            wrapper.last(" limit "+ searchVo.getLimitStart() +","+ searchVo.getLimitEnd());
        }
        return baseMapper.selectList(wrapper);
    }

	@Override
	public R updateFlagById(String id, String isDeclare, String undeclareReason) {
		TStatisticsDeclarer tStatisticsDeclarer = baseMapper.selectById(id);
		if (Common.isNotNull(tStatisticsDeclarer)) {
			tStatisticsDeclarer.setIsDeclare(isDeclare);
			if (Common.isNotNull(undeclareReason)) {
				tStatisticsDeclarer.setUndeclareReason(undeclareReason);
			}
			baseMapper.updateById(tStatisticsDeclarer);
			return R.ok();
		}
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
	}

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

    private LambdaQueryWrapper buildQueryWrapper(TStatisticsDeclarerSearchVo entity){
        LambdaQueryWrapper<TStatisticsDeclarer> wrapper = Wrappers.lambdaQuery();
		if (Common.isNotNull(entity.getEmpName())) {
			wrapper.eq(TStatisticsDeclarer::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getDeclareMonth())) {
			wrapper.eq(TStatisticsDeclarer::getDeclareMonth,entity.getDeclareMonth());
		}
		if (Common.isNotNull(entity.getEmpIdcard())) {
			wrapper.eq(TStatisticsDeclarer::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getDeclareUnit())) {
			wrapper.likeRight(TStatisticsDeclarer::getDeclareUnit,entity.getDeclareUnit());
		}
        return wrapper;
    }

    @Override
    public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
        List<ErrorMessage> errorMessageList = new ArrayList<>();
        ExcelUtil<TStatisticsDeclarerVo> util1 = new ExcelUtil<>(TStatisticsDeclarerVo.class);;
        // 写法2：
        // 匿名内部类 不用额外写一个DemoDataListener
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        try {
            EasyExcel.read(inputStream, TStatisticsDeclarerVo.class, new ReadListener<TStatisticsDeclarerVo>() {
                /**
                 * 单次缓存的数据量
                 */
                public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
                /**
                 *临时存储
                 */
                private List<TStatisticsDeclarerVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

                @Override
                public void invoke(TStatisticsDeclarerVo data, AnalysisContext context) {
                    ReadRowHolder readRowHolder = context.readRowHolder();
                    Integer rowIndex = readRowHolder.getRowIndex();
                    data.setRowIndex(rowIndex+1);
                    ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
                    if (Common.isNotNull(errorMessage)){
                        errorMessageList.add(errorMessage);
                    }else {
                        cachedDataList.add(data);
                    }
                    if (cachedDataList.size() >= BATCH_COUNT) {
                        saveData();
                        // 存储完成清理 list
                        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                    }
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    saveData();
                }

                /**
                 * 加上存储数据库
                 */
                private void saveData() {
                    log.info("{}条数据，开始存储数据库！", cachedDataList.size());
                    importTStatisticsDeclarer(cachedDataList,errorMessageList);
                    log.info("存储数据库成功！");
                }
            }).sheet().doRead();
        }catch (Exception e){
            log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR,e);
            return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
        }
        return  R.ok(errorMessageList);
    }
    private void importTStatisticsDeclarer(List<TStatisticsDeclarerVo> excelVOList, List<ErrorMessage> errorMessageList) {

		int successInt = 0;
		int failuerInt = 0;
		List<TStatisticsDeclarerVo> updateList = new ArrayList<>();
        // 执行数据插入操作 组装
        for (int i = 0; i < excelVOList.size(); i++) {
            TStatisticsDeclarerVo excel = excelVOList.get(i);

			if (CommonConstants.ONE_STRING.equals(excel.getIsDeclare()) && Common.isEmpty(excel.getUndeclareReason())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "本期是否申报为否时，不申报原因不可为空"));
				failuerInt++;
				continue;
			}

			//根据身份证号和申报月份查找申报人员
			TStatisticsDeclarer tStatisticsDeclarer = baseMapper.selectOne(Wrappers.<TStatisticsDeclarer>query().lambda()
					.eq(TStatisticsDeclarer::getEmpIdcard, excel.getEmpIdcard())
					.eq(TStatisticsDeclarer::getDeclareMonth, excel.getDeclareMonth())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(tStatisticsDeclarer)) {
				tStatisticsDeclarer.setIsDeclare(excel.getIsDeclare());
				if (Common.isNotNull(excel.getUndeclareReason())) {
					tStatisticsDeclarer.setUndeclareReason(excel.getUndeclareReason());
				}
				baseMapper.updateById(tStatisticsDeclarer);
				successInt++;
			}else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "未找到身份证和申报月份对应的申报人员信息"));
				failuerInt++;
				continue;
			}
		}
		errorMessageList.add(new ErrorMessage(-1, "成功操作" + successInt +"条数据," + "失败"
				+ failuerInt + "条数据"));
	}
}
