package com.yifu.cloud.plus.v1.yifu.salary.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
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.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.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.SocialDaprUtils;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TInsuranceUnpurchasePerson;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TInsuranceUnpurchasePersonSalary;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAtta;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TInsuranceUnpurchasePersonMapper;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TInsuranceUnpurchasePersonSalaryMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TInsuranceUnpurchasePersonService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAttaService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 含风险项目不购买申请明细表
 *
 * @author huych
 * @date 2025-01-10 11:23:21
 */
@Log4j2
@Service
public class TInsuranceUnpurchasePersonServiceImpl extends ServiceImpl<TInsuranceUnpurchasePersonMapper, TInsuranceUnpurchasePerson> implements TInsuranceUnpurchasePersonService {

	@Resource
	private SocialDaprUtils socialDaprUtil;
	@Resource
	TInsuranceUnpurchasePersonSalaryMapper salaryMapper;
	@Resource
	@Lazy
	private TSalaryAttaService tSalaryAttaService;
	@Resource
	private OSSUtil ossUtil;

    /**
     * 含风险项目不购买申请明细表简单分页查询
     * @param tInsuranceUnpurchasePerson 含风险项目不购买申请明细表
     * @return
     */
    @Override
    public IPage<TInsuranceUnpurchasePerson> getTInsuranceUnpurchasePersonPage(Page<TInsuranceUnpurchasePerson> page, TInsuranceUnpurchasePersonSearchVo tInsuranceUnpurchasePerson){
        return baseMapper.getTInsuranceUnpurchasePersonPage(page,tInsuranceUnpurchasePerson);
    }

    /**
     * 含风险项目不购买申请明细表批量导出
     * @param searchVo 含风险项目不购买申请明细表
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TInsuranceUnpurchasePersonSearchVo searchVo){
        String fileName = "含风险项目商险不购买导出" + DateUtil.getThisTime() + ".xlsx";
        //获取要导出的列表
        List<TInsuranceUnpurchasePersonVo> list = new ArrayList<>();
        long count = baseMapper.getTInsuranceUnpurchaseInfoExportCount(searchVo);
        try (ServletOutputStream 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，然后文件流会自动关闭
            ExcelWriter excelWriter = EasyExcel.write(out, TInsuranceUnpurchasePersonVo.class).build();
            int index = 0;
            if (count > CommonConstants.ZERO_INT){
				if (count > CommonConstants.EXCEL_EXPORT_LIMIT_NEW) {
					exportError(response, "数据超过2万条，请联系管理员后端导出");
				} else {
					for (int i = 0; i <= count; i = i + CommonConstants.EXCEL_EXPORT_LIMIT_NEW) {
						// 获取实际记录
						searchVo.setLimitStart(i);
						searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT_NEW);
						list = baseMapper.getTInsuranceUnpurchaseInfoExportList(searchVo);
						if (Common.isNotNull(list)) {
							WriteSheet writeSheet = EasyExcel.writerSheet("含风险项目不购买申请明细表" + index).build();
							excelWriter.write(list, writeSheet);
							index++;
						}
						if (Common.isNotNull(list)) {
							list.clear();
						}
					}
				}
            }else {
                WriteSheet writeSheet = EasyExcel.writerSheet("含风险项目不购买申请明细表"+index).build();
                excelWriter.write(list,writeSheet);
            }
            if (Common.isNotNull(list)){
                list.clear();
            }
            excelWriter.finish();
        }catch (Exception e){
            log.error("执行异常" ,e);
        }
    }

	@Override
	public List<TInsuranceUnpurchasePersonAddVo> getTInsuranceUnpurchasePersonList(String id) {
		return baseMapper.getTInsuranceUnpurchasePersonList(id);
	}

	@Override
	public List<TInsuranceUnpurchasePerson> getBuyList(String deptNo, List<String> idCardList) {
		return baseMapper.getBuyList(deptNo, idCardList);
	}

	/**
	 * @param id 明细id
	 * @Description: 刷新社保状态
	 * @Author: hgw
	 * @Date: 2025/1/15 13:22
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> getSocialWorkInjuryHandleById(String id) {
		TInsuranceUnpurchasePerson person = this.getById(id);
		if (person == null || Common.isEmpty(person.getEmpIdcardNo())|| Common.isEmpty(person.getEmpName())) {
			return R.failed("未找到数据");
		}
		TInsuranceUnpurchasePersonCardVo cardVo = new TInsuranceUnpurchasePersonCardVo();
		cardVo.setEmpIdcardNo(person.getEmpIdcardNo());
		cardVo.setEmpName(person.getEmpName());
		R<Boolean> flag = socialDaprUtil.selectExitSocialInjury(cardVo);
		if (Common.isEmpty(flag) || Boolean.FALSE.equals(flag.getData())) {
			person.setSocialStatus(CommonConstants.ONE_STRING);
		} else {
			person.setSocialStatus(CommonConstants.ZERO_STRING);
		}
		this.updateById(person);
		return R.ok("成功");
	}

	@Override
	public R<TInsuranceUnpurchasePerson> getPersonInfo(String id) {
		TInsuranceUnpurchasePerson person = baseMapper.selectById(id);
		if (Common.isNotNull(person)) {
			List<TInsuranceUnpurchasePersonSalary> personInfoList = salaryMapper.selectList(
					Wrappers.<TInsuranceUnpurchasePersonSalary>lambdaQuery()
							.eq(TInsuranceUnpurchasePersonSalary::getParentId, id)
							.eq(TInsuranceUnpurchasePersonSalary::getDeleteFlag, CommonConstants.ZERO_INT));
			person.setPersonInfoList(personInfoList);
		} else {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		List<TSalaryAtta> attaInfo = tSalaryAttaService.list(Wrappers.<TSalaryAtta>query().lambda().eq(TSalaryAtta::getLinkId, person.getParnetId()));
		if (attaInfo != null && !attaInfo.isEmpty()) {
			URL url;
			for (TSalaryAtta a: attaInfo) {
				url = ossUtil.getObjectUrl(null, a.getAttaSrc());
				a.setAttaUrl(url.toString());
			}
		}
		person.setAttaInfoList(attaInfo);
		return R.ok(person);
	}

	/**
	 * @Description: 刷新社保状态
	 * @Author: hgw
	 * @Date: 2025/1/15 13:22
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public void doSocialWorkInjuryHandleAll() {
		List<String> personList = baseMapper.getSocialBuyList();
		if (personList != null) {
			R<ListStringVo> listVoR = socialDaprUtil.selectWorkInjuryHandleAll();
			if (listVoR != null && listVoR.getData() != null
					&& listVoR.getData().getListVo() != null && !listVoR.getData().getListVo().isEmpty()) {
				List<String> socialList = listVoR.getData().getListVo();
				Map<String, Integer> socialMap = new HashMap<>();
				Integer value = CommonConstants.ONE_INT;
				for (String s : socialList) {
					socialMap.put(s, value);
				}
				// 更新为是在保
				List<String> updateZero = new ArrayList<>();
				// 更新为不在保
				List<String> updateOne = new ArrayList<>();
				for (String idCard : personList) {
					if (socialMap.get(idCard) != null) {
						updateZero.add(idCard);
					} else {
						updateOne.add(idCard);
					}
				}
				if (!updateZero.isEmpty()) {
					baseMapper.updateSocialStatusZero(updateZero);
				}
				if (!updateOne.isEmpty()) {
					baseMapper.updateSocialStatusOne(updateOne);
				}
				// 清理信息
				updateZero.clear();
				updateOne.clear();
				personList.clear();
				socialList.clear();
				socialMap.clear();
			}
		}
	}

	private void exportError(HttpServletResponse response, String errorMessage) {
		String fileName = "导出异常" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<ExportErrorVo> list = new ArrayList<>();
		list.add(new ExportErrorVo(errorMessage));
		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 = EasyExcelFactory.write(out, ExportErrorVo.class).build();
			int index = 0;
			WriteSheet writeSheet = EasyExcelFactory.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);
			}
		}
	}

}
