/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.emergency.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.api.DepartmentClient;
import com.tofly.api.UserClent;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.FileTableEnum;
import com.tofly.gpsboot.common.system.IsDispatchingEnum;
import com.tofly.api.mssage.SendMessageFeign;
import com.tofly.gpsboot.service.emergency.EmergencyTypeService;
import com.tofly.pojo.emergency.EmergencyType;
import com.tofly.pojo.note.SendMessage;
import com.tofly.pojo.note.SendNoteEn;
import com.tofly.gpsboot.mapper.emergency.EmergencyMapper;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.emergency.EmergencyService;
import com.tofly.gpsboot.service.mq.IPlanMessageService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.Department;
import com.tofly.pojo.User;
import com.tofly.pojo.emergency.Emergency;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 应急事件记录表
 *
 * @author admin
 * @date Tue Feb 22 00:00:00 CST 2022
 */
@Service("emergencyService")
public class EmergencyServiceImpl extends ServiceImpl<EmergencyMapper, Emergency> implements EmergencyService {

    @Autowired
    private IPlanMessageService iPlanMessageService;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Value("${xrty.ftp.emergency}")
    private String emergencyFilePath;
    @Autowired
    private UserClent userClent;
    @Autowired
    private DepartmentClient departmentClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SendMessageFeign sendMessageFeign;
@Autowired
private EmergencyTypeService emergencyTypeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone saveInfo(List<MultipartFile> fileList, Emergency emergency) throws Exception {
        StringBuilder fileIdList = new StringBuilder("");
        if(null!=emergency.getFileIds()){
            fileIdList.append(emergency.getFileIds());
        }

        // 判断当前是否有文件,则存入返回文件id
        if (null != fileList && fileList.size() > 0) {
            StringBuilder builder = iFileInfoService.saveFileList(fileList, emergencyFilePath, FileTableEnum.TF_YWPN_EMERGENCY_W.getTableName());
            if(null!=builder && builder.length()>0){
                if(fileIdList.length()>0){
                    fileIdList.append(Constant.CSV).append(builder.toString());
                }else {
                    fileIdList.append(builder.toString());
                }
            }
        }
        String isDispatching = emergency.getIsDispatching();
        emergency.setFileIds(fileIdList.toString());
        if (IsDispatchingEnum.IS_DISPATCHING_YES.getCode().equals(isDispatching)) {
            emergency.setState("2");
            if(emergency.getDispatchingUserId()==null || emergency.getDispatchingUserId()==0) {
                emergency.setDispatchingUserId(SecurityUtils.getUserId());

            }
            emergency.setDispatchingTime(new Date());

        }

        EmergencyType emergencyType=emergencyTypeService.getById(emergency.getTypeId());
        String messageNote=null;
        if(emergencyType!=null && StringUtil.isNotEmpty(emergency.getName())){
            messageNote=emergencyType.getName();

        }
        if(StringUtil.isNotEmpty(emergency.getNote()) && emergency.getNote()!="null"){
            messageNote+=":"+emergency.getNote();

        }else{
            emergency.setNote(null);
        }
        emergency.setMessageNote(messageNote);
        if(StringUtil.isEmpty(emergency.getDisPhone()) || emergency.getDisPhone()=="null"){
            emergency.setDisPhone(null);
        }
        if(StringUtil.isEmpty(emergency.getFoundPhone()) || emergency.getFoundPhone()=="null"){
            emergency.setFoundPhone(null);
        }

        // 自动生成编码
        emergency.setCode(this.sendOrderCode(SecurityUtils.getUserId()));
        this.save(emergency);
        // 判断是否自动派工
        if (IsDispatchingEnum.IS_DISPATCHING_YES.getCode().equals(isDispatching)) {
            // 对当前计划派工人 发送审核消息/代办信息

            // 获取处理人和协同处理人id列表
            Set<Long> userIdSet = new HashSet<>();
            Long disUserId = emergency.getDisUserId();
            String synergyUserIds = emergency.getSynergyUserIds();
            if (!StringUtils.isEmpty(synergyUserIds)) {
                userIdSet = Arrays.stream(synergyUserIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toSet());
            }
            userIdSet.add(disUserId);
            // 代办任务发送
            iPlanMessageService.emergencySendMessage(emergency.getId(),emergency.getDispatchingUserId(), userIdSet,disUserId,emergency.getMessageNote());
            if("1".equals(emergency.getIsMessage())){
                // 手机短信消息发送
                SendNoteEn sendNoteEn = new SendNoteEn();
                SendMessage sendMessage = new SendMessage();
                sendMessage.setTxlx("4");
                sendMessage.setTxnr(emergency.getMessageNote());
                sendMessage.setLxdh(emergency.getDisPhone());
                List<SendMessage> sendMessageList = new ArrayList<>();
                sendMessageList.add(sendMessage);
                sendNoteEn.setSendMessageList(sendMessageList);
                return sendMessageFeign.sendMessage(sendNoteEn);
            }
        }
        return ResultRespone.success();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean dispatchingInfo(Emergency emergency) {
        // 设置已派工
        emergency.setIsDispatching(IsDispatchingEnum.IS_DISPATCHING_YES.getCode());
        emergency.setState("2");

        this.updateById(emergency);

        // 对当前计划派工人 发送审核消息/代办信息
        ReportAuditDto dto = new ReportAuditDto();
        dto.setId(emergency.getId());
        dto.setAuditId(emergency.getDispatchingUserId());
        dto.setAuditNotes(emergency.getNote());
        // 获取处理人和协同处理人id列表
        Set<Long> userIdSet = new HashSet<>();
        Long disUserId = emergency.getDisUserId();
        String synergyUserIds = emergency.getSynergyUserIds();
        if (!StringUtils.isEmpty(synergyUserIds)) {
            userIdSet = Arrays.stream(synergyUserIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toSet());
        }
        userIdSet.add(disUserId);

        // 代办任务发送
        iPlanMessageService.emergencySendMessage(emergency.getId(),emergency.getDispatchingUserId(), userIdSet,disUserId,emergency.getMessageNote());
        if("1".equals(emergency.getIsMessage())){
            //TODO 手机短信消息发送
        }
        return true;
    }
    private String sendOrderCode(Long userId) {
        StringBuilder deptCode = new StringBuilder("");
        // 获取用户对应的机构编码
        User user = userClent.getById(userId).getResult();
        if (null != user) {
            Long departmentId = user.getDepartmentId();
            if (null != departmentId) {
                Department department = departmentClient.getById(departmentId).getResult();
                deptCode.append(department.getCode());
            }
        }
        //生成一个序列号，每天从0开始自增
        deptCode.append(this.produceSerialNumber());
        return deptCode.toString();

    }


    private String produceSerialNumber() {

        //批次前缀
        String prefix = DateTimeUtil.getCurrentDate(DateTimeUtil.NUMBER_FORMAT);
        String pre = prefix.substring(0, 8);
        //使用redis生成唯一流水号
        Long sequence = stringRedisTemplate.opsForValue().increment(Constant.MESSAGE_BATCH_ROB_MAINTAIN_SEQUENCE + "_" + pre, 1);
        if (sequence == 1) {
            stringRedisTemplate.delete(stringRedisTemplate.keys(Constant.MESSAGE_BATCH_ROB_MAINTAIN_SEQUENCE + "_" + "*"));
            sequence = stringRedisTemplate.opsForValue().increment(Constant.MESSAGE_BATCH_ROB_MAINTAIN_SEQUENCE + "_" + pre, 1);
        }
        //批次后缀 取流水号最后5位 如果不足5位前面补0
        String suffix = String.format("%05d", sequence % 100000);
        return pre + suffix;
    }
}
