package com.tofly.xrtygis.custom.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.api.UserClent;
import com.tofly.api.message.MessageClient;
import com.tofly.api.message.MessageStateClient;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.JSONUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.pojo.User;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.xrtygis.config.FilePathBean;
import com.tofly.xrtygis.custom.entity.CustomDutyroster;
import com.tofly.xrtygis.custom.entity.CustomRxKnowledge;
import com.tofly.xrtygis.custom.entity.dma.ImportExDuty;
import com.tofly.xrtygis.custom.entity.dma.ImportExDutyExtend;
import com.tofly.xrtygis.custom.entity.enums.GisMessage;
import com.tofly.xrtygis.custom.entity.gs.GsBean;
import com.tofly.xrtygis.custom.entity.gs.Jbgl;
import com.tofly.xrtygis.custom.mapper.CustomGsMapper;
import com.tofly.xrtygis.custom.service.CustomGsService;
import com.tofly.xrtygis.custom.util.DateTimeUtil;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.em.ExcelExportFileTypeEnum;
import com.tofly.xrtygis.entity.*;
import com.tofly.xrtygis.service.*;
import com.tofly.xrtygis.strategy.ExcelStrategyContext;
import com.tofly.xrtygis.util.ExcelUtil;
import lombok.SneakyThrows;
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 org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 供水热线
 *
 * @author FlashWJL
 * @date 2021/3/23 16:36
 */
@Service
public class CustomGsServiceImpl implements CustomGsService {
    @Autowired
    private DutyrosterService dutyrosterService;
    @Autowired
    private FilePathBean filePathBean;
    @Autowired
    private FileService fileService;
    @Autowired
    private RxjbglService jbglService;
    @Autowired
    private RxknowledgeService knowledgeService;
    @Autowired
    private RxwtglService rxwtglService;
    @Autowired
    private UserClent clent;
    @Autowired
    private MessageClient messageClient;
    @Autowired
    private MessageStateClient messageStateClient;
    @Autowired
    private GardetemplateService gardetemplateService;
    @Autowired
    private ExcelStrategyContext excelStrategyContext;
    @Autowired
    private CustomGsMapper customGsMapper;

    @Value("${gsrx.jbgl}")
    private String jbRoute;

    private final static Map<Integer, String> MONTH_MAP = new HashMap<>();

    static {
        MONTH_MAP.put(1, "一月");
        MONTH_MAP.put(2, "二月");
        MONTH_MAP.put(3, "三月");
        MONTH_MAP.put(4, "四月");
        MONTH_MAP.put(5, "五月");
        MONTH_MAP.put(6, "六月");
        MONTH_MAP.put(7, "七月");
        MONTH_MAP.put(8, "八月");
        MONTH_MAP.put(9, "九月");
        MONTH_MAP.put(10, "十月");
        MONTH_MAP.put(11, "十一月");
        MONTH_MAP.put(12, "十二月");

    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public boolean dutymanager(GsBean gsBean) {
        Date time = gsBean.getDutyDate();
        Long dayTimeUser = gsBean.getDaytimeUser();
//        Long dayTimeDept = gsBean.getDaytimeDept();
        Long nightUser = gsBean.getNightUser();
//        Long nightDept = gsBean.getNightDept();

        if (StringUtil.isNull(time)) {
            throw new ToflyDeniedException("请传入工作时间");
        }
        //如果创建的排班时间在当天之前，则不能排班了 (Date8Util.getCurrentDate() , "yyyy-MM-dd");
        Date currentDate = Date8Util.getCurrentDate();
        String currentStr = DateUtil.parseDateToStr("yyyy-MM-dd", currentDate);
        currentDate = DateUtil.formatDate(currentStr, "yyyy-MM-dd");
        if (time.before(currentDate)) {
            throw new ToflyDeniedException("只能对当天之后进行排班");
        }
        //白班  && StringUtil.isNotNull(dayTimeDept)
        if (StringUtil.isNotNull(dayTimeUser)) {
            Dutyroster dutyroster = new Dutyroster();
            dutyroster.setDutyDate(time);
            dutyroster.setDutyUser(dayTimeUser);
            dutyroster.setWorkTime("1");
//            dutyroster.setDeptId(dayTimeDept);
            duty(dutyroster);
        }
        //夜班 && StringUtil.isNotNull(nightDept)
        if (StringUtil.isNotNull(nightUser)) {
            Dutyroster dutyroster = new Dutyroster();
            dutyroster.setDutyDate(time);
            dutyroster.setDutyUser(nightUser);
//            dutyroster.setDeptId(nightDept);
            dutyroster.setWorkTime("2");
            duty(dutyroster);
        }


        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean duty(Dutyroster dutyroster) {
        //创建排班之前需要判断改员工在同一天不能有两次上班、或者休息提醒
        //人员
        Long ryId = dutyroster.getDutyUser();
        //班次
        String workTime = dutyroster.getWorkTime();
        //上班日期
        Date dutyDate = dutyroster.getDutyDate();
        Dutyroster duty = dutyrosterService.getOne(Wrappers.<Dutyroster>lambdaQuery().eq(Dutyroster::getDutyDate, dutyDate)
                .eq(Dutyroster::getDutyUser, ryId));
        if (StringUtil.isNotNull(duty)) {
            //如果该人员有班
            ResultRespone respone = clent.getById(ryId);
            User user = JSONObject.parseObject(JSONObject.toJSONString(respone.getResult()), User.class);

            String date = Date8Util.format(duty.getDutyDate(), "yyyy-MM-dd");
            if ("3".equals(duty.getWorkTime())) {
                throw new ToflyDeniedException("人员" + user.getRealName() + "在" + date + "休息");
            } else if (duty.getWorkTime().equals(workTime)) {
                //如果制定的排班与当前的排班一模一样则提示
                throw new ToflyDeniedException("人员" + user.getRealName() + "在" + date + "上" + duty.getWorkName());
            }
            //直接删除后保存，相当于是修改
            else {
                dutyrosterService.removeById(duty.getId());
            }
        }
        return dutyrosterService.save(dutyroster);
        //未传ID则是新增排班
//        if (StringUtil.isNull(dutyroster.getId())) {
//            return dutyrosterService.save(dutyroster);
//        }
//        else {
//            //传递了ID，则是根据ID修改数据
//            return dutyrosterService.updateById(dutyroster);
//        }
    }

    @Override
    public List<Dutyroster> getDuty(CustomDutyroster dutyroster) {
        List<Long> userId = null;
        if (dutyroster.getDeptId() != null) {
            userId = customGsMapper.getUserId(dutyroster.getDeptId());
        }
        return dutyrosterService.list(Wrappers.<Dutyroster>lambdaQuery()
                .in(userId != null && !userId.isEmpty(), Dutyroster::getDutyUser, userId)
                .le(StringUtil.isNotNull(dutyroster.getEndTime()), Dutyroster::getDutyDate, dutyroster.getEndTime())
                .ge(StringUtil.isNotNull(dutyroster.getStartTime()), Dutyroster::getDutyDate, dutyroster.getStartTime())
                .eq(StringUtil.isNotNull(dutyroster.getDutyUser()), Dutyroster::getDutyUser, dutyroster.getDutyUser())
                .orderByAsc(Dutyroster::getDutyDate));
    }

    @Override
    public List<Dutyroster> dutyMonth(Date month, Long user) {
        String monthStr = DateUtil.parseDateToStr("yyyy-MM", month);
        //获取当月信息
        return dutyrosterService.getByMonth(monthStr, user);
    }

    @Override
    public boolean removeById(Long id) {
        return dutyrosterService.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addHandOver(Rxjbgl jbgl, HttpServletRequest request) {
//        String time=DateUtil.getDateFormat(Date8Util.getCurrentDate(),"yyyy-MM-dd 00:00:00");
//        //当前这个人是白班还是夜班
//        String state = dutyrosterService.getOne(Wrappers.<Dutyroster>lambdaQuery()
//                .eq(Dutyroster::getDutyUser, SecurityUtils.getUserId())
//                .eq(Dutyroster::getDutyDate, time)
//                .select(Dutyroster::getWorkTime)).getWorkTime();
//        //如果是白班人员交班，则查找当天晚班人员
//        if (state.equals("2")){
//            List<Dutyroster> dutyrosterList = dutyrosterService.list(Wrappers.<Dutyroster>lambdaQuery()
//                    .eq(Dutyroster::getDutyDate,time).eq(Dutyroster::getWorkTime,"2"));
//
//        }
//        如果是夜班，则查找第二天的白班人员
//        先查询下一班人员集合
//        然后筛选没有交接的人员

        StringBuilder fileIds = uploadFile("TF_YWPN_RXJBGL_W", request, filePathBean.getJbFile());
        //交班文件
        if (fileIds.length() > 0) {
            jbgl.setFileid(fileIds.substring(0, fileIds.length() - 1));
        }
        Date time = Date8Util.getCurrentDate();
        jbgl.setJbsj(time);

        //如果是重发交接班申请
        Long id = jbgl.getId();
        if (StringUtil.isNotNull(id)) {
            //判断只有交班人员才可以重发交班申请
            Long jjry = SecurityUtils.getUserId();
            if (!jjry.equals(jbgl.getJjry())) {
                throw new ToflyDeniedException("该交班记录只有创建人才可以重发");
            }
            //先移除原来的；再添加
            jbglService.removeById(id);
            //初始化重发
            jbgl.setId(null);
            jbgl.setJjzt("0");
            jbgl.setJbms(null);
            jbgl.setJbbh(null);
            jbgl.setIsmaneger(null);
            //目前没有file
            jbgl.setFileid(null);
        }
        //判断交班人员身份，是否管理人员或者坐席人员
        jbglService.save(jbgl);
        //发送消息给接班人员
        Messagepush messagepush = new Messagepush();
        messagepush.setMessage(jbgl.getJbnr());
        messagepush.setTopic(GisMessage.HAND_OVER.getTopic());
//        messagepush.setTopic(jbgl.getJbnr());
        messagepush.setType(GisMessage.HAND_OVER.getType());
        messagepush.setTableName(GisMessage.HAND_OVER.getTableName());
        messagepush.setRouteIp(jbRoute);
        messagepush.setCreateUser(jbgl.getJjry());
        //消息推送
        Long resultId = messageClient.save(messagepush).getResult();
        //指定消息接收人
        Messagerecipient messagerecipient = new Messagerecipient();
        messagerecipient.setMessageId(resultId);
        messagerecipient.setRecipient(jbgl.getJbry());
        messageStateClient.save(messagerecipient);
        return true;
    }

    @Override
    public IPage<Rxjbgl> getHandOver(Page page, HttpServletResponse response, Jbgl jbgl, String templateFlag) {
        Long userId = SecurityUtils.getUserId();
        Date startTime = jbgl.getStartTime();
        Date endTime = jbgl.getEndTime();


//这里应该有角色配置，比如是管理员；则可以查看所有的排班
//         = SecurityUtils.getRoles();

        IPage<Rxjbgl> rxjbglList = jbglService.page(page, Wrappers.<Rxjbgl>lambdaQuery().and(w -> w.eq(Rxjbgl::getJbry, userId).or()
                .eq(Rxjbgl::getJjry, userId))
                .between(StringUtil.isNotNull(endTime), Rxjbgl::getJbsj, startTime, endTime)
                .orderByDesc(Rxjbgl::getJbsj));


        if ("1".equals(templateFlag)) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("exportHandOverService", templateFlag);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONStringWithDateFormat(rxjbglList.getRecords(), "yyyy-MM-dd HH:mm:ss");
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("exportHandOverService", templateFlag, resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        }

        return rxjbglList;
    }

    @Override
    public boolean updateHandOver(Rxjbgl jbgl) {
        //判断；必须是接班人才可以对当前交班记录操作
        Long currentUser = SecurityUtils.getUserId();
        Rxjbgl rxjbgl = jbglService.getOne(Wrappers.<Rxjbgl>lambdaQuery().eq(Rxjbgl::getId, jbgl.getId()).select(Rxjbgl::getJbry, Rxjbgl::getId));
        Long jbry = rxjbgl.getJbry();
        String jbryName = rxjbgl.getJbryName();
        if (!currentUser.equals(jbry)) {
            throw new ToflyDeniedException("只有" + jbryName + "才可以操作自己的接班记录");
        }
        //如果是接班人员拒绝，则必须填写描述
        if (jbgl.getJjzt().equals("2")) {
            if (StringUtil.isEmpty(jbgl.getJbms())) {
                throw new ToflyDeniedException("请接班人员填写描述");
            }
        }
        if (jbgl.getJjzt().equals("0")) {
            throw new ToflyDeniedException("请正确输入");
        }

        Rxjbgl byId = jbglService.getById(jbgl.getId());

        if (!StringUtils.isEmpty(byId.getJbgd())) {
            customGsMapper.updateGdInfo(byId.getJbry(), Arrays.asList(byId.getJbgd().split(",")));
        }

        return jbglService.update(Wrappers.<Rxjbgl>lambdaUpdate().eq(Rxjbgl::getId, jbgl.getId())
                .set(Rxjbgl::getJjzt, jbgl.getJjzt()).set(StringUtil.isNotEmpty(jbgl.getJbms()), Rxjbgl::getJbms, jbgl.getJbms()));
    }

    @Override
    public boolean updateHandOverTwo(Rxjbgl jbgl) {
        Long id = jbgl.getId();
        Long jbry = jbgl.getJbry();
        String jbnr = jbgl.getJbnr();
        String jbtxqk = jbgl.getJbtxqk();
        String jbzysx = jbgl.getJbzysx();
        String jbbghj = jbgl.getJbbghj();
        String jbgd = jbgl.getJbgd();
        String jbms = jbgl.getJbms();
        if (StringUtil.isNull(id)) {
            throw new ToflyDeniedException("请传入交班ID");
        }
        jbglService.update(Wrappers.<Rxjbgl>lambdaUpdate().eq(Rxjbgl::getId, id)
                .set(StringUtil.isNotNull(jbry), Rxjbgl::getJbry, jbry).set(StringUtil.isNotEmpty(jbnr), Rxjbgl::getJbnr, jbnr)
                .set(StringUtil.isNotEmpty(jbtxqk), Rxjbgl::getJbtxqk, jbtxqk).set(StringUtil.isNotEmpty(jbzysx), Rxjbgl::getJbzysx, jbzysx)
                .set(StringUtil.isNotEmpty(jbbghj), Rxjbgl::getJbbghj, jbbghj).set(StringUtil.isNotEmpty(jbgd), Rxjbgl::getJbgd, jbgd)
                .set(StringUtil.isEmpty(jbnr), Rxjbgl::getJbnr, "").set(StringUtil.isEmpty(jbtxqk), Rxjbgl::getJbtxqk, "")
                .set(StringUtil.isEmpty(jbzysx), Rxjbgl::getJbzysx, "").set(StringUtil.isEmpty(jbbghj), Rxjbgl::getJbbghj, "")
                .set(StringUtil.isEmpty(jbgd), Rxjbgl::getJbgd, "")
                //如果
                .set(Rxjbgl::getJjzt, "0"));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addKnowledge(Rxknowledge rxknowledge, HttpServletRequest request) {

        StringBuilder fileIds = uploadFile("TF_YWPN_RXKNOWLEDGE_W", request, filePathBean.getKnowledgeFile());
        if (fileIds.length() > 0) {
            rxknowledge.setFileid(fileIds.substring(0, fileIds.length() - 1));
        }
        //判断有没有父级标题
        if (StringUtil.isNotNull(rxknowledge.getPid())) {
            //查询父级
            Rxknowledge kn = knowledgeService.getOne(Wrappers.<Rxknowledge>lambdaQuery()
                    .eq(Rxknowledge::getId, rxknowledge.getPid()).select(Rxknowledge::getId));
            if (StringUtil.isNull(kn)) {
                throw new ToflyDeniedException("错误,没有该父级");
            }
            //判断该父级下面有没有同名知识库
            Rxknowledge knName = knowledgeService.getOne(Wrappers.<Rxknowledge>lambdaQuery().eq(Rxknowledge::getTitle, rxknowledge.getTitle())
                    .eq(Rxknowledge::getPid, rxknowledge.getPid()).select(Rxknowledge::getId, Rxknowledge::getTitle));
            if (StringUtil.isNotNull(knName)) {
                throw new ToflyDeniedException("存在相同知识库标题：:" + rxknowledge.getTitle());
            }
        } else {
            //没有父级时，判断有没有同名知识库
            Rxknowledge knName = knowledgeService.getOne(Wrappers.<Rxknowledge>lambdaQuery().eq(Rxknowledge::getTitle, rxknowledge.getTitle())
                    .select(Rxknowledge::getId, Rxknowledge::getTitle));
            if (StringUtil.isNotNull(knName)) {
                throw new ToflyDeniedException("存在相同知识库标题：:" + rxknowledge.getTitle());
            }
        }
        return knowledgeService.save(rxknowledge);
    }

    /**
     * 文件上传管理
     *
     * @param tableName
     * @param request
     * @return
     */
    public StringBuilder uploadFile(String tableName, HttpServletRequest request, String filePathBean) {
        //可以考虑将文件上传这一代码抽离出来公共使用
        MultiValueMap<String, MultipartFile> files = ((MultipartHttpServletRequest) request).getMultiFileMap();
        StringBuilder fileIds = new StringBuilder("");
        files.forEach((k, v) -> {
            //保存照片
            v.forEach(file -> {
                //文件名
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName)) {
                    //文件路径
                    String filePath = filePathBean + IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf("."));
                    boolean b = FtpUtil.uploadFile2Ftp(file, filePath);
                    if (b) {
                        File localFile = new File();
                        localFile.setFilePath(filePath);
                        localFile.setFileName(fileName);
                        localFile.setOtherName(IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(".")));
                        localFile.setTableName(tableName);//关联表名称
                        //获取后缀
                        String suffix = fileName.substring(fileName.lastIndexOf("."));
                        localFile.setFileFormat(suffix);
                        localFile.setFileSize(file.getSize() + "kb");
                        fileService.save(localFile);
                        //获得文件ID
                        fileIds.append(localFile.getId() + ",");
                    }
                }
            });
        });
        return fileIds;
    }

    @Override
    public List<CustomRxKnowledge> getKnowledge() {
        List<Rxknowledge> rxknowledges = knowledgeService.list();
        //集合转json字符串，然后字符串再转bean集合
        List<CustomRxKnowledge> customList = JSONObject.parseArray(JSONObject.toJSONString(rxknowledges), CustomRxKnowledge.class);
        //生成树结构；参数说明：目录数据集合、目录ID、父级目录ID、子目录集合
        List<CustomRxKnowledge> list = JSONUtil.parTree(customList, CustomRxKnowledge::getId, CustomRxKnowledge::getPid, CustomRxKnowledge::getList);
        return list;
    }

    /**
     * 暂时还没有删除服务器上面的文件，
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delKnowledge(Long id) {
        //查询该ID的知识库下面有没有子级，先删子级
        List<Rxknowledge> list = knowledgeService.list(Wrappers.<Rxknowledge>lambdaQuery().eq(Rxknowledge::getPid, id).select(Rxknowledge::getId));
        //如果没有子级
        if (list.size() > 0) {
            delete(list);
        }
        //查询文件ID
        Rxknowledge file = knowledgeService.getOne(Wrappers.<Rxknowledge>lambdaQuery().eq(Rxknowledge::getId, id).select(Rxknowledge::getFileid));
        if (StringUtil.isNotNull(file)) {
            List<Long> fileIds = Arrays.asList(file.getFileid().split(",")).stream().map(k -> Long.parseLong(k.trim())).collect(Collectors.toList());
            //查询文件路径
            List<String> filePath = fileService.list(Wrappers.<File>lambdaQuery().in(File::getId, fileIds).select(File::getFilePath)).stream().map(File::getFilePath).collect(Collectors.toList());
            //删除文件表数据
            fileService.removeByIds(fileIds);
            //删除服务器文件
            filePath.forEach(k -> {
                FtpUtil.deleteFile(k);
            });
        }
        knowledgeService.removeById(id);
        //暂时还没有删除文件
//        FtpUtil.deleteFile();
        return true;
    }

    /**
     * 利用递归删除
     *
     * @param list
     * @return
     */
    public boolean delete(List<Rxknowledge> list) {
        List<Long> ids = list.stream().map(Rxknowledge::getId).collect(Collectors.toList());
        List<Rxknowledge> rxknowledgeList = knowledgeService.list(Wrappers.<Rxknowledge>lambdaQuery()
                .in(Rxknowledge::getPid, ids).select(Rxknowledge::getId));
        //查询文件ID
        List<Rxknowledge> rxknowledges = knowledgeService.list(Wrappers.<Rxknowledge>lambdaQuery().in(Rxknowledge::getId, ids).select(Rxknowledge::getFileid));
        if (StringUtil.isNotNull(rxknowledges)) {
            List<String> strFileIdList = rxknowledges.stream().filter(StringUtil::isNotNull).map(Rxknowledge::getFileid).collect(Collectors.toList());
            strFileIdList.forEach(k -> {
                List<Long> fileIds = Arrays.stream(k.split(",")).map(l -> Long.parseLong(l.trim())).collect(Collectors.toList());
                //查询文件路径
                List<String> filePath = fileService.list(Wrappers.<File>lambdaQuery().in(File::getId, fileIds).select(File::getFilePath)).stream().map(File::getFilePath).collect(Collectors.toList());
                //删除文件表数据
                fileService.removeByIds(fileIds);
                //删除服务器文件
                filePath.forEach(FtpUtil::deleteFile);
            });
        }
        knowledgeService.removeByIds(ids);
        for (int i = 0; i < rxknowledgeList.size(); i++) {
            delete(rxknowledgeList);
        }
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateKnowledge(Rxknowledge rxknowledge, HttpServletRequest request) {
        //查询文件path
        Rxknowledge knowledgeServiceOne = knowledgeService.getOne(Wrappers.<Rxknowledge>lambdaQuery().eq(Rxknowledge::getId, rxknowledge.getId()).select(Rxknowledge::getFileid));

        //知识库的文件上传
        StringBuilder fileIds = uploadFile("TF_YWPN_RXKNOWLEDGE_W", request, filePathBean.getKnowledgeFile());

        if (fileIds.length() > 0) {
            if (StringUtil.isNull(knowledgeServiceOne)) {
                //如果原有文件为空，则直接设置
                rxknowledge.setFileid(fileIds.substring(0, fileIds.length() - 1));
            } else {
                //直接拼接文件ID，修改中新增文件
                rxknowledge.setFileid(fileIds.append(knowledgeServiceOne.getFileid()).toString());
            }
        }
        Long pid = rxknowledge.getPid();
        String titile = rxknowledge.getTitle();
        String content = rxknowledge.getContent();
        Long user = SecurityUtils.getUserId();
        Date time = Date8Util.getCurrentDate();
        String yxbz = rxknowledge.getYxbz();

        if (StringUtil.isEmpty(content)) {
            knowledgeService.update(Wrappers.<Rxknowledge>lambdaUpdate().eq(Rxknowledge::getId, rxknowledge.getId())
                    .set(StringUtil.isNotNull(pid), Rxknowledge::getPid, pid).set(StringUtil.isNotEmpty(titile), Rxknowledge::getTitle, titile)
                    .set(Rxknowledge::getContent, "").set(StringUtil.isNotEmpty(yxbz), Rxknowledge::getYxbz, yxbz)
                    .set(StringUtil.isNotEmpty(rxknowledge.getFileid()), Rxknowledge::getFileid, rxknowledge.getFileid()));
        } else {
            //修改
            knowledgeService.update(Wrappers.<Rxknowledge>lambdaUpdate().eq(Rxknowledge::getId, rxknowledge.getId())
                    .set(StringUtil.isNotNull(pid), Rxknowledge::getPid, pid).set(StringUtil.isNotEmpty(titile), Rxknowledge::getTitle, titile)
                    .set(Rxknowledge::getContent, content).set(StringUtil.isNotEmpty(yxbz), Rxknowledge::getYxbz, yxbz)
                    .set(StringUtil.isNotEmpty(rxknowledge.getFileid()), Rxknowledge::getFileid, rxknowledge.getFileid()));
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delKnowledgePic(Long id, String filePath) {
        //格式化filePath
        List<String> pathList = Arrays.asList(filePath.split(","));
        //删除服务器文件
        pathList.forEach(FtpUtil::deleteFile);
        //查询出要删除的文件ID
        List<Long> delFileIds = fileService.list(Wrappers.<File>lambdaQuery().in(File::getFilePath, pathList).select(File::getId)).stream().map(File::getId).collect(Collectors.toList());
        //删除的文件ID转map
        Map<String, Long> mapfileIds = delFileIds.stream().collect(Collectors.toMap(String::valueOf, m -> m));
        //删除数据库文件记录数据
        fileService.remove(Wrappers.<File>lambdaQuery().in(File::getId, delFileIds));
        //知识库原有的文件ID
        List<String> fileidList = Arrays.asList(knowledgeService.getOne(Wrappers.<Rxknowledge>lambdaQuery().eq(Rxknowledge::getId, id)
                .select(Rxknowledge::getFileid)).getFileid().split(","));
        //过滤出不被删除的文件ID
        List<String> saveFileIds = fileidList.stream().filter(k -> mapfileIds.get(k) == null).collect(Collectors.toList());
        if (saveFileIds.size() > 0) {
            String fileis = StringUtil.join(saveFileIds, ",");
            knowledgeService.update(Wrappers.<Rxknowledge>lambdaUpdate().eq(Rxknowledge::getId, id).set(Rxknowledge::getFileid, fileis));
        } else {
            knowledgeService.update(Wrappers.<Rxknowledge>lambdaUpdate().eq(Rxknowledge::getId, id).set(Rxknowledge::getFileid, ""));
        }
        return true;
    }

    @Override
    public boolean gradeTemplate(Gardetemplate gardetemplate) {
        Long id = gardetemplate.getId();
        if (StringUtil.isNull(id)) {
            throw new ToflyDeniedException("ID必传");
        }
        Integer fwzc = gardetemplate.getFwzc();
        Integer zzkg = gardetemplate.getZzkg();
        Integer fwyy = gardetemplate.getFwyy();
        Integer yyyd = gardetemplate.getYyyd();
        Integer khgx = fwzc + zzkg + fwyy + yyyd;
        if (khgx.intValue() > 30) {
            throw new ToflyDeniedException("建立良好客户关系总分数不能超过30分");
        }
        Integer jdwz = gardetemplate.getJdwz();
        Integer jdzq = gardetemplate.getJdzq();
        Integer ywzs = jdwz + jdzq;
        if (ywzs.intValue() > 20) {
            throw new ToflyDeniedException("业务知识总分数不能超过30分");
        }
        Integer qtlj = gardetemplate.getQtlj();
        Integer xxsj = gardetemplate.getXxsj();
        Integer xxqr = gardetemplate.getXxqr();
        Integer dhjq = gardetemplate.getDhjq();
        Integer gtnl = qtlj + xxsj + xxqr + dhjq;
        if (gtnl.intValue() > 30) {
            throw new ToflyDeniedException("沟通能力总分数不能超过30分");
        }
        Integer zlk = gardetemplate.getZlk();
        Integer lcgf = gardetemplate.getLcgf();
        Integer zxnl = zlk + lcgf;
        if (zxnl.intValue() > 20) {
            throw new ToflyDeniedException("执行能力总分数不能超过30分");
        }
        gardetemplateService.updateById(gardetemplate);
        return true;
    }

    @Override
    public Gardetemplate getGradeTemplate() {
        return gardetemplateService.list().get(0);
    }

    @Override
    public boolean importDutyManagerInfo(MultipartFile file) {
        if (StringUtil.isNull(file)) {
            throw new ToflyDeniedException("上传文件为空");
        }
//        DateTime date = cn.hutool.core.date.DateUtil.date();
//        int month = cn.hutool.core.date.DateUtil.month(date) + 1;
        MONTH_MAP.forEach((k, v) -> {
            importDuty(file, MONTH_MAP.get(k));
//            if (MONTH_MAP.containsKey(month)) {
//                if (k >= month) {
//                    importDuty(file, MONTH_MAP.get(k));
//                }
//            }
        });
        return true;
    }


    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public void importDuty(MultipartFile file, String sheetName) {
        InputStream inputStream = file.getInputStream();
        Map<Long, User> usermap = new HashMap<>();
        List<String> keyus = new ArrayList<>();
        Long maxId = dutyrosterService.getMaxId();
        Long row = maxId == null ? 0 : maxId;
        com.tofly.common.core.util.io.ExcelUtil opsExcel = new com.tofly.common.core.util.io.ExcelUtil(ImportExDutyExtend.class);
        List<ImportExDutyExtend> ips = opsExcel.importExcel(sheetName, inputStream);
        Date dt = Date.from(DateTimeUtil.getTodayBeginTime().atZone(ZoneId.systemDefault()).toInstant());
        if (ips == null || ips.size() <= 1) {
            throw new ToflyDeniedException("数据为空！");
        }

        Set<Date> delDate = new HashSet<>();
        List<ImportExDuty> resultDuty = new ArrayList<>();
        ImportExDuty ie = null;
        for (ImportExDutyExtend v : ips) {
            //跳过第一条数据
            if (ips.get(0) == v) {
                continue;
            }
            //去空
            if (!StringUtils.isEmpty(v.getDutyUser()) || !StringUtils.isEmpty(v.getDutyUser1())) {
//                if ("0".equals(ie.getWorkTime())) {
////                    throw new ToflyDeniedException("工作时段错误!序号:" + v.getExId());
////                } else
                if (v.getDutyDate() == null) {
                    throw new ToflyDeniedException("工作日期为空!序号:" + v.getExId());
                }
//                else if (v.getDutyDate().getTime() < dt.getTime()) {
//                    throw new ToflyDeniedException("工作日期小于当前时间!序号:" + v.getExId());
//                }
                String uk = v.getDutyUser() + "_" + DateTimeUtil.getLocalDate(v.getDutyDate(), DateTimeUtil.DAY_FORMAT);
                if (keyus.contains(uk)) {
                    throw new ToflyDeniedException("!序号:" + v.getExId());
                } else {
                    keyus.add(uk);
                }
                //白班
                User user1;
                Long dutyUser = v.getDutyUser();

                if (usermap.containsKey(dutyUser)) {
                    user1 = usermap.get(dutyUser);
                } else {
                    user1 = clent.getById(dutyUser).getResult();
                    usermap.put(dutyUser, user1);
                }
                if (v.getDutyUser() == null || user1 == null) {
                    throw new ToflyDeniedException("白班用户编号ID有为空或白班用户编号ID错误!序号:" + v.getExId() + ";Sheet:" + sheetName);
                }
                //夜班
                User user2;
                Long dutyUser1 = v.getDutyUser1();

                if (usermap.containsKey(dutyUser1)) {
                    user2 = usermap.get(v.getDutyUser1());
                } else {
                    user2 = clent.getById(v.getDutyUser1()).getResult();
                    usermap.put(v.getDutyUser1(), user2);
                }

                if (v.getDutyUser1() == null || user2 == null) {
                    throw new ToflyDeniedException("夜班用户编号ID有为空或夜班用户编号ID错误!序号:" + v.getExId() + ";Sheet:" + sheetName);
                }

                if (dutyUser != null) {
                    ie = new ImportExDuty();
                    ie.setWorkTime("1")
                            .setCreateUser(SecurityUtils.getUserId())
                            .setCreateTime(new Date())
                            .setId(row + 1)
                            .setDutyUser(dutyUser)
                            .setDutyDate(v.getDutyDate());

                    delDate.add(v.getDutyDate());
                    resultDuty.add(ie);
                    row++;
                }
                if (dutyUser1 != null) {
                    ie = new ImportExDuty();
                    ie.setWorkTime("2")
                            .setCreateUser(SecurityUtils.getUserId())
                            .setCreateTime(new Date())
                            .setId(row + 1)
                            .setDutyUser(dutyUser1)
                            .setDutyDate(v.getDutyDate());

                    delDate.add(v.getDutyDate());
                    resultDuty.add(ie);
                    row++;
                }
            }
        }
        if (!resultDuty.isEmpty()) {
            dutyrosterService.remove(new QueryWrapper<Dutyroster>().lambda().in(!delDate.isEmpty(), Dutyroster::getDutyDate, delDate));
            dutyrosterService.saveDutyrosters(resultDuty);
        }

    }

    @Override
    public List<Rxknowledge> getKnowledgeByTitle(String title) {
        return knowledgeService.list(Wrappers.<Rxknowledge>lambdaQuery().like(Rxknowledge::getTitle, title));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProlem(Rxwtgl wtgl, HttpServletRequest request) {
        StringBuilder fileIds = uploadFile("TF_YWPN_RXWTGL_W", request, filePathBean.getKnowledgeFile());
        if (fileIds.length() > 0) {
            wtgl.setFileid(fileIds.toString());
        }
        wtgl.setSfhf("0");
        rxwtglService.save(wtgl);
        return true;
    }

    /**
     * 回复问题
     *
     * @param wtgl 问题管理
     * @return boolean
     */
    @Override
    public boolean replyProlem(Rxwtgl wtgl) {
        if (wtgl.getId() == null) {
            throw new ToflyDeniedException("问题id不能为空");
        }
        return rxwtglService.update(Wrappers.<Rxwtgl>lambdaUpdate()
                .eq(Rxwtgl::getId, wtgl.getId())
                .set(Rxwtgl::getSfhf, "1")
                .set(Rxwtgl::getHfry, SecurityUtils.getUserId())
                .set(Rxwtgl::getHfnr, wtgl.getHfnr())
                .set(Rxwtgl::getHfsj, new Date()));
    }

    @Override
    public IPage getProblem(Rxwtgl wtgl, Page page) {
        return rxwtglService.page(page, Wrappers.<Rxwtgl>lambdaQuery()
                .orderByAsc(Rxwtgl::getShbz).orderByAsc(Rxwtgl::getSfrk)
                .orderByDesc(Rxwtgl::getCreateDate)
                .like(StringUtil.isNotEmpty(wtgl.getBtmc()), Rxwtgl::getBtmc, wtgl.getBtmc())
                .like(StringUtil.isNotEmpty(wtgl.getWtms()), Rxwtgl::getWtms, wtgl.getWtms())
                .like(StringUtil.isNotEmpty(wtgl.getShbz()), Rxwtgl::getShbz, wtgl.getShbz()));
    }

    @Override
    /* HttpServletRequest request, */
    public boolean updateProblem(Rxwtgl wtgl, Long pid) {

//        if (request != null) {
//            StringBuilder fileIds = uploadFile("TF_YWPN_RXWTGL_W", request, filePathBean.getJbFile());
//            wtgl.setFileid(wtgl.getFileid() + "," + fileIds.toString());
//        }
        //审核标志
        String shbz = wtgl.getShbz();
        rxwtglService.update(Wrappers.<Rxwtgl>lambdaUpdate().eq(Rxwtgl::getId, wtgl.getId())
                .set(StringUtil.isNotEmpty(shbz), Rxwtgl::getShbz, shbz)
                //审核通过则入库
                .set("1".equals(shbz), Rxwtgl::getSfrk, "1")
                //审核不通过则不入库
                .set("2".equals(shbz), Rxwtgl::getSfrk, "0")
//                .set(request != null, Rxwtgl::getFileid, wtgl.getFileid())
                .set(StringUtil.isNotEmpty(shbz), Rxwtgl::getShsj, new Date())
                .set(StringUtil.isNotEmpty(shbz), Rxwtgl::getShry, SecurityUtils.getUserId()));

        Rxknowledge know = new Rxknowledge();
        know.setFileid(wtgl.getFileid()).setTitle(wtgl.getBtmc()).setYxbz("1").setContent(wtgl.getWtms());
        if (pid != null) {
            know.setPid(pid);
        }
        return knowledgeService.save(know);
    }


}
