package com.qmth.sop.business.templete.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.sop.business.bean.dto.*;
import com.qmth.sop.business.bean.params.UserArchivesParam;
import com.qmth.sop.business.bean.query.DingSubmitQuery;
import com.qmth.sop.business.bean.query.UserArchivesQuery;
import com.qmth.sop.business.bean.result.SysMessageResult;
import com.qmth.sop.business.bean.result.TBDingAttendanceResult;
import com.qmth.sop.business.bean.result.TBDingSubmitQueryResult;
import com.qmth.sop.business.entity.*;
import com.qmth.sop.business.service.*;
import com.qmth.sop.business.sync.RtzfApiUtils;
import com.qmth.sop.business.sync.been.rtzf.RtzfResult;
import com.qmth.sop.business.sync.been.rtzf.RtzfUserInfo;
import com.qmth.sop.business.templete.service.TaskLogicService;
import com.qmth.sop.business.util.ImportExportUtil;
import com.qmth.sop.business.util.excel.BasicExcelListener;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.*;
import com.qmth.sop.common.util.DateDisposeUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 任务处理逻辑impl
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/3/29
 */
@Service
public class TaskLogicServiceImpl implements TaskLogicService {
    private final static Logger log = LoggerFactory.getLogger(TaskLogicServiceImpl.class);
    @Resource
    private ImportExportUtil importExportUtil;

    @Resource
    private BasicAttachmentService basicAttachmentService;

    @Resource
    private SysCustomService sysCustomService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysLevelService sysLevelService;

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private TBDingService tbDingService;

    @Resource
    private SysSupplierService sysSupplierService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private TBUserArchivesService tbUserArchivesService;

    @Resource
    private SequenceService sequenceService;

    @Resource
    private SysDeviceService sysDeviceService;

    @Resource
    private TBDingSubmitService tbDingSubmitService;

    @Resource
    private SysDeviceBrandService sysDeviceBrandService;

    @Resource
    private SysDeviceModelService sysDeviceModelService;

    @Resource
    private TBCrmService tbCrmService;

    @Resource
    private RtzfApiUtils rtzfApiUtils;

    /**
     * 处理导入人员档案数据
     *
     * @param map 数据源
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map<String, Object> executeImportUserArchivesLogic(Map<String, Object> map) throws Exception {
        InputStream inputStream = null;
        try {
            TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
            SysUser requestUser = (SysUser) map.get(SystemConstant.USER);
            inputStream = importExportUtil.getUploadFileInputStream(tbTask);
            LinkedMultiValueMap<String, UserArchivesImportDto> userArchivesImportDtoLinkedMultiValueMap = new LinkedMultiValueMap<>();
            StringJoiner errorData = new StringJoiner("");
            EasyExcel.read(inputStream, UserArchivesImportDto.class, new BasicExcelListener<UserArchivesImportDto>() {

                @Override
                public void handle(LinkedMultiValueMap<String, UserArchivesImportDto> dataList, StringJoiner errorDataSj, Exception exception) {
                    userArchivesImportDtoLinkedMultiValueMap.addAll(dataList);
                    errorData.add(errorDataSj.toString());
                }
            }).headRowNumber(2).sheet(0).doRead();

            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> userArchivesImportDtoLinkedMultiValueMap);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA_ERROR, v -> errorData.toString());

            List<UserArchivesImportDto> userArchivesImportDtoList = userArchivesImportDtoLinkedMultiValueMap.get(BasicExcelListener.SUCCESS);
            if (CollectionUtils.isNotEmpty(userArchivesImportDtoList)) {
                List<String> supplierNameList = userArchivesImportDtoList.stream().map(UserArchivesImportDto::getSupplierName).distinct().collect(Collectors.toList());
                Map<String, Long> roleMap = new HashMap<>();
                List<SysRole> regionCoordinatorList = sysRoleService.list(new QueryWrapper<SysRole>().lambda().eq(SysRole::getType, RoleTypeEnum.REGION_COORDINATOR));
                if (CollectionUtils.isNotEmpty(regionCoordinatorList)) {
                    SysRole regionCoordinator = regionCoordinatorList.get(0);
                    roleMap.put(regionCoordinator.getType().getDesc(), regionCoordinator.getId());
                }

                List<SysRole> effectEngineerList = sysRoleService.list(new QueryWrapper<SysRole>().lambda().eq(SysRole::getType, RoleTypeEnum.EFFECT_ENGINEER));
                if (CollectionUtils.isNotEmpty(effectEngineerList)) {
                    SysRole effectEngineer = effectEngineerList.get(0);
                    roleMap.put(effectEngineer.getType().getDesc(), effectEngineer.getId());
                }

                List<SysRole> assistantEngineerList = sysRoleService.list(new QueryWrapper<SysRole>().lambda().eq(SysRole::getType, RoleTypeEnum.ASSISTANT_ENGINEER));
                if (CollectionUtils.isNotEmpty(assistantEngineerList)) {
                    SysRole assistantEngineer = assistantEngineerList.get(0);
                    roleMap.put(assistantEngineer.getType().getDesc(), assistantEngineer.getId());
                }


                Map<String, Long> supplierMap = new HashMap<>();
                if (CollectionUtils.isNotEmpty(supplierNameList)) {
                    List<SysSupplier> supplierList = sysSupplierService.list(new QueryWrapper<SysSupplier>().lambda().select(SysSupplier::getId, SysSupplier::getName).in(SysSupplier::getName, supplierNameList));
                    supplierMap = supplierList.stream().collect(Collectors.toMap(SysSupplier::getName, SysSupplier::getId));
                }
                for (UserArchivesImportDto userArchivesImportDto : userArchivesImportDtoList) {
                    UserArchivesParam userArchivesParam = new UserArchivesParam();
                    userArchivesParam.setName(userArchivesImportDto.getName());
                    userArchivesParam.setProvince(userArchivesImportDto.getProvince());
                    userArchivesParam.setCity(userArchivesImportDto.getCity());
                    userArchivesParam.setArea(userArchivesImportDto.getArea());
                    userArchivesParam.setGender(GenderEnum.convertTitleToEnum(userArchivesImportDto.getGender()));
                    String identity = userArchivesImportDto.getIdentity();
                    userArchivesParam.setIdentity(identity);
                    List<TBUserArchives> tbUserArchivesList = tbUserArchivesService.list(new QueryWrapper<TBUserArchives>().lambda().eq(TBUserArchives::getIdentity, identity));
                    if (tbUserArchivesList.size() > 1) {
                        throw ExceptionResultEnum.ERROR.exception("存在多个相同身份证异常[" + identity + "]");
                    } else if (tbUserArchivesList.size() == 1) {
                        // 身份证相同则编辑用户
                        userArchivesParam.setId(tbUserArchivesList.get(0).getId());
                        userArchivesParam.setCode(tbUserArchivesList.get(0).getCode());
                    } else {
                        userArchivesParam.setCode(sequenceService.createSerialNo(SequenceEnum.USER_ARCHIVES_CODE));
                    }
                    userArchivesParam.setEducation(EducationEnum.convertTitleToEnum(userArchivesImportDto.getEducation()));
                    userArchivesParam.setMobileNumber(userArchivesImportDto.getMobileNumber());
                    String email = userArchivesImportDto.getEmail();
                    if (email != null && email.length() > 0) {
//                        Pattern pattern = Pattern.compile(SystemConstant.EMAIL_REGEX);
//                        Matcher matcher = pattern.matcher(email);
//                        if (!matcher.matches()) {
//                            throw ExceptionResultEnum.ERROR.exception("导入数据中的 email : " + email + "不符合规范");
//                        }
                        userArchivesParam.setEmail(email);
                    }

                    String supplierName = userArchivesImportDto.getSupplierName();
                    Long supplierId = supplierMap.get(supplierName);
                    if (supplierId != null && supplierId > 0) {
                        userArchivesParam.setSupplierId(supplierId);
                    }
                    String archivesTimeStr = userArchivesImportDto.getArchivesTimeStr();
                    Long archivesTime = DateDisposeUtils.parseDate(archivesTimeStr).getTime();
                    userArchivesParam.setArchivesTime(archivesTime);

                    String roleNames = userArchivesImportDto.getRoleNames();
                    List<Long> roleIdList = new ArrayList<>();
                    for (String roleName : roleNames.split(",")) {
                        Long roleId = roleMap.get(roleName);
                        if (roleId != null && roleId > 0) {
                            roleIdList.add(roleId);
                        }
                    }
                    userArchivesParam.setRoleIds(roleIdList.toArray(new Long[0]));
                    userArchivesParam.setAuthenticationScore(userArchivesImportDto.getAuthenticationScore());

                    String authenticationValidTimeStr = userArchivesImportDto.getAuthenticationValidTimeStr();
                    if (authenticationValidTimeStr != null && authenticationValidTimeStr.length() > 0){
                        Long authenticationValidTime = DateDisposeUtils.parseDate(authenticationValidTimeStr).getTime();
                        userArchivesParam.setAuthenticationValidTime(authenticationValidTime);
                    }
                    userArchivesParam.setRemark(userArchivesImportDto.getRemark());
                    tbUserArchivesService.editUserArchives(userArchivesParam, requestUser);
                }

            }
        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        }
        return map;
    }


    /**
     * 处理客户表导入
     *
     * @param map 数据源
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    @Transactional
    public Map<String, Object> executeImportCustomLogic(Map<String, Object> map) throws Exception {
        InputStream inputStream = null;
        try {
            TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
            inputStream = importExportUtil.getUploadFileInputStream(tbTask);
            LinkedMultiValueMap<String, CustomImportDto> customImportDtoLinkedMultiValueMap = new LinkedMultiValueMap<>();
            StringJoiner errorData = new StringJoiner("");
            EasyExcel.read(inputStream, CustomImportDto.class, new BasicExcelListener<CustomImportDto>() {

                @Override
                public void handle(LinkedMultiValueMap<String, CustomImportDto> dataList, StringJoiner errorDataSj, Exception exception) {
                    customImportDtoLinkedMultiValueMap.addAll(dataList);
                    errorData.add(errorDataSj.toString());
                }
            }).ignoreEmptyRow(true).headRowNumber(2).sheet(0).autoTrim(true).doRead();

            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> customImportDtoLinkedMultiValueMap);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA_ERROR, v -> errorData.toString());
            int errorSize = Objects.nonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.ERROR)) ? Objects.requireNonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.ERROR)).size() : 0;
            if (errorSize == 0) {
                Objects.requireNonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.SUCCESS)).forEach(e -> {
                    SysCustom sysCustom = new SysCustom();
                    sysCustom.setAddress(e.getAddress());
                    sysCustom.setName(e.getName());
                    sysCustom.setArea(e.getArea());
                    sysCustom.setCity(e.getCity());
                    sysCustom.setCode(e.getCode());
                    ProductTypeEnum type = ProductTypeEnum.OFFICE.getTitle().equals(e.getType()) ? ProductTypeEnum.OFFICE : ProductTypeEnum.CLOUD_MARK;
                    sysCustom.setType(type);
                    sysCustom.setProvince(e.getProvince());
                    sysCustom.setPeoperDay(e.getPeoperDay());
                    SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getRealName, e.getManager()));
                    if (Objects.isNull(sysUser)) {
                        throw ExceptionResultEnum.ERROR.exception("客户经理不存在！");
                    }
                    SysLevel sysLevel = sysLevelService.getOne(new QueryWrapper<SysLevel>().lambda().eq(SysLevel::getLevel, e.getLevel()).eq(SysLevel::getType, type));
                    if (Objects.isNull(sysLevel)) {
                        throw ExceptionResultEnum.ERROR.exception("服务档位不存在！");
                    }
                    sysCustom.setLevelId(sysLevel.getId());
                    sysCustom.setSync(false);
                    sysCustom.setEnable(true);
                    sysCustom.setCreateId(((SysUser) map.get("account")).getId());
                    sysCustom.setCreateTime(System.currentTimeMillis());
                    sysCustomService.saveOrUpdate(sysCustom);

                });
            }


        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        }
        return map;
    }


    /**
     * 处理回执明细导出
     *
     * @param map 数据源
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    public Map<String, Object> executeExportSysMessageLogic(Map<String, Object> map) throws Exception {
        File fileTemp = null;
        try {
            fileTemp = SystemConstant.getFileTempVar(SystemConstant.XLSX_PREFIX);

            List<SysMessageResult> lists = sysMessageService.query((Long) map.get("noticeId"), (String) map.get("city"), (Long) map.get("supplierId"), (Boolean) map.get("status"));
            //List<SysMessageResult> 转化成 List<SysMessageExportDto>

            List<SysMessageExportDto> sysMessageExportDtoList = lists.stream().map(e -> {
                SysMessageExportDto dto = new SysMessageExportDto();
                dto.setCity(e.getCity());
                dto.setCode(e.getCode());
                dto.setCountry(e.getCountry());
                dto.setCustom(e.getCustom());
                dto.setMobileNumber(e.getMobileNumber());
                dto.setName(e.getName());
                dto.setProvince(e.getProvince());
                dto.setService(e.getService());
                dto.setStatus(e.getStatus() ? "已阅" : "未阅");
                dto.setSupplier(e.getSupplier());
                //时间戳转化为日期字符串
                if (Objects.nonNull(e.getReceiveTime())) {
                    dto.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(e.getReceiveTime()));
                }
                if (Objects.nonNull(e.getType())) {
                    dto.setType(e.getType().getTitle());
                }
                return dto;
            }).collect(Collectors.toList());

            EasyExcel.write(fileTemp, SysMessageExportDto.class).sheet("回执明细导出").doWrite(sysMessageExportDtoList);

            BasicAttachment basicAttachment = basicAttachmentService.saveAttachment(fileTemp, UploadFileEnum.FILE);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> sysMessageExportDtoList);
            map.computeIfAbsent(SystemConstant.EXCEL_ATTACHMENT, v -> basicAttachment);
        } finally {
            if (Objects.nonNull(fileTemp)) {
                fileTemp.delete();
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> executeExportDingCountLogic(Map<String, Object> map) throws Exception {
        File fileTemp = null;
        try {
            fileTemp = SystemConstant.getFileTempVar(SystemConstant.XLSX_PREFIX);
            List<TBDingSubmitQueryResult> tbDingCountQueryResults = tbDingService.query((SysUser) map.get(SystemConstant.USER), (Long) map.get("serviceId"), (String) map.get("status"), (Long) map.get("createId"), (String) map.get("userName"), (Long) map.get("supplierId"), (String) map.get("String"), (String) map.get("sopNo"), (Long) map.get("days"));

            EasyExcel.write(fileTemp, TBDingSubmitQueryResult.class).sheet("考勤打卡统计导出").doWrite(tbDingCountQueryResults);

            BasicAttachment basicAttachment = basicAttachmentService.saveAttachment(fileTemp, UploadFileEnum.FILE);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> tbDingCountQueryResults);
            map.computeIfAbsent(SystemConstant.EXCEL_ATTACHMENT, v -> basicAttachment);
        } finally {
            if (Objects.nonNull(fileTemp)) {
                fileTemp.delete();
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> executeExportDingAttendanceLogic(Map<String, Object> map) throws Exception {
        File fileTemp = null;
        try {
            fileTemp = SystemConstant.getFileTempVar(SystemConstant.XLSX_PREFIX);
            List<TBDingAttendanceResult> tbDingAttendanceResults = tbDingService.attendanceQuery((Long) map.get("serviceId"), (String) map.get("userName"), (Long) map.get("startTime"), (Long) map.get("endTime"), (Long) map.get("supplierId"), (String) map.get("custom"), (String) map.get("sopNo"), (InOutTypeEnum) map.get("type"), (DingResultEnum) map.get("status"), (Long) map.get("abnormal"));

//            tbDingAttendanceResults.forEach(e -> {
//                //e.setStatus(FlowStatusEnum.convertToEnum(e.getStatus()).getTitle());
//            });
            EasyExcel.write(fileTemp, TBDingAttendanceResult.class).sheet("考勤明细导出").doWrite(tbDingAttendanceResults);

            BasicAttachment basicAttachment = basicAttachmentService.saveAttachment(fileTemp, UploadFileEnum.FILE);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> tbDingAttendanceResults);
            map.computeIfAbsent(SystemConstant.EXCEL_ATTACHMENT, v -> basicAttachment);
        } finally {
            if (Objects.nonNull(fileTemp)) {
                fileTemp.delete();
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> executeImportDeviceLogic(Map<String, Object> map) throws Exception {
        InputStream inputStream = null;
        try {
            TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
            inputStream = importExportUtil.getUploadFileInputStream(tbTask);
            LinkedMultiValueMap<String, DeviceImportDto> customImportDtoLinkedMultiValueMap = new LinkedMultiValueMap<>();
            StringJoiner errorData = new StringJoiner("");
            EasyExcel.read(inputStream, DeviceImportDto.class, new BasicExcelListener<DeviceImportDto>() {

                @Override
                public void handle(LinkedMultiValueMap<String, DeviceImportDto> dataList, StringJoiner errorDataSj, Exception exception) {
                    customImportDtoLinkedMultiValueMap.addAll(dataList);
                    errorData.add(errorDataSj.toString());
                }
            }).ignoreEmptyRow(true).headRowNumber(2).sheet(0).autoTrim(true).doRead();


            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> customImportDtoLinkedMultiValueMap);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA_ERROR, v -> errorData.toString());
            int errorSize = Objects.nonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.ERROR)) ? Objects.requireNonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.ERROR)).size() : 0;

            if (errorSize == 0) {
                List<SysDevice> sysDevices = new ArrayList<>();
                List<SysSupplier> supplierList = sysSupplierService.list(new QueryWrapper<SysSupplier>().lambda().eq(SysSupplier::getType, SupplierTypeEnum.DEVICE));
                List<SysDeviceBrand> brandList = sysDeviceBrandService.list();
                List<SysDeviceModel> modelList = sysDeviceModelService.list();
                Objects.requireNonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.SUCCESS)).forEach(e -> {
                    SysDevice device = new SysDevice();
                    if (brandList.stream().noneMatch(r -> r.getBrand().equals(e.getBrand()))) {
                        SysDeviceBrand brand = new SysDeviceBrand();
                        brand.setBrand(e.getBrand());
                        brand.insertInfo(((SysUser) map.get("account")).getId());
                        sysDeviceBrandService.saveOrUpdate(brand);
                        brandList.add(brand);
                        SysDeviceModel model = new SysDeviceModel();
                        model.setBrandId(brand.getId());
                        model.setModel(e.getModel());
                        model.insertInfo(((SysUser) map.get("account")).getId());
                        sysDeviceModelService.saveOrUpdate(model);
                        modelList.add(model);
                    } else {
                        if (modelList.stream().noneMatch(r -> r.getModel().equals(e.getModel()))) {
                            SysDeviceModel model = new SysDeviceModel();
                            model.setBrandId(brandList.stream().filter(r -> r.getBrand().equals(e.getBrand())).findFirst().get().getId());
                            model.setModel(e.getModel());
                            model.insertInfo(((SysUser) map.get("account")).getId());
                            sysDeviceModelService.saveOrUpdate(model);
                            modelList.add(model);
                        }
                    }

                    device.setBrand(e.getBrand());
                    device.setModel(e.getModel());


                    device.setDeviceCode(e.getDeviceCode());
                    InOutTypeEnum bound = InOutTypeEnum.IN.getTitle().contains(e.getBound()) ? InOutTypeEnum.IN : InOutTypeEnum.OUT;
                    device.setBound(bound);
                    device.setLocation(e.getLocation());
                    device.setEnable(true);
                    //日期字符串转换时间戳
                    try {
                        device.setBuyTime(new SimpleDateFormat("yyyy/MM/dd").parse(e.getBuyTime()).getTime());
                    } catch (ParseException ex) {
                        throw ExceptionResultEnum.ERROR.exception("购买时间格式错误");
                    }

                    device.setScanCount(e.getScanCount());
                    if (supplierList.stream().noneMatch(s -> s.getName().equals(e.getSupplier()))) {
                        throw ExceptionResultEnum.ERROR.exception("供应商不存在！");
                    }
                    device.setSupplierId(supplierList.stream().filter(s -> s.getName().equals(e.getSupplier())).findFirst().get().getId());
                    device.setSerialNo(e.getSerialNo());
                    DeviceStatusEnum status = DeviceStatusEnum.NORMAL.getTitle().equals(e.getStatus()) ? DeviceStatusEnum.NORMAL : DeviceStatusEnum.BREAK_DOWN;
                    device.setStatus(status);
                    device.setSync(false);
                    device.insertInfo(((SysUser) map.get("account")).getId());
                    sysDevices.add(device);
                });
                sysDeviceService.saveSysDevice(sysDevices);
            }


        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> executeExportDingSubmitLogic(Map<String, Object> map) throws Exception {
        File fileTemp = null;
        try {
            fileTemp = SystemConstant.getFileTempVar(SystemConstant.XLSX_PREFIX);
            //数据读取逻辑start
            DingSubmitQuery query = (DingSubmitQuery) map.get(SystemConstant.QUERY);
            Long serviceUnitId = query.getServiceUnitId();
            String dingSubmitStatusDesc = query.getDingSubmitStatusDesc();
            Long submitUserId = query.getSubmitUserId();
            String archivesName = query.getArchivesName();
            Long supplierId = query.getSupplierId();
            String customName = query.getCustomName();
            String sopNo = query.getSopNo();
            Integer violationHoursLimit = query.getViolationHoursLimit();
            Integer dingExceptionLimit = query.getDingExceptionLimit();
            Integer remainLimit = query.getRemainLimit();
            Integer exceptionLimit = query.getExceptionLimit();

            SysUser requestUser = (SysUser) map.get(SystemConstant.USER);

            List<DingSubmitExportDto> dingSubmitExportDtoList = tbDingSubmitService.findDingSubmitExportList(serviceUnitId, dingSubmitStatusDesc,
                    submitUserId, archivesName, supplierId, customName, sopNo, violationHoursLimit, dingExceptionLimit, remainLimit, exceptionLimit, requestUser.getId());
            //数据读取逻辑end
            EasyExcel.write(fileTemp, DingSubmitExportDto.class).sheet("考勤提交导出").doWrite(dingSubmitExportDtoList);

            BasicAttachment basicAttachment = basicAttachmentService.saveAttachment(fileTemp, UploadFileEnum.FILE);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> dingSubmitExportDtoList);
            map.computeIfAbsent(SystemConstant.EXCEL_ATTACHMENT, v -> basicAttachment);
        } finally {
            if (Objects.nonNull(fileTemp)) {
                fileTemp.delete();
            }
        }
        return map;
    }

    /**
     * 处理导出人员档案数据
     *
     * @param map 数据源
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map<String, Object> executeExportUserArchivesLogic(Map<String, Object> map) throws Exception {
        File fileTemp = null;
        try {
            fileTemp = SystemConstant.getFileTempVar(SystemConstant.XLSX_PREFIX);
            //数据读取逻辑start
            UserArchivesQuery query = (UserArchivesQuery) map.get(SystemConstant.QUERY);
            String city = query.getCity();
            Long supplierId = query.getSupplierId();
            String archivesName = query.getArchivesName();
            RoleTypeEnum roleType = query.getRoleType();
            Boolean authenticationStatus = query.getAuthenticationStatus();
            Long archivesTimeStart = query.getArchivesTimeStart();
            Long archivesTimeEnd = query.getArchivesTimeEnd();
            Integer remainValidDay = query.getRemainValidDay();
            List<UserArchivesImportDto> archivesImportDtoList = tbUserArchivesService.findExportData(city, supplierId, archivesName, roleType, authenticationStatus, archivesTimeStart, archivesTimeEnd, remainValidDay);
            //数据读取逻辑end
            EasyExcel.write(fileTemp, UserArchivesImportDto.class).sheet("人员档案导出").doWrite(archivesImportDtoList);

            BasicAttachment basicAttachment = basicAttachmentService.saveAttachment(fileTemp, UploadFileEnum.FILE);
            map.computeIfAbsent(SystemConstant.EXCEL_DATA, v -> archivesImportDtoList);
            map.computeIfAbsent(SystemConstant.EXCEL_ATTACHMENT, v -> basicAttachment);
        } finally {
            if (Objects.nonNull(fileTemp)) {
                fileTemp.delete();
            }
        }
        return map;
    }

    @Transactional
    @Override
    public Map<String, Object> executeSyncFxxkData(Map<String, Object> map) {
        return tbCrmService.syncCrmFromFxxk(map);
    }

    @Transactional
    @Override
    public Map<String, Object> executeSyncRtzfUserPush(Map<String, Object> map) {
        // 需要同步的用户
        List<SysUser> sysUserList = sysUserService.list(new QueryWrapper<SysUser>().lambda().eq(SysUser::getRtzfSyncStatus, RtzfSyncStatusEnum.NEED_SYNC));
        List<RtzfUserInfo> rtzfUserInfoList = sysUserList.stream().flatMap(e -> {
            Long id = e.getId();
            RtzfUserInfo rtzfUserInfo = new RtzfUserInfo();
            rtzfUserInfo.setUserName(String.valueOf(id));
            rtzfUserInfo.setRealName(e.getRealName());

            String companyName = sysUserService.findUserCompanyName(id);
            if (companyName != null && companyName.length() > 0) {
                rtzfUserInfo.setCompanyName(companyName);
            }
            rtzfUserInfo.setPhoneNo(e.getMobileNumber());
            // TODO: 2023/11/27 密码要解密再加密
            String password = e.getPassword();
            rtzfUserInfo.setPassword(password);
            rtzfUserInfo.setVerifyPassword(password);
            GenderEnum gender = e.getGender();
            rtzfUserInfo.setSex(GenderEnum.MAN.equals(gender) ? 1 : 0);
            rtzfUserInfo.setWorkNo(String.valueOf(id));
            rtzfUserInfo.setState(0);

            // 0 为启用，1 为禁用
            Boolean enable = e.getEnable();
            rtzfUserInfo.setWorkState(enable ? 0 : 1);
            List<Long> roleIdList = sysRoleService.listRolesByUserId(id)
                    .stream()
                    .map(RoleDto::getId)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(roleIdList)) {
                rtzfUserInfo.setRoleIds(roleIdList);
            }
            return Stream.of(rtzfUserInfo);
        }).collect(Collectors.toList());
        SysUser requestUser = (SysUser) map.get(SystemConstant.USER);
        rtzfApiUtils.pushUserBatch(requestUser, rtzfUserInfoList);
        sysUserList = sysUserList
                .stream()
                .peek(e -> e.setRtzfSyncStatus(RtzfSyncStatusEnum.ALREADY_SYNC))
                .collect(Collectors.toList());
        sysUserService.updateBatchById(sysUserList);

        map.put(SystemConstant.SUCCESS, sysUserList.size());
        map.put(SystemConstant.RESULT_ERROR, 0);
        return map;
    }

    @Override
    public Map<String, Object> executeSyncRtzfUserUpdate(Map<String, Object> map) {
        SysUser requestUser = (SysUser) map.get(SystemConstant.USER);
        List<SysUser> sysUserList = sysUserService.list(new QueryWrapper<SysUser>()
                .lambda().eq(SysUser::getRtzfSyncStatus, RtzfSyncStatusEnum.NEED_UPDATE));
        int successCount = 0;
        int errorCount = 0;
        List<String> errorList = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            RtzfResult rtzfResult = null;
            try {
                rtzfResult = sysUserService.rtzfUpdateUser(requestUser, sysUser);
                if (Objects.isNull(rtzfResult)) {
                    errorCount++;
                    throw ExceptionResultEnum.ERROR.exception("用户更新无返回结果");
                }
            } catch (Exception e) {
                log.error("软通智服用户更新接口同步失败 ：用户id : {}", sysUser.getId());
            }
            if (Objects.nonNull(rtzfResult) && !"0".equals(rtzfResult.getCode())) {
                String msg = rtzfResult.getMsg();
                String error = String.format("用户[%s]账号信息更新失败 : [%s]" + sysUser.getRealName(), msg);
                errorList.add(error);
                errorCount++;
            } else {
                successCount++;
            }
        }
        if (CollectionUtils.isNotEmpty(errorList)) {
            throw ExceptionResultEnum.ERROR.exception(String.join("\n", errorList));
        }
        map.put(SystemConstant.SUCCESS, successCount);
        map.put(SystemConstant.RESULT_ERROR, errorCount);
        return map;
    }
}