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

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.message.MessageClient;
import com.tofly.api.message.MessageStateClient;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
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.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.xrtygis.custom.entity.enums.GisMessage;
import com.tofly.xrtygis.custom.entity.gs.Emergency;
import com.tofly.xrtygis.custom.service.EmergencyService;
import com.tofly.xrtygis.entity.File;
import com.tofly.xrtygis.entity.Rxyjfw;
import com.tofly.xrtygis.service.FileService;
import com.tofly.xrtygis.service.RxyjfwService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author FlashWJL
 * @date 2021/4/1 17:21
 */
@Service
public class EmergencyServiceImpl implements EmergencyService {

    @Autowired
    private RxyjfwService rxyjfwService;
    @Autowired
    private FileService fileService;
    @Autowired
    private MessageClient messageClient;
    @Autowired
    private MessageStateClient messageStateClient;

    @Value("${gsrx.emergency}")
    private String emergencyRoute;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEmer(Rxyjfw rxyjfw) {
        if (StringUtil.isEmpty(rxyjfw.getYjms())) {
            throw new ToflyDeniedException("请输入应急描述");
        }
        if ("1".equals(rxyjfw.getYjly())) {
            rxyjfw.setCreateUser(236L);
        } else {
            rxyjfw.setCreateUser(SecurityUtils.getUserId());
        }
        //新增的应急是没有审核信息的
        rxyjfw.setShbz("0");
        rxyjfw.setYjbh(DateUtil.parseDateToStr("yyyyMMddHHmmss", Date8Util.getCurrentDate()) + rxyjfw.getYjly());
        if (rxyjfwService.save(rxyjfw)) {
            Messagepush messagepush = new Messagepush();
            messagepush.setMessage(rxyjfw.getYjms());
            messagepush.setTopic(rxyjfw.getYjbt());
            messagepush.setType(GisMessage.EMERGENCY.getType());
            messagepush.setTableName(GisMessage.EMERGENCY.getTableName());
            messagepush.setRouteIp("/waterHotline/workbench");
            //这里暂时先默认写一个ID，具体创建这个消息的是谁，后面问下需求
            messagepush.setCreateUser(SecurityUtils.getUserId());
            //消息推送
            Long resultId = messageClient.save(messagepush).getResult();
            //指定消息接收人
            Messagerecipient messagerecipient = new Messagerecipient();
            messagerecipient.setMessageId(resultId);
            //暂时写成具体的管理人，后面根据角色查询工作人员
            messagerecipient.setRecipient(rxyjfw.getShry());
            messageStateClient.save(messagerecipient);
        }

        return true;
    }

    @Override
    public void saveEmerSys(Long flowNum) {
        //在保存系统应急记录之前需要查询一次，如果已经有当天的应急记录，则不保存了
        String dateStr = DateUtil.parseDateToStr("yyyyMMddHHmmss", Date8Util.getCurrentDate());
        dateStr = dateStr.substring(0, 8);
        Rxyjfw queryRxYj = rxyjfwService.getOne(Wrappers.<Rxyjfw>lambdaQuery().eq(Rxyjfw::getYjly, "1")
                .like(Rxyjfw::getYjbh, dateStr));
        //如果没有当天没有系统应急记录，则保存一条系统应急
        if (StringUtil.isNull(queryRxYj)) {
            Rxyjfw rxyjfw = new Rxyjfw();
            rxyjfw.setYjly("1");
            rxyjfw.setCreateUser(236L);
            rxyjfw.setYwlx("流量预警");
            rxyjfw.setYjms("流量预警已超过" + flowNum + "个");
            rxyjfw.setYjbt("流量预警消息");
            //系统保存应急
            saveEmer(rxyjfw);
        }

    }

    @Override
    public void saveEmerSys2(Long blockCallNum) {
        //在保存系统应急记录之前需要查询一次，如果已经有当天的应急记录，则不保存了
        String dateStr = DateUtil.parseDateToStr("yyyyMMddHHmmss", Date8Util.getCurrentDate());
        dateStr = dateStr.substring(0, 8);
        Rxyjfw queryRxYj = rxyjfwService.getOne(Wrappers.<Rxyjfw>lambdaQuery().eq(Rxyjfw::getYjly, "1")
                .like(Rxyjfw::getYjbh, dateStr));
        //如果没有当天没有系统应急记录，则保存一条系统应急
        if (StringUtil.isNull(queryRxYj)) {
            Rxyjfw rxyjfw = new Rxyjfw();
            rxyjfw.setYjly("1");
            rxyjfw.setCreateUser(236L);
            rxyjfw.setYwlx("未接通预警");
            rxyjfw.setYjms("未接通预警已超过" + blockCallNum + "个");
            rxyjfw.setYjbt("未接通预警消息");
            //系统保存应急
            saveEmer(rxyjfw);
        }
    }


    @Override
    public Page getEmer(Page page, Emergency emergency) {
        Rxyjfw rxyjfw = new Rxyjfw();
        BeanUtils.copyProperties(emergency, rxyjfw);
        Date startTime = emergency.getStartTime();
        Date endTime = emergency.getEndTime();
        return rxyjfwService.page(page, Wrappers.query(rxyjfw).lambda()
                .le(StringUtil.isNotNull(endTime), Rxyjfw::getCreateDate, endTime)
                .ge(StringUtil.isNotNull(startTime), Rxyjfw::getCreateDate, startTime));
    }

    @Override
    public boolean updateEmer(Rxyjfw rxyjfw, HttpServletRequest request) {
        //根据应急服务查询当前文件ID
        return rxyjfwService.updateById(rxyjfw);
    }


    @Override
    public boolean delEmer(List<String> asList) {
//        //查询应急文件
//        List<Rxyjfw> rxyjfwList = rxyjfwService.list(Wrappers.<Rxyjfw>lambdaQuery().in(Rxyjfw::getId, asList).select(Rxyjfw::getFileid,Rxyjfw::getId));
//
//        if (StringUtil.isNotNull(rxyjfwList)) {
//            //文件数据表ID
//            List<String> fileIds = rxyjfwList.stream().filter(k->StringUtil.isNotNull(k)).map(Rxyjfw::getFileid).collect(Collectors.toList());
//            if (StringUtil.isNotNull(fileIds)&&fileIds.size()>0){
//                fileIds.forEach(k->{
//                    fileService.removeByIds(Arrays.asList(k.split(",")));
//                });
//                List<List<String>> paths = rxyjfwList.stream().filter(k -> StringUtil.isNotNull(k)).map(Rxyjfw::getFilePaths).collect(Collectors.toList());
//                paths.forEach(k -> {
//                    k.forEach(v -> {
//                        //删除文件
//                        FtpUtil.deleteFile(v);
//                    });
//                });
//            }
//        }
        //删除应急服务
        rxyjfwService.removeByIds(asList);
        return true;
    }

    /**
     * 这里是提醒，只有相对应的用户角色才能有信息返回
     *
     * @param page
     * @return
     */
    @Override
    public Page remind(Page page) {
        //查询当前人员角色
        List<Integer> roles = SecurityUtils.getRoles();
        //这里判断有没有对应的角色


        if (roles.contains("")) {
            //如果有，则查询应急服务数据
            return rxyjfwService.page(page);
        }
//        没有则返回空
        return null;
    }


    @Override
    public String checkData(Rxyjfw rxyjfw) {
        if (rxyjfw.getId() == null) {
            return "审核id不能为空";
        }
        Rxyjfw rxdb = rxyjfwService.getById(rxyjfw.getId());
        if (!"1".equals(rxdb.getIsReview())) {
            return "应急服务不需要审核!";
        }
        if (SecurityUtils.getUserId() == null || !SecurityUtils.getUserId().equals(rxdb.getShry())) {
            return "指定审核人与登入人不一致!";
        }
        if ("1".equals(rxdb.getShbz())) {
            return "应急服务已审核";
        }
        if (StringUtils.isEmpty(rxyjfw.getShjg()) || StringUtils.isEmpty(rxyjfw.getShyj())) {
            return "应急服务审核结果或审核意见不能为空!";
        }
        return null;
    }

    @Override
    public Integer countEmergency() {
        List<Rxyjfw> result = rxyjfwService.list(Wrappers.<Rxyjfw>lambdaQuery().eq(Rxyjfw::getIsRead, "0"));
        return result.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean eliminateUnreads() {
        return rxyjfwService.update(Wrappers.<Rxyjfw>lambdaUpdate().and(w -> w.eq(Rxyjfw::getIsRead, "0").or().isNull(Rxyjfw::getIsRead))
                .set(Rxyjfw::getIsRead, "1"));
    }


    @Override
    public boolean audit(Rxyjfw rxyjfw) {
        rxyjfw.setShsj(new Date());
        rxyjfw.setShbz("1");
        return rxyjfwService.updateById(rxyjfw);
    }


    /**
     * 文件上传管理
     *
     * @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;
    }


}
