/**
 * 公用的请求方法
 */
import io from 'socket.io-client'; //io進行通訊
import { Toast, Modal } from 'antd-mobile';

// 获取请求的地址
const getBaseUrl = () => {
  let cache = localStorage.getItem('ZZJ-base');
  if (!cache) {
    return null;
  }
  cache = JSON.parse(cache);
  const isDev = import.meta.env.MODE == 'development';
  return isDev ? cache.Address : `${cache.BASE_URL}${cache.Address}`;
};
/**
 *
 * @param {*} code 接口地址
 * @param {*} params 接口请求的参数
 * @param {*} showError 接口请求失败时头部是否显示错误提示 默认不显示
 * @returns
 */
export const fetchPost = function (code, params, showError = false) {
  const BASEURL = getBaseUrl();
  const isDev = import.meta.env.MODE == 'development';
  if (!BASEURL) {
    return;
  }
  return new Promise((resolve, reject) => {
    fetch(BASEURL, {
      method: 'post',
      mode: 'cors',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        // 241 Basic X3N5c3RlbTppcmlz==
        // 1.6 Basic cHJoaXA6cHJoaXBAMjAyMA==
        Authorization: isDev
          ? 'Basic X3N5c3RlbTppcmlz=='
          : 'Basic cHJoaXA6cHJoaXBAMjAyMA==',
        'Access-Control-Allow-Origin': '*', // httpConfig.reqIP
      },
      body: JSON.stringify({
        code,
        ...params,
      }),
    })
      .then((res) => {
        if (res.status === 200) {
          return res.json();
        } else {
          Toast.show({
            icon: 'fail',
            duration: 3000,
            content: res.errorMessage,
          });
          reject(res);
        }
      })
      .then((data) => {
        if (data.errorCode != 0) {
          showError &&
            Toast.show({
              icon: 'fail',
              duration: 3000,
              content: data.errorMessage || data.errorCode || '请求出错',
            });
          reject(data);
        } else {
          resolve(data);
        }
      })
      .catch((error) => {
        console.error(error);
        reject(error);
      });
  });
};
/**
 * 模拟socket发送消息 测试！！!!
 * @param {*} getMessage
 */
const testSocket = (getMessage) => {
  // 模拟数据
  const tempList = [
    {
      roomDesc: '专家诊室1',
      docName: '宦大达',
      callMsg: {
        callPat: [{ patCallNo: '11号', patName: '患*者' }],
        waitPat: [
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 1',
            patName: '患*者1',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 2',
            patName: '患*者2',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 3',
            patName: '患*者3',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 4',
            patName: '患*者4',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 5',
            patName: '患*者5',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 6',
            patName: '患*者1',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 7',
            patName: '患*者2',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 1',
            patName: '患*者1',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 2',
            patName: '患*者2',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 3',
            patName: '患*者3',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 4',
            patName: '患*者4',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 5',
            patName: '患*者5',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 6',
            patName: '患*者1',
          },
          {
            patCallStatusDesc: '未签',
            patCallNo: '08:00 7',
            patName: '患*者2',
          },
          { patCallStatusDesc: '未签', patCallNo: '复03', patName: '患者3a' },
          { patCallStatusDesc: '未签', patCallNo: '复01', patName: '患*者1' },
          { patCallStatusDesc: '未签', patCallNo: '复02', patName: '患*者2' },
          { patCallStatusDesc: '未签', patCallNo: '复03', patName: '患者3a' },
          { patCallStatusDesc: '未签', patCallNo: '复04', patName: '患者4a' },
          { patCallStatusDesc: '未签', patCallNo: '10', patName: '患*者10' },
          { patCallStatusDesc: '未签', patCallNo: '11', patName: '患*者11' },
          { patCallStatusDesc: '未签', patCallNo: '12', patName: '患*者12' },
        ],
        reWaitPat: [
          { patCallStatusDesc: '未签', patCallNo: '01', patName: '患*者' },
          { patCallStatusDesc: '未签', patCallNo: '02', patName: '患*者' },
          { patCallStatusDesc: '未签', patCallNo: '03', patName: '患者3' },
          { patCallStatusDesc: '未签', patCallNo: '01', patName: '患*者' },
          { patCallStatusDesc: '未签', patCallNo: '02', patName: '患*者' },
          { patCallStatusDesc: '未签', patCallNo: '03', patName: '患者3' },
          { patCallStatusDesc: '未签', patCallNo: '04', patName: '患者4' },
          { patCallStatusDesc: '未签', patCallNo: '03', patName: '患者3' },
          { patCallStatusDesc: '未签', patCallNo: '01', patName: '患*者' },
          { patCallStatusDesc: '未签', patCallNo: '02', patName: '患*者' },
          { patCallStatusDesc: '未签', patCallNo: '03', patName: '患者3' },
          { patCallStatusDesc: '未签', patCallNo: '04', patName: '患者4' },
        ],
      },
      delayPat:
        '患*者1,患*者2,患者3a,患*者1,患*者2,患者3a,患者4a,患*者1,患*者2,患者3a,患*者1,患*者2,患者3a,患者4a患*者1,患*者2,患者3a,患*者1,患*者2,患者3a,患者4a',
    },
    {
      roomDesc: '专家诊室2',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [
          { patCallStatusDesc: '未签', patCallNo: 'A1', patName: '患*者1' },
          { patCallStatusDesc: '未签', patCallNo: 'A2', patName: '患*者2' },
          { patCallStatusDesc: '未签', patCallNo: 'A3', patName: '患*者3' },
          { patCallStatusDesc: '未签', patCallNo: 'A4', patName: '患*者4' },
          { patCallStatusDesc: '未签', patCallNo: 'A5', patName: '患*者5' },
          { patCallStatusDesc: '未签', patCallNo: 'A6', patName: '患*者6' },
          { patCallStatusDesc: '未签', patCallNo: 'A7', patName: '患*者7' },
          { patCallStatusDesc: '未签', patCallNo: 'A8', patName: '患*者8' },
          { patCallStatusDesc: '未签', patCallNo: 'A9', patName: '患*者9' },
          { patCallStatusDesc: '未签', patCallNo: 'A10', patName: '患*者10' },
          { patCallStatusDesc: '未签', patCallNo: 'A11', patName: '患*者11' },
          { patCallStatusDesc: '未签', patCallNo: 'A12', patName: '患*者12' },
        ],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室2',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: 'B复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室3',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [
          { patCallNo: '复01', patName: '患*者1' },
          { patCallNo: '复1', patName: '患*者2' },
          { patCallNo: '01', patName: '患*者3' },
          { patCallNo: '复1', patName: '患*者4' },
        ],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室4',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室5',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '专家诊室4',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
      voiceFileName: '',
    },
    {
      voiceFileName: '2222',
      path: '111',
      roomDesc: '诊室7',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室8',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室9',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室10',
      docName: '医生1',
      callMsg: {
        refreshFlag: 'Y',
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室11',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '11号', patName: '患*者' }],
        waitPat: [
          { patCallNo: '1', patName: '患*者1' },
          { patCallNo: '2', patName: '患*者2' },
          { patCallNo: '3', patName: '患*者3' },
          { patCallNo: '4', patName: '患*者4' },
          { patCallNo: '5', patName: '患*者5' },
          { patCallNo: '6', patName: '患*者6' },
          { patCallNo: '7', patName: '患*者7' },
          { patCallNo: '8', patName: '患*者8' },
          { patCallNo: '9', patName: '患*者9' },
          { patCallNo: '10', patName: '患*者10' },
          { patCallNo: '11', patName: '患*者11' },
          { patCallNo: '12', patName: '患*者12' },
        ],
        reWaitPat: [
          { patCallNo: '复01', patName: '患*者1' },
          { patCallNo: '复02', patName: '患*者2' },
          { patCallNo: '复03', patName: '患者3a' },
          { patCallNo: '复04', patName: '患者4a' },
        ],
      },
    },
    {
      roomDesc: '诊室12',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
    {
      roomDesc: '诊室13',
      docName: '医生1',
      callMsg: {
        callPat: [{ patCallNo: '1号', patName: '患*者' }],
        waitPat: [{ patCallNo: '复01', patName: '患*者1' }],
        reWaitPat: [{ patCallNo: '复01', patName: '患*者1' }],
      },
    },
  ];
  // todo 测试代码方法
  if (tempList) {
    var start = 0;
    setInterval(() => {
      if (start > 12) {
        return;
      }
      getMessage(JSON.stringify(tempList[start]));
      ++start;
    }, 1000);
  }
};
// scoket创建
let handler = null;
export const initSocket = (obj, getMessage) => {
  // 测试模拟发送消息start！！！！
  // if (testSocket(getMessage)) {
  //   return;
  // }
  // 测试模拟发送消息end！！！！
  if (window.socket) {
    return;
  }
  window.socket = io(obj.serverIP + ':' + obj.serverPort, {
    reconnectionAttempts: 0,
    reconnection: true,
    transports: ['websocket'],
    forceNew: true,
    query: {
      type: 'C',
      deviceID: obj.deviceID,
    },
  });
  // window.socket = new WebSocket('http://m00.puruiit.cn:10015/socket.io/?type=C&deviceID=8e5604af-99db-47a5-b5e9-465040486690&EIO=4&transport=websocket');
  window.socket.on('connect_timeout', function () {
    console.log('connect_timeout');
    window.socket.close();
    window.socket = null;
    initSocket(obj, getMessage);
    Toast.show({
      duration: 10000,
      content: 'scoket连接超时',
    });
  });
  //服务器连接异常
  window.socket.on('connect_error', (e) => {
    console.log('connect_error', e);
    // Toast.show({
    //   duration: 10000,
    //   content: 'scoket连接出错了' + e,
    // });
    if (!handler) {
      handler = Modal.show({
        content: '连接断开' + e,
        closeOnMaskClick: true,
      });
    }
    window.socket.close();
    window.socket = null;
    initSocket(obj, getMessage);
  });
  //服务器响应消息
  window.socket.on('callNumber', (data) => {
    // Toast.show({
    //   duration: 20000,
    //   content: data1.path+data1.voiceFileName,
    // });
    getMessage && getMessage(data);
  });
  window.socket.on('connect', function () {
    console.log('scoket连接成功');
    console.log(handler);
    if (handler) {
      handler?.close();
      handler = null;
    }
    Toast.show({
      duration: 10000,
      content: '连接成功',
    });
  });

  window.socket.on('disconnect', function (e) {
    // Toast.show({
    //   duration: 10000,
    //   content: '连接断开' + e,
    // });
    if (!handler) {
      handler = Modal.show({
        content: '连接断开' + e,
        closeOnMaskClick: true,
      });
    }
    // window.socket = null;
    // initSocket(obj, getMessage);
  });
};
