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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.vo.EmployeeRegistrationPreVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TDispatchInfoPreVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainRegistListVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSocialPreDetailVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
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.LocalDateTimeUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.social.entity.TDispatchInfoPre;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialPreDetail;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TDispatchInfoPreMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.TDispatchInfoPreService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialPreDetailService;
import com.yifu.cloud.plus.v1.yifu.social.vo.TDispatchInfoPreExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TDispatchInfoPreSearchVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 社保待购买表
 *
 * @author huych
 * @date 2025-09-30 16:40:07
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TDispatchInfoPreServiceImpl extends ServiceImpl<TDispatchInfoPreMapper, TDispatchInfoPre> implements TDispatchInfoPreService {

	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	private final TSocialPreDetailService socialPreDetailService;

	/**
     * 社保待购买表简单分页查询
     * @param tDispatchInfoPre 社保待购买表
     * @return
     */
    @Override
    public IPage<TDispatchInfoPre> getTDispatchInfoPrePage(Page<TDispatchInfoPre> page, TDispatchInfoPreSearchVo tDispatchInfoPre){
		//权限赋值
		initSearchVo(tDispatchInfoPre);
        return baseMapper.getTDispatchInfoPrePage(page,tDispatchInfoPre);
    }

    /**
     * 社保待购买表批量导出
     * @param searchVo 社保待购买表
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TDispatchInfoPreSearchVo searchVo){
        String fileName = "社保待购买批量导出" + DateUtil.getThisTime() + ".xlsx";
        //获取要导出的列表
        List<TDispatchInfoPreExportVo> list = new ArrayList<>();
		initSearchVo(searchVo);
        long count = baseMapper.selectExportCount(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, TDispatchInfoPreExportVo.class).build();
            int index = 0;
            if (count >  CommonConstants.ZERO_INT){
                for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
                    // 获取实际记录
                    searchVo.setLimitStart(i);
                    searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
                    list = baseMapper.selectExportList(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<TDispatchInfoPre> getNoPageList(TDispatchInfoPreSearchVo searchVo) {
		searchVo.setType(CommonConstants.ONE_STRING);
		initSearchVo(searchVo);
		return baseMapper.geNoPageList(searchVo);
	}

	@Override
	public R confirm(List<String> idList) {
		List<TDispatchInfoPre> socialPreList = baseMapper.selectList(Wrappers.<TDispatchInfoPre>query()
				.lambda().in(TDispatchInfoPre::getId, idList)
				.eq(TDispatchInfoPre::getProcessStatus, CommonConstants.ZERO_STRING));
		if (Common.isEmpty(socialPreList)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		LambdaUpdateWrapper<TDispatchInfoPre> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(TDispatchInfoPre::getId,idList)
				.eq(TDispatchInfoPre::getProcessStatus, CommonConstants.ZERO_STRING)
				.set(TDispatchInfoPre::getProcessStatus, CommonConstants.ONE_STRING);
		this.update(updateWrapper);
		return R.ok();
	}

	@Override
	public long getDispatchInfoCount(TDispatchInfoPreSearchVo searchVo) {
		initSearchVo(searchVo);
		return baseMapper.selectExportCount(searchVo);
	}

	@Override
	public Boolean saveSocialPreInfo(EmployeeRegistrationPreVo registrationPreVo) {
		if (Common.isNotNull(registrationPreVo.getSocialIsBuy())
				&& registrationPreVo.getSocialIsBuy().equals(CommonConstants.ZERO_STRING)
				&& !registrationPreVo.getExitSocialInfoList().isEmpty()) {
			//删除已存在的入职确认信息对应的社保明细
			socialPreDetailService.remove(Wrappers.<TSocialPreDetail>lambdaQuery()
					.eq(TSocialPreDetail::getRegisterId, registrationPreVo.getExitSocialInfoList()
							.get(0).getRegisterId()));
			//批量新增
			for (TSocialPreDetailVo vo :registrationPreVo.getExitSocialInfoList()) {
				TSocialPreDetail preDetal = new TSocialPreDetail();
				BeanUtils.copyProperties(vo, preDetal);
				socialPreDetailService.save(preDetal);
			}
			//批量删除社保待购买列表中的待确认、待派单、派单失败、审核、办理失败的数据
			baseMapper.delete(Wrappers.<TDispatchInfoPre>query().lambda().in(
							TDispatchInfoPre::getProcessStatus,Arrays.asList("0", "1", "2", "4","8"))
							.eq(TDispatchInfoPre::getRegisterId,registrationPreVo.getExitSocialInfoList()
							.get(0).getRegisterId()));
		} else {
			TDispatchInfoPreVo preVo = registrationPreVo.getDispatchInfoPreVo();
			if (null != preVo) {
				try {
					//删除已存在的入职确认信息对应的社保明细
					socialPreDetailService.remove(Wrappers.<TSocialPreDetail>lambdaQuery()
							.eq(TSocialPreDetail::getRegisterId, preVo.getRegisterId()));
					//判断是否存在社保待购买信息
					TDispatchInfoPre preExit = baseMapper.selectOne(Wrappers.<TDispatchInfoPre>query().lambda()
							.eq(TDispatchInfoPre::getRegisterId, preVo.getRegisterId())
							.eq(TDispatchInfoPre::getEmpIdcard, preVo.getEmpIdcard())
							.in(TDispatchInfoPre::getProcessStatus, Arrays.asList("0", "1", "2", "4","8"))
							.last(CommonConstants.LAST_ONE_SQL));
					TDispatchInfoPre pre = new TDispatchInfoPre();
					BeanUtils.copyProperties(preVo, pre);
					//时间格式转化
					if (Common.isNotNull(preVo.getExpectedCollectionTime())) {
						pre.setExpectedCollectionTime(LocalDateTimeUtils.dateToLocalDateTime(preVo.getExpectedCollectionTime()));
					}
					if (Common.isNotNull(preVo.getExpectedConfirmTime())) {
						pre.setExpectedConfirmTime(LocalDateTimeUtils.dateToLocalDateTime(preVo.getExpectedConfirmTime()));
					}
					if (Common.isNotNull(preExit)) {
						pre.setId(preExit.getId());
						baseMapper.deleteById(preExit);
						baseMapper.insert(pre);
					} else {
						baseMapper.insert(pre);
					}
				} catch (Exception e) {
					log.error("执行异常", e);
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * @Description: 获取前端客服的所有项目权限
	 * @Author: huych
	 * @Date: 2025/3/13 17:02
	 * @return:
	 **/
	public void initSearchVo(TDispatchInfoPreSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc = this.haveRole(user, roleId);
		if (isSsc || CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
			searchVo.setAuthSql(null);
			return;
		}
		if (Common.isNotNull(searchVo.getType()) && CommonConstants.ONE_STRING.equals(searchVo.getType())) {
			searchVo.setAuthSql(null);
			//获取项目信息
			R<TSettleDomainRegistListVo> domainR = archivesDaprUtil.getAllDeptByCustomerLoginName(user.getUsername());
			if (null != domainR && null != domainR.getData() && null != domainR.getData().getDeptNos() && !domainR.getData().getDeptNos().isEmpty()) {
				searchVo.setDeptNoList(domainR.getData().getDeptNos());
			} else {
				searchVo.setId(CommonConstants.ONE_STRING_NEGATE);
			}
		}
	}

	public boolean haveRole(YifuUser user, long roleId) {
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				return true;
			}
		}
		return false;
	}
}
