package com.zcxk.charge.xxl.jobs;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zcxk.charge.api.dto.WorkOrderManageByAlarmDto;
import com.zcxk.charge.api.vo.DeviceAlarmInfoForOrderVo;
import com.zcxk.charge.core.dao.AlarmDetailMapper;
import com.zcxk.charge.xxl.client.OperationManagerClient;
import com.zcxk.charge.xxl.client.UserCenterClient;
import com.zcxk.core.common.pojo.Message;
import com.zcxk.core.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Andy
 * @version V1.0
 * @description: 报警信息生成工单信息
 * @date 2021/8/18
 **/
@Component
@Slf4j
public class WorkOrderManageJob extends BaseJob {

    @Resource
    private AlarmDetailMapper alarmDetailMapper;

    @Resource
    private OperationManagerClient operationManagerClient;

    @Resource
    private UserCenterClient userCenterClient;

    /**
    * 报警信息生成工单信息
    * @author Andy
    * @date 11:09 2021/8/18
    * @param string:
    * @return com.xxl.job.core.biz.model.ReturnT<java.lang.String>
    **/
    @XxlJob("workOrderManageJob")
    public ReturnT<String> execute(String string) {
        saveWorkOrderManageInfo();
        return ReturnT.SUCCESS;
    }

    /**
    * 报警信息生成工单信息
    * @author Andy
    * @date 11:09 2021/8/18
    * @return void
    **/
    public void saveWorkOrderManageInfo(){
        List<DeviceAlarmInfoForOrderVo> deviceAlarmInfoForOrders = alarmDetailMapper.getAlarmInfoForWorkOrderManage();
        if (CollectionUtils.isEmpty(deviceAlarmInfoForOrders)){
            return;
        }
        List<WorkOrderManageByAlarmDto> workOrderManageByAlarms = new ArrayList<>();
        List<WorkOrderManageByAlarmDto> updates = new ArrayList<>();
        List<DeviceAlarmInfoForOrderVo> errData = new ArrayList<>();
        // 获取已经存在的设备工单
        Set<Long> deviceIdSet = deviceAlarmInfoForOrders.stream().map(DeviceAlarmInfoForOrderVo::getDeviceId).collect(Collectors.toSet());
        List<WorkOrderManageByAlarmDto> workOrders = operationManagerClient.findWorkOrderByDeviceIds(new ArrayList<>(deviceIdSet));
        Map<Long,WorkOrderManageByAlarmDto> workOrderMap = workOrders.stream().collect(Collectors.toMap(WorkOrderManageByAlarmDto::getDeviceId, Function.identity(), (key1, key2) -> key2));
        // 组合工单，并发送消息
        for(DeviceAlarmInfoForOrderVo deviceAlarmInfoForOrder : deviceAlarmInfoForOrders){
            if (workOrderMap.containsKey(deviceAlarmInfoForOrder.getDeviceId()) && workOrderMap.get(deviceAlarmInfoForOrder.getDeviceId()) != null){
                WorkOrderManageByAlarmDto orderManageByAlarmDto = workOrderMap.get(deviceAlarmInfoForOrder.getDeviceId());
                orderManageByAlarmDto.setTaskDesc(orderManageByAlarmDto.getTaskDesc()+";"+deviceAlarmInfoForOrder.getTaskDesc());
                updates.add(orderManageByAlarmDto);
                continue;
            }
            WorkOrderManageByAlarmDto workOrderManageByAlarm = new WorkOrderManageByAlarmDto();
            workOrderManageByAlarm.setTaskNo(DateUtil.formatDate(new Date(),"yyyyMMddHHmmssSSS")+((int) (Math.random()*(9999-1000)+1000)));
            workOrderManageByAlarm.setTenantId(deviceAlarmInfoForOrder.getTenantId());
            workOrderManageByAlarm.setParentSceneId(deviceAlarmInfoForOrder.getParentSceneId());
            workOrderManageByAlarm.setParentSceneName(deviceAlarmInfoForOrder.getParentSceneName());
            workOrderManageByAlarm.setDeviceId(deviceAlarmInfoForOrder.getDeviceId());
            workOrderManageByAlarm.setDeviceName(deviceAlarmInfoForOrder.getDeviceName());
            workOrderManageByAlarm.setCompanyOrgId(deviceAlarmInfoForOrder.getCompanyOrgId());
            workOrderManageByAlarm.setDepartmentOrgId(deviceAlarmInfoForOrder.getDepartmentOrgId());
            workOrderManageByAlarm.setAddress(deviceAlarmInfoForOrder.getAddress());
            workOrderManageByAlarm.setGeo(deviceAlarmInfoForOrder.getGeo());
            workOrderManageByAlarm.setOrderTime(deviceAlarmInfoForOrder.getOrderTime());
            workOrderManageByAlarm.setTaskDesc(deviceAlarmInfoForOrder.getTaskDesc());
            // 推送消息
            sendMessage(deviceAlarmInfoForOrder, workOrderManageByAlarm, errData);
            workOrderManageByAlarms.add(workOrderManageByAlarm);
        }
        // 去掉推送失败的数据
        if(errData.size()>0){
            deviceAlarmInfoForOrders.removeAll(errData);
        }
        // 保存工单
        if (workOrderManageByAlarms.size()>0){
            operationManagerClient.saveByAlarms(workOrderManageByAlarms);
        }
        if (updates.size()>0){
            operationManagerClient.updateByAlarms(updates);
        }
        if (deviceAlarmInfoForOrders.size()>0){
            //标记报警已生成工单
            alarmDetailMapper.updateAlarmSendMessageState(deviceAlarmInfoForOrders);
        }
    }

    /**
    * 推送消息
    * @author Andy
    * @date 11:07 2021/8/18
    * @param deviceAlarmInfoForOrder:
    * @param workOrderManageByAlarm:
    * @param errData:
    * @return void
    **/
    private void sendMessage(DeviceAlarmInfoForOrderVo deviceAlarmInfoForOrder, WorkOrderManageByAlarmDto workOrderManageByAlarm, List<DeviceAlarmInfoForOrderVo> errData){
        Integer companyOrgId    = null;
        Integer departmentOrgId = null;
        Message message = new Message();
        message.setStatus(1);
        message.setTenantId(deviceAlarmInfoForOrder.getTenantId());
        message.setMessageId(UUID.randomUUID().toString());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("工单类型"," ");
        jsonObject.put("工单编号",workOrderManageByAlarm.getTaskNo());
        //消息内容，如果需要动态使用，配合模板使用{key:value}
        message.setMessageContent(jsonObject.toJSONString());
        //消息类型
        message.setMessageType(7);
        //模板id
        message.setMessageTemplateId(7);
        //渠道
        message.setChannel(0);
        if (StringUtils.isNotBlank(workOrderManageByAlarm.getCompanyOrgId())){
            companyOrgId=Integer.valueOf(workOrderManageByAlarm.getCompanyOrgId());
        }
        if(StringUtils.isNotBlank(workOrderManageByAlarm.getDepartmentOrgId())){
            departmentOrgId=Integer.valueOf(workOrderManageByAlarm.getDepartmentOrgId());
        }
        try{
            List<Integer> taskUsers = userCenterClient.findUserIdsByPermissonOrg(workOrderManageByAlarm.getTenantId(),companyOrgId,departmentOrgId);
            if(taskUsers!=null){
                taskUsers.forEach(id->{
                    message.setUserId(id);
                    super.send(message);
                });
            }
        } catch (Exception e){
            e.printStackTrace();
            errData.add(deviceAlarmInfoForOrder);
        }
    }

}
