import Common from './Common.js';
import { h } from 'vue';
import { Notify } from 'pc-component-v3';
import TaskOpenUtil from '../workflow/TaskOpenUtil1.js';
import { message, notification } from 'ant-design-vue';
import { MessageTwoTone } from '@ant-design/icons-vue';
import WindowService from './WindowService.js';
import { queryAuth, addAuth } from '../api/authorization/index.js';
export default {

  flag: false,
  timer: null,
  source: null,
  isSound: false,
  allMessage: [],
  webSocket: null,
  notificationId: null,


  // 触发通知
  triggerNotification: function () {
    const _self = this;
    let token = localStorage.getItem('#token');
    if (!token) {
      _self.timer = null;
      _self.allMessage.splice(0, _self.allMessage.length);
      notification.close(_self.notificationId);
      return;
    }
    _self.timer = setInterval(function () {
      let allowSound = localStorage.getItem('allowSound');
      if (_self.allMessage.length > 0) {
        let index = Math.floor(Math.random() * _self.allMessage.length);
        let item = _self.allMessage[index];
        notification.close(_self.notificationId);
        _self.openNotification(item);
        _self.isShowNotification(item);
        if (_self.JudgmentDomain() && allowSound === 'true') {
          _self.playSound(true);
        }
        _self.allMessage.splice(index, 1);
      } else {
        clearInterval(_self.timer);
        _self.timer = null;
      }
    }, 5000);
  },

  // 判断域名是否相同如果不同才播放声音
  JudgmentDomain: function () {
    const prevUrl = localStorage.getItem('#prevUrl');
    if (prevUrl) {
      const currentUrl = window.location.hostname;
      if (prevUrl === currentUrl) {
        return false;
      } else {
        return true;
      }
    } else {
      return true;
    }
  },

  // 播放声音
  playSound: async function (isPlay) {
    const _self = this;
    if (_self.flag && isPlay) {
      return;
    }
    let ctx = new (window.AudioContext || window.webkitAudioContext)();
    const audioUrl = '/static/assets/client-base-v4/sound/sound.mp3';
    const res = await fetch(audioUrl);
    const arrayBuffer = await res.arrayBuffer();
    ctx.decodeAudioData(
      arrayBuffer,
      function (buffer) {
        //处理成功返回的数据类型为AudioBuffer
        //创建AudioBufferSourceNode对象
        _self.source = ctx.createBufferSource();
        _self.source.buffer = buffer;
        _self.source.connect(ctx.destination);
        _self.source.currentTime = 0;
        if (isPlay) {
          _self.source.start(0);
          setTimeout(() => {
            _self.source.stop();
            _self.flag = false;
          }, 5000);
          _self.flag = true;
        }
      },
      function (e) {
        console.info('处理出错');
      },
    );
  },

  // 检验是否支持系统提示
  isShowNotification: function (message) {
    const _self = this;
    // 检查浏览器是否支持 Notification API
    if (!('Notification' in window)) {
      alert('此浏览器不支持桌面通知');
      return;
    }
    // 检查用户是否已经允许显示通知
    if (Notification.permission === 'granted') {
      // 如果已经允许，直接显示通知
      _self.selectTaskInfo(message.content, false);
    } else if (Notification.permission !== 'denied') {
      // 否则，请求用户允许显示通知
      Notification.requestPermission().then(permission => {
        // 如果用户允许，显示通知
        if (permission === 'granted') {
          _self.selectTaskInfo(message.content, false);
        }
      });
    }
  },

  // 进行系统提示
  showNotification: function (message) {
    const _self = this;
    // 创建一个新的 Notification 对象
    if (message.type == 'NEW_TASK') {
      const notification = new Notification('待处理消息', {
        body: message.content.title,
      });
      // 监听通知的点击事件
      notification.onclick = () => {
        _self.openNewTask(message);
      };
    } else if (message.type == 'NEW_UserReadDocument') {
      const notification = new Notification('待审阅消息', {
        body: message.content.title,
      });
      notification.onclick = () => {
        _self.openDocumentTask(message);
      };
    }
  },

  // 打开待处理消息
  openNewTask: function (taskInfo) {
    TaskOpenUtil.openTask(taskInfo).then(
      successData => {
        if (successData.type === 'newWindow') {
          WindowService.open(successData.url, '待处理');
        }
      },
      errorData => {
        if (errorData != null) {
          Notify.error(errorData.title, errorData.message, false);
        }
      },
    );
  },

  // 打开待审阅消息
  openDocumentTask: function (taskInfo) {
    TaskOpenUtil.openCopyTask(taskInfo).then(
      successData => {
        if (successData.type === 'newWindow') {
          WindowService.open(successData.url, '抄送我的', function () {
            console.log('打开审阅单');
          });
        }
      },
      errorData => {
        if (errorData != null) {
          Notify.error(errorData.title, errorData.message, false);
        }
      },
    );
  },

  // 选择了taskInfo 先查询授权资源
  selectTaskInfo: function (taskInfo, isProdog, isNewTask) {
    const _self = this;
    const params = {
      userId: JSON.parse(localStorage.getItem('#LoginInfo')).userId,
      recordId: taskInfo.recordId,
      windowNo: taskInfo.windowNo,
    };
    queryAuth(params).then(
      success => {
        if (success.errorCode === 0) {
          if (isProdog) {
            if (isNewTask) {
              _self.openNewTask(taskInfo);
            } else {
              _self.openDocumentTask(taskInfo);
            }
          } else {
            _self.showNotification(taskInfo);
          }
        } else {
          _self.addAuthorization(params, taskInfo,isProdog,isNewTask);
        }
      },
      err => {
        Common.processException(err);
      },
    );
  },

  // 增加授权资源
  addAuthorization: function (params, taskInfo,isProdog,isNewTask) {
    const _self = this;
    addAuth(params).then(
      success => {
        if (success.errorCode === 0) {
          if(isProdog){
            if (isNewTask) {
              _self.openNewTask(taskInfo);
            } else {
              _self.openDocumentTask(taskInfo);
            }
          } else {
            _self.showNotification(taskInfo);
          }
        } else {
          message.warning(success.errorMessage);
        }
      },
      err => {
        Common.processException(err);
      },
    );
  },

  // 打开消息提示框
  openNotification: function (messageData) {
    const _self = this;
    _self.notificationId = messageData.uuid;
    if (messageData.type == 'NEW_TASK') {
      notification.open({
        key: messageData.uuid,
        message: messageData.content.title,
        description: '您有一条待处理消息',
        icon: () =>
          h(MessageTwoTone, {
            style: 'color: #108ee9',
          }),
        duration: 5,
        style: {
          marginTop: '30px',
        },
        onClick: () => {
          notification.close(messageData.uuid);
          // _self.replyMessage(messageData.content.id);
          _self.selectTaskInfo(messageData.content,true,true);
        },
      });
    } else if (messageData.type == 'NEW_UserReadDocument') {
      notification.open({
        key: messageData.uuid,
        message: messageData.content.title,
        description: '您有一条待审阅消息',
        icon: () =>
          h(MessageTwoTone, {
            style: 'color: #108ee9',
          }),
        duration: 5,
        onClick: () => {
          notification.close(messageData.uuid);
          // _self.replyDocument(messageData.content.id);
          _self.selectTaskInfo(messageData.content,true,false);
        },
      });
    }
  },


  // 确认收到待处理消息
  replyMessage: function (id) {
    let requestUrl = 'UnPushTaskResource/Task?id=' + id;
    $.ajax({
      url: Common.getApiURL(requestUrl),
      type: 'get',
      dataType: 'json',
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },
      success: function (data) {
        // console.log(data, 'data---------');
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        Common.processException(XMLHttpRequest, textStatus, errorThrown);
      },
    });
  },
  // 确认收到待审阅消息
  replyDocument: function (id) {
    let requestUrl = 'UnPushTaskResource/UserReadDocument?id=' + id;
    $.ajax({
      url: Common.getApiURL(requestUrl),
      type: 'get',
      dataType: 'json',
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },
      success: function (data) {
        // console.log(data, 'data---------');
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        Common.processException(XMLHttpRequest, textStatus, errorThrown);
      },
    });
  },
  // 弹出打开声音提示框
  messageModal: function () {
    const _self = this;
    const play = () => {
      let allowSound = localStorage.getItem('allowSound');
      if (allowSound && allowSound == 'false') {
        _self.playSound(false);
        localStorage.setItem('allowSound', true);
      }
      window.removeEventListener('mousemove', play);
    };
    window.addEventListener('mousemove', play);

    // Modal.warning({
    //   okText: '确认',
    //   title: '温馨提示',
    //   content: '您的浏览器设置，提示音无法自动播放，请您点击【确认】按钮，可以自动播放提示音。',
    //   onOk() {
    //     _self.playSound(false);
    //     localStorage.setItem('allowSound', true);
    //   },
    // });
  },
  // 触发仪表盘数量更新事件
  executionEvent: function () {
    // 获取刷新元素
    const refreshElement = document.querySelector('#refreshCount');
    // 自定义事件
    const customEvent = new CustomEvent('evt');
    // 触发事件
    window.refreshTimer = setInterval(function () {
      refreshElement.dispatchEvent(customEvent);
      clearInterval(window.refreshTimer);
      window.refreshTimer = null;
    }, 10000);
  },
  // 打开websocket
  openWebSocket: function () {
    const _self = this;

    // 如果websocket已连接就不在连接
    if (_self.webSocket && _self.webSocket.readyState == 1) {
      return;
    }
    let token = localStorage.getItem('#token');
    let websocketUrl = Common.getHostPageBaseURL() + '/WebSocket/MessageQueue';
    if (websocketUrl.indexOf('https') == 0) {
      websocketUrl = websocketUrl.replace('https', 'wss').replace('/api', '');
    } else if (websocketUrl.indexOf('http') == 0) {
      websocketUrl = websocketUrl.replace('http', 'ws').replace('/api', '');
    }
    _self.webSocket = new WebSocket(websocketUrl, [token]);
    _self.webSocket.onopen = function () {
      console.log('websocket打开');
    };
    _self.webSocket.onmessage = function (message) {
      let taskData = JSON.parse(message.data);
      console.log('websocket 收到信息 : ' + taskData);
      if (taskData) {
        _self.allMessage.push(taskData);
      }
      if (_self.timer == null) {
        _self.triggerNotification();
      }
      if (!window.refreshTimer) {
        _self.executionEvent();
      }
      _self.webSocket.send(message.data);
    };
    _self.webSocket.onclose = function () {
      console.log('websocket关闭');
      _self.webSocket = null;
    };
    _self.webSocket.onerror = function (event) {
      console.log('websocket异常');
      _self.webSocket.close();
    };

  },
  // 注销后关闭websocket和循环
  closeWebsocket: function () {
    const _self = this;
    if (_self.webSocket) {
      _self.webSocket.close();
      clearInterval(_self.timer);
      clearInterval(window.refreshTimer);
      _self.timer = null;
      _self.webSocket = null;
      window.refreshTimer = null;
      _self.allMessage.splice(0, _self.allMessage.length);
      notification.close(_self.notificationId);
    }
  },
};
