package com.testor.module.duty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.file.model.dto.FileAjaxDTO;
import com.testor.biz.file.model.dto.FileDTO;
import com.testor.biz.file.service.SysFileService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.api.FileController;
import com.testor.module.duty.dao.TSysDutyLogDao;
import com.testor.module.duty.model.domain.TSysDuty;
import com.testor.module.duty.model.domain.TSysDutyLog;
import com.testor.module.duty.model.domain.TSysDutyMonth;
import com.testor.module.duty.model.domain.TSysTaskWork;
import com.testor.module.duty.model.dto.*;
import com.testor.module.duty.service.DutyService;
import com.testor.module.duty.service.TSysDutyLogService;
import com.testor.module.duty.service.TSysDutyMonthService;
import com.testor.module.duty.service.TSysTaskWorkService;
import com.testor.module.mq.service.WeatherService;
import com.testor.module.mq.vo.WeatherWarnInfoVO;
import com.testor.module.partner.model.domain.TJobAccounting;
import com.testor.module.partner.model.domain.TPartnerOrg;
import com.testor.module.partner.model.domain.TPartnerOrgRes;
import com.testor.module.partner.model.domain.TPartnerStaff;
import com.testor.module.partner.service.TJobAccountingService;
import com.testor.module.partner.service.TPartnerOrgResService;
import com.testor.module.partner.service.TPartnerOrgService;
import com.testor.module.partner.service.TPartnerStaffService;
import com.testor.module.report.service.DutyRecordService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 值班日志Service业务层处理
 *
 * @author testor-framework
 * @date 2022-06-08 14:31:30
 */
@Service
public class TSysDutyLogServiceImpl extends SuperServiceImpl<TSysDutyLogDao, TSysDutyLog> implements TSysDutyLogService {
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TSysDutyLogService tSysDutyLogService;

    @Autowired
    private TSysTaskWorkService tSysTaskWorkService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TSysDutyMonthService tSysDutyMonthService;

    @Autowired
    private TPartnerOrgResService tPartnerOrgResService;

    @Autowired
    private TPartnerOrgService tPartnerOrgService;

    @Autowired
    private TPartnerStaffService tPartnerStaffService;

    @Autowired
    private TJobAccountingService tJobAccountingService;

    @Autowired
    private WeatherService weatherService;


    @Override
    public BaseResponse<Object> getInterestedPerson() {
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        //获取相关方组织负责方，这儿没加状态筛选
        List<TPartnerOrgRes> tPartnerOrgResList = tPartnerOrgResService
                .list(new LambdaQueryWrapper<TPartnerOrgRes>()
                        .eq(TPartnerOrgRes::getOrgId, orgId));
        //获取相关方组织机构，这儿没加状态筛选
        List<TPartnerOrg> tPartnerOrgList = null;
        ArrayList<String> partnerIds = new ArrayList<>();
        for (TPartnerOrgRes tPartnerOrgRes : tPartnerOrgResList) {
            String partnerId = tPartnerOrgRes.getPartnerId();
            partnerIds.add(partnerId);
        }
        QueryWrapper<TPartnerOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", partnerIds);
        queryWrapper.eq("is_blacklist", "0");
        if (partnerIds.size() != 0) {
            tPartnerOrgList = tPartnerOrgService.list(queryWrapper);
        }
        Interested interested = null;
        List<Interested> interesteds = new ArrayList<>();
        //循环相关方添加人员
        if (ObjectHelper.isNotEmpty(tPartnerOrgList)) {
            for (TPartnerOrg tPartnerOrg : tPartnerOrgList) {
                interested = BeanHelper.beanToBean(tPartnerOrg, Interested.class);
                String id = interested.getId();
                QueryWrapper<TPartnerStaff> wrapper = new QueryWrapper<>();
                wrapper.eq("partner_id", id);
                List<TPartnerStaff> list = tPartnerStaffService.list(wrapper);
                interested.setPerson(list);
                interesteds.add(interested);
            }
        }
        BaseResponse<Object> response = new BaseResponse<>();
        response.setData(interesteds);
        return response;
    }

    @Override
    public BaseResponse<Object> getActivityClass(TSysDutyLogParam addRequest) throws Exception {
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        QueryWrapper<TSysDuty> queryWrapper = new QueryWrapper<>();
        String classes = addRequest.getClasses();
        String dutyDate = addRequest.getDutyDate();
        String unitBelong = addRequest.getUnitBelong();
        queryWrapper.eq("duty_date", dutyDate)
                .eq("classes", classes)
                .eq("unit_belong", unitBelong)
                .eq("company_id", loginUser.getOrgId());
        TSysDuty tSysDuty = dutyService.getOne(queryWrapper);
        String refId = tSysDuty.getRefId();
        TSysDutyMonth tSysDutyMonth = tSysDutyMonthService.getById(refId);
        String dateTime = null;
        if (classes.contains("早")) {
            dateTime += " " + tSysDutyMonth.getMorTime();
        }
        if (classes.contains("中")) {
            dateTime += " " + tSysDutyMonth.getNoonTime();
        }
        if (classes.contains("晚")) {
            dateTime += " " + tSysDutyMonth.getLateTime();
        }
        if (classes.contains("全")) {
            dateTime += " " + tSysDutyMonth.getAllTime();
        }
        String[] split = dateTime.split("-");
        String startTime = dutyDate + " " + split[0];
        String endTIme = dutyDate + " " + split[1];
        QueryWrapper<TJobAccounting> wrapper = new QueryWrapper<TJobAccounting>();
        wrapper.between(TJobAccounting.ACC_START_DATE, startTime, endTIme);
        wrapper.eq(TJobAccounting.ORG_ID, loginUser.getOrgId());
        if ("本单位".equals(unitBelong)) {
            wrapper.eq(TJobAccounting.LEASE, 0);
        }
        List<TJobAccounting> tJobAccountingList = tJobAccountingService.list(wrapper);
        BaseResponse<Object> response = new BaseResponse<>();
        response.setData(tJobAccountingList);
        return response;

    }

    @Override
    public BaseResponse<Object> getGuardian() {
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        DeptDto deptDto = BeanHelper.beanToBean(sysOrg, DeptDto.class);

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SysUser.ORG_ID, sysOrg.getOrgId());
        List<SysUser> sysUsers = sysUserService.list(queryWrapper);
        for (SysUser sysUser : sysUsers) {
            sysUser.setLoginPwd("");
        }
        deptDto.setUsers(sysUsers);
        baseResponse.setData(deptDto);
        return baseResponse;
    }

    @Override
    public BaseResponse<Object> addEntity(TSysDutyLogParam addRequest) throws Exception {
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        QueryWrapper<TSysDuty> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("duty_date", addRequest.getDutyDate())
                .eq("classes", addRequest.getClasses())
                .eq("unit_belong", addRequest.getUnitBelong())
                .eq("company_id", loginUser.getOrgId())
                .eq("user_id", loginUser.getUserId());
        TSysDuty one = dutyService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException("当前登录人没有值班记录");
        }
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        //不是危险作业活动的id
        //String noRiskJob = addRequest.getNoRiskJob();
        //List<String> list = Arrays.asList(noRiskJob.split(","));
        //for (String s : list) {
            //TSysTaskWork tSysTaskWork = tSysTaskWorkService.getById(s);
//            if (tSysTaskWork.getCause() == null) {
//                TSysTaskWork taskWork = new TSysTaskWork();
//                taskWork.setId(tSysTaskWork.getId());
//                taskWork.setActiveCategory(tSysTaskWork.getActiveCategory());
//                baseResponse.setData(taskWork);
//                return baseResponse;
//            }
        //}

        if (ObjectHelper.isNotEmpty(addRequest)) {

            String id = IdHelper.getId32bit();
            TSysDutyLog data = BeanHelper.beanToBean(addRequest, TSysDutyLog.class);
            data.setCompanyId(sysOrg.getOrgId());
            data.setCreateBy(loginUser.getUserId());
            data.setCreateDate(new Date());
            data.setCompanyName(sysOrg.getOrgName());
            data.setDeptName(sysOrg.getOrgName());
            data.setSubmitter(loginUser.getUserName());
            data.setId(id);
            boolean result = this.save(data);
            TSysDuty duty = new TSysDuty();
            if (data.getStatus().equals(BizConstants.STATUS_ENABLE)) {
                duty.setIsCreateLog("1");
            }
            duty.setDutyLogId(id);
            duty.setId(one.getId());
            dutyService.updateById(duty);
            if (result) {
                TSysDutyLog newEntity = new TSysDutyLog();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<ReturnCreateLog> getCreateLogMsg(TSysDutyLogParam addRequest) throws Exception {
        BaseResponse<ReturnCreateLog> response = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        //ToDo  获取天气信息开始
        List<WeatherWarnInfoVO> warnListLog = weatherService.getWarnListLog(addRequest, sysOrg);
        //todo 获取天气信息结束
        ReturnCreateLog returnCreateLog = new ReturnCreateLog();
        if (CollectionUtils.isNotEmpty(warnListLog)) {
            returnCreateLog.setWeatherInfo(warnListLog.get(0).getWarnMessage());
        }else {
            returnCreateLog.setWeatherInfo("无");
        }
        if (ObjectHelper.isNotEmpty(addRequest)) {
            QueryWrapper<TSysDuty> queryWrapper = new QueryWrapper<>();

            queryWrapper.eq("duty_date", addRequest.getDutyDate())
                    .eq("classes", addRequest.getClasses())
                    .eq("unit_belong", addRequest.getUnitBelong())
                    .eq("company_id", loginUser.getOrgId())
                    .ne("status", BizConstants.STATUS_DELETE)
                    .ne("status", "3");
            //获取当前班次的所有值班人员
            List<TSysDuty> sysDutyList = dutyService.list(queryWrapper);
            for (TSysDuty duty : sysDutyList) {
                //控制只有本班值班人员能创建值班日志
                if ("1".equals(duty.getIsCreateLog())) {
                    throw new BusinessException("值班日志已创建，其他人员无法上传本班日志");
                }
                if ("1".equals(duty.getIsLeader())) {
                    returnCreateLog.setLeaderName(duty.getName());
                }
            }
            //判断是否是领导创建日志
            queryWrapper
                    .eq("company_id", loginUser.getOrgId())
                    .eq("user_id", loginUser.getUserId())
                    .eq("duty_date", addRequest.getDutyDate())
                    .eq("unit_belong", addRequest.getUnitBelong())
                    .eq("classes", addRequest.getClasses())
                    .ne("status", BizConstants.STATUS_DELETE);
            TSysDuty sysDuty = dutyService.getOne(queryWrapper);
            if (sysDuty == null) {
                throw new BusinessException("当前登录人没有值班记录");
            }
            //======确定上个班的日志=====

            // 获取当前日期前一天的日期
//            LocalDate localDate = LocalDate.now().minusDays(1);
            //获取指定日期的前一天
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate parse = LocalDate.parse(addRequest.getDutyDate(), fmt);
            LocalDate localDate = parse.minusDays(1);



            QueryWrapper<TSysDuty> query = new QueryWrapper<>();
            query.between("duty_date", localDate.toString(), addRequest.getDutyDate())
                    .eq("company_id", loginUser.getOrgId())
                    .eq("unit_belong", addRequest.getUnitBelong());
            //获取当前天和前一天的所有值班信息
            List<TSysDuty> listDutyTwoDay = dutyService.list(query);
            //按照值班日期升序排序后的数据
            List<TSysDuty> collect = listDutyTwoDay.stream().sorted(Comparator.comparing(p -> p.getDutyDate())).collect(Collectors.toList());
            // 按照值班日期+值班模式分组
            Map<String, List<TSysDuty>> dutyGroup = collect.stream().collect(Collectors.groupingBy(p -> p.getDutyDate() + p.getClasses()));
            //拼接当前值班日期和值班模式用于确定上一个班次
            String dutyClass = addRequest.getDutyDate() + addRequest.getClasses();
            //获取所有key的集合（dutyDate+classes）
            List<String> dutyClassList = dutyGroup.keySet().stream().collect(Collectors.toList());
            //拿到当前班次的上一个班次
            String dutyDateClassesKey = "";
            for (int i = 0; i < dutyClassList.size(); i++) {
                if (dutyClass.equals(dutyClassList.get(i))) {
                    if (i != 0) {
                        dutyDateClassesKey = dutyClassList.get(i - 1);
                    }
                }
            }
            //获取上一个班次的所有值班人员
            List<TSysDuty> tSysDuties = null;
            if (!("".equals(dutyDateClassesKey))) {
                tSysDuties = dutyGroup.get(dutyDateClassesKey);
            }
            //返回上一个班次遗留问题
            String logHandoverIssue = returnHandoverIssue(tSysDuties);
            returnCreateLog.setPreHandoverIssue(logHandoverIssue);
            //=========

            returnCreateLog.setDutyDate(sysDuty.getDutyDate());
            String week = DutyRecordService.getWeek(sysDuty.getDutyDate());
            String timeFrame = null;
            if (week.equals("星期六") || week.equals("星期日")) {
                timeFrame = "节假日";
            } else {
                timeFrame = "工作日";
            }
            returnCreateLog.setTimeFrame(timeFrame);
            returnCreateLog.setIsLeader(sysDuty.getIsLeader());
            if (sysDuty.getIsLeader() == null) {
                returnCreateLog.setIsLeader("0");
            }

        }
        response.setData(returnCreateLog);
        return response;
    }

    private String returnHandoverIssue(List<TSysDuty> tSysDuties) {
        String handoverIssue = "";
        if (tSysDuties != null) {
            String dutyLogId = "";
            for (TSysDuty tSysDuty : tSysDuties) {
                if ("1".equals(tSysDuty.getIsCreateLog())) {
                    dutyLogId = tSysDuty.getDutyLogId();
                }
            }
            TSysDutyLog tSysDutyLog = tSysDutyLogService.getById(dutyLogId);
            if (tSysDutyLog != null) {
                handoverIssue = tSysDutyLog.getHandoverIssue();
            }
        }
        return handoverIssue;
    }

    @Override
    public BaseResponse<DutyLogDetail> getByIds(String id) {
        BaseResponse<DutyLogDetail> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TSysDutyLog data = this.getById(id);
            if (data==null) {
                return baseResponse;
            }
            DutyLogDetail dutyLogDetail = BeanHelper.beanToBean(data, DutyLogDetail.class);
            String[] split = null;
            if (StringUtils.isNotBlank(dutyLogDetail.getJobId())) {
                split = dutyLogDetail.getJobId().split(",");
            }
            List<TSysTaskWork> taskWorks = new ArrayList<>();
            if (ObjectHelper.isNotEmpty(split)) {
                for (String s : split) {
                    TSysTaskWork taskWork = tSysTaskWorkService.getById(s);
                    taskWorks.add(taskWork);
                }
            }
            dutyLogDetail.setTaskWorks(taskWorks);

            baseResponse.setData(dutyLogDetail);
        }
        return baseResponse;
    }

    @Autowired
    private TSysTaskWorkService TSysTaskWorkService;

//    @Autowired
//    private SysFileController sysFileController;

    @Autowired
    private FileController fileController;

    @Override
    @Transactional
    public BaseResponse<Object> addEntityAndTask(TSysDutyLogParam addRequest) throws Exception {
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        String substring = addRequest.getClasses().substring(0, 2);
        QueryWrapper<TSysDuty> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("duty_date", addRequest.getDutyDate())
                .eq("classes", substring)
                .eq("unit_belong", addRequest.getUnitBelong())
                .eq("company_id", loginUser.getOrgId())
                .eq("user_id", loginUser.getUserId())
                .ne("status", BizConstants.STATUS_DELETE);
        TSysDuty one = dutyService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException("当前登录人没有值班记录");
        }
        BaseResponse<Object> baseResponse = new BaseResponse<>();

        QueryWrapper<TSysDuty> Wrapper = new QueryWrapper<>();

        Wrapper.eq("duty_date", addRequest.getDutyDate())
                .eq("classes", substring)
                .eq("unit_belong", addRequest.getUnitBelong())
                .eq("company_id", loginUser.getOrgId())
                .ne("status", BizConstants.STATUS_DELETE);
        // 交班领导
        String handoverLeader = "";
        //获取当前班次的所有值班人员
        List<TSysDuty> sysDutyList = dutyService.list(Wrapper);
        for (TSysDuty duty : sysDutyList) {
            // 获取交班领导
            if ("1".equals(duty.getIsLeader())) {
                handoverLeader = duty.getUserId();
            }
            //控制只有本班值班人员能创建值班日志
            if ("1".equals(duty.getIsCreateLog()) && StringUtils.isBlank(addRequest.getId()) && addRequest.getStatus().equals(BizConstants.STATUS_ENABLE)) {
                throw new BusinessException("值班日志已创建，请勿重复创建");
            }
        }
        //处理领导签字base64照片==
        String handoverSign = addRequest.getHandoverSign();
        String fileId = null;
        if (StringHelper.isNotEmpty(handoverSign) && (handoverSign.contains("data:image/png;base64,") || handoverSign.contains("data:image/svg+xml;base64,"))) {
            if (!"".equals(handoverSign)) {
                String fileName = "";
                FileAjaxDTO fileAjaxDTO = new FileAjaxDTO();
                fileAjaxDTO.setFile(handoverSign);
                String str = "";
                if (handoverSign.contains("data:image/png;base64,")) {
                    fileName = "交班领导签字_" + System.currentTimeMillis() + ".png";
                    str = handoverSign.replace("data:image/png;base64,", "");
                } else if (handoverSign.contains("data:image/svg+xml;base64,")) {
                    fileName = "交班领导签字_" + System.currentTimeMillis() + ".svg";
                    str = handoverSign.replace("data:image/svg+xml;base64,", "");
                }
                fileAjaxDTO.setFileName(fileName);
                int i = str.indexOf("=");
                if (str.indexOf("=") > 0) {
                    str = str.substring(0, i);
                }
                int length = str.length();
                int i1 = length - (length / 8) * 2;
                String s = String.valueOf(i1);
                fileAjaxDTO.setFileSize(s);
                BaseResponse<FileDTO> fileDTOBaseResponse = fileController.uploadBase64(fileAjaxDTO);
                fileId = fileDTOBaseResponse.getData().getFilePath();
            }
        }

        //===

        //添加作业活动
        List<TSysTaskWork> taskWorks = addRequest.getTaskWorks();
        List<String> taskIds = new ArrayList<>();
        for (TSysTaskWork taskWork : taskWorks) {
            String taskId = TSysTaskWorkService.addEntity(taskWork);
            taskIds.add(taskId);
        }

        if (ObjectHelper.isNotEmpty(addRequest)) {
            String id = addRequest.getId();
            if (StringHelper.isEmpty(id)) {
                id = IdHelper.getId32bit();
            }
            TSysDutyLog data = BeanHelper.beanToBean(addRequest, TSysDutyLog.class);
            // 保存交班领导签字id
            data.setHandoverSign(fileId);
            data.setCompanyId(sysOrg.getOrgId());
            data.setCreateBy(loginUser.getUserId());
            data.setCreateDate(new Date());
            data.setCompanyName(sysOrg.getOrgName());
            data.setDeptName(sysOrg.getOrgName());
            data.setProcessStatus("3");
            data.setSubmitter(loginUser.getUserName());
            data.setClasses(addRequest.getClasses());
            data.setJobId(String.join(",", taskIds));
            data.setId(id);
            boolean result = this.saveOrUpdate(data);
            TSysDuty duty = new TSysDuty();
            if (data.getStatus().equals(BizConstants.STATUS_ENABLE)) {
                duty.setIsCreateLog("1");
            }
            duty.setDutyLogId(id);
            duty.setId(one.getId());
            dutyService.updateById(duty);
            // ==============
            //获取指定日期的后一天
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate parse = LocalDate.parse(addRequest.getDutyDate(), fmt);
            LocalDate localDate = parse.plusDays(1);
            QueryWrapper<TSysDuty> query = new QueryWrapper<>();
            query.between("duty_date", addRequest.getDutyDate(), localDate.toString())
                    .eq("company_id", loginUser.getOrgId())
                    .ne("status", BizConstants.STATUS_DELETE)
                    .eq("unit_belong", addRequest.getUnitBelong());
            //获取当前天和后一天的所有值班信息
            List<TSysDuty> listDutyTwoDay = dutyService.list(query);
            //按照值班日期升序排序后的数据
            List<TSysDuty> collect = listDutyTwoDay.stream().sorted(Comparator.comparing(p -> p.getDutyDate())).collect(Collectors.toList());
            // 按照值班日期+值班模式分组
            Map<String, List<TSysDuty>> dutyGroup = collect.stream().collect(Collectors.groupingBy(p -> p.getDutyDate() + p.getClasses()));
            //拼接当前值班日期和值班模式用于确定下一个班次
            String dutyClass = addRequest.getDutyDate() + substring;
            //获取所有key的集合（dutyDate+classes）
            List<String> dutyClassList = dutyGroup.keySet().stream().collect(Collectors.toList());
            //获取班次日期
            List<String> dates = collect.stream().collect(Collectors.groupingBy(p -> p.getDutyDate())).keySet().stream().sorted().collect(Collectors.toList());
            //排序模板
            HashMap<String,Integer> sorted= new HashMap<>();
            sorted.put("早",1);
            sorted.put("中",2);
            sorted.put("晚",3);
            sorted.put("全",4);
            //存放排序好的列表
            List<String> atLast = new ArrayList<>();
            //排序
            for (String date : dates) {
                List<String> classes = new ArrayList<>();
                for (String s : dutyClassList) {
                    if (s.contains(date)){
                        classes.add(s);
                    }
                }
                Collections.sort(classes, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        if (o1.contains("早")) {
                            o1 = "早";
                        }
                        if (o1.contains("中")) {
                            o1 = "中";
                        }
                        if (o1.contains("晚")) {
                            o1 = "晚";
                        }
                        if (o1.contains("全")) {
                            o1 = "全";
                        }
                        if (o2.contains("早")) {
                            o2 = "早";
                        }
                        if (o2.contains("中")) {
                            o2 = "中";
                        }
                        if (o2.contains("晚")) {
                            o2 = "晚";
                        }
                        if (o2.contains("全")) {
                            o2 = "全";
                        }
                        int i1 = sorted.get(o1);
                        int i2 = sorted.get(o2);
                        if (i1>i2){
                            return 1;
                        }else if (i1<i2){
                            return -1;
                        }else {
                            return 0;
                        }
                    }
                });
                //存放排序好的列表
                atLast.addAll(classes);
            }
            //拿到当前班次的下一个班次
            String dutyDateClassesKey = "";
            for (int i = 0; i < atLast.size(); i++) {
                if (dutyClass.equals(atLast.get(i))) {
                    if (i < atLast.size() - 1) {
                        dutyDateClassesKey = atLast.get(i + 1);
                    }
                }
            }
            //获取下一个班次的所有值班人员
            List<TSysDuty> tSysDuties = null;
            if (!("".equals(dutyDateClassesKey))) {
                tSysDuties = dutyGroup.get(dutyDateClassesKey);
            }
            //返回接班领导
            String successionLeader = "";
            if (ObjectHelper.isNotEmpty(tSysDuties)) {
                for (TSysDuty tSysDuty : tSysDuties) {
                    if ("1".equals(tSysDuty.getIsLeader())) {
                        successionLeader = tSysDuty.getUserId();
                    }
                }
            }
            //=========
            if (result) {
                DutyHandover dutyHandover = new DutyHandover();
                dutyHandover.setId(id);
                dutyHandover.setClasses(addRequest.getClasses());
                dutyHandover.setDutyDate(addRequest.getDutyDate());
                dutyHandover.setHandoverLeader(handoverLeader);
                dutyHandover.setSuccessionLeader(successionLeader);
                if ("1".equals(one.getIsLeader())) {
                    dutyHandover.setIsLeader(one.getIsLeader());
                } else {
                    dutyHandover.setIsLeader("0");
                }
                baseResponse.setData(dutyHandover);
            }
        }
        return baseResponse;
    }

    @Autowired
    private SysFileService sysFileService;

    @Value("${minio.bucket}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String address;

    private static final Logger log = LoggerFactory.getLogger(TSysDutyLogServiceImpl.class);

    @Autowired
    private MinioClient minioClient;

    private void uploadMinio(InputStream input, String fileName, String contentType) {
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(input, input.available(), -1)
                    .contentType(contentType)
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
