import React from 'react';
import Login from '@components/login/Index.jsx';
import DoctorScreen from '@pages/doctorScreen/Index.jsx';
import BigScreen from '@pages/bigScreen/Index.jsx';
import OperateScreen from '@pages/operateScreen/Index.jsx';
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { initSocket } from '@api/index.js';
import { AntOutline, SetOutline } from 'antd-mobile-icons';
import { Toast } from 'antd-mobile';
// // 安卓相关处理
import audioSrc from './../../assets/mp3.wav';

window.webGetDeviceId = function (callback) {
  window.callback = callback;
};
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleLogin: false,
      userData: {}, // 用户及房间数据
      patList: [], // 就诊等待数据
      waitPat: [],
      patListArea: [], //区域等待就诊患者数据
      reWaitPat: [], // 复诊的患者
      roomObj: {},
      delayPat: [], //候诊数据
      showType: 'doctor', // doctor医生诊室 area诊区叫号 operate手术室
      cache: {},
      colorName: localStorage.getItem('ZZJ-color'), // white-bg白色 dark-bg深色
      deviceID: '',
      hosLogo: '',
      voiceSrc: [],
      isPlay: false,
      voiceList: [],
      myStatus: false,
      // 模拟数据
      tempList: [
        {
          'roomDesc': '专家诊室一', 'docName': '宦大达', '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': '复01', 'patName': '患*者1' },
              { 'patCallNo': '复02', 'patName': '患*者2' },
              { 'patCallNo': '复03', 'patName': '患者3a' },
              { 'patCallNo': '复04', 'patName': '患者4a' }],
          },
          delayPat: '患*者1,患*者2,患者3a,患*者1,患*者2,患者3a,患者4a,患*者1,患*者2,患者3a,患*者1,患*者2,患者3a,患者4a患*者1,患*者2,患者3a,患*者1,患*者2,患者3a,患者4a',
        },
        {
          'roomDesc': '诊室1', 'docName': '医生1', 'callMsg':
          {
            'callPat': [{ 'patCallNo': '1号', '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' },
            ],
          }
        },
        {
          'roomDesc': '诊室2', 'docName': '医生1', 'callMsg':
          {
            'callPat': [{ 'patCallNo': '1号', 'patName': '患*者' }],
            'waitPat': [
              { 'patCallNo': '复01', 'patName': '患*者1' },
            ],
            'reWaitPat': [
              { 'patCallNo': '复01', 'patName': '患*者1' },
            ],
          }
        },
        {
          'roomDesc': '诊室3', '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' },
            ],
          }
        },
        {
          'roomDesc': '诊室5', 'docName': '医生1', 'callMsg':
          {
            'callPat': [{ 'patCallNo': '1号', 'patName': '患*者' }],
            'waitPat': [
              { 'patCallNo': '复01', 'patName': '患*者1' },
            ],
            'reWaitPat': [
              { 'patCallNo': '复01', 'patName': '患*者1' },
            ],
          }
        },
        {
          'roomDesc': '诊室6', 'docName': '医生1', 'callMsg':
          {
            'callPat': [{ 'patCallNo': '1号', 'patName': '患*者' }],
            'waitPat': [
              { 'patCallNo': '复01', 'patName': '患*者1' },
            ],
            'reWaitPat': [
              { 'patCallNo': '复01', 'patName': '患*者1' },
            ],
          }
        },
        {
          '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':
          {
            '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' },
            ],
          }
        },
      ],
    };
  }
  componentDidMount() {
    this.initDevice();
    this.initAndroidVoice();
    const test = () => {
      var start = 0;
      setInterval(() => {
        const data = this.state.tempList[start];
        const patList = [...data.callMsg.callPat, ...data.callMsg.waitPat.map(v => {
          return { ...v, status: 'waiting' };
        })];
        const { roomObj } = this.state;
        roomObj[data.roomDesc] = data;
        const newArray = Object.keys(roomObj).map(key => {
          return roomObj[key];
        });
        this.setState({
          userData: {
            ...data?.userData,
            areaDesc: data.locDesc, // 大屏诊区
            roomDesc: data.roomDesc, // 诊室
          },
          patList,
          waitPat: data.callMsg.waitPat,
          reWaitPat: data.callMsg.reWaitPat,
          patListArea: newArray,
          roomObj,
          delayPat: data.delayPat,
        });
        ++start;
        if (start > 13) {
          start = 0;
        }
        this.initVoice('/mp3.wav');
      }, 2950);
    };
    // test();
  }
  initAndroidVoice() {
    window.mediaPlayOver = (flag) => {
      if (flag == 'success') {
        this.state.voiceList.splice(0, 1);
        this.setState({
          voiceList: this.state.voiceList,
        }, () => {
          this.soundPaly();
        });
      }
    };
  }
  soundPaly(src) {
    const isDev = import.meta.env.MODE == 'development';
    if (src || isDev || this.state.voiceList.length > 0) {
      this.setState({
        myStatus: true,
      }, () => {
        const ua = navigator.userAgent.toLowerCase();
        if (/android/.test(ua)) {
          window.JavaClientCall && window.JavaClientCall.mediaFilePlay(src || isDev ? 'https://np.h03.p0551.com/images/wav/eba7ea72748b33c07d55ca7c443d6146.wav' : this.state.voiceList[0]);
        }
      });
    } else {
      this.setState({
        myStatus: false
      });
    }
  }
  // 音频播放事件
  initVoice = (src) => {
    const { voiceSrc } = this.state;
    voiceSrc.push(src);
    this.setState({
      voiceSrc,
    }, () => {
      if (voiceSrc.length == 1) {
        playVioce(src);
      }
    });
    const playVioce = (audioSrc) => {
      if (this.state.isPlay) {
        return;
      }
      this.setState({
        isPlay: true,
      }, () => {
        const domAudio = document.querySelector('#audio');
        domAudio.src = audioSrc;
        domAudio.playbackRate = 1;
        domAudio.currentTime = 0;
        domAudio.load();
        domAudio.play();
        const mes = () => {
          Toast.show({
            duration: 10000,
            content: '播放完成',
          });
          const { voiceSrc } = this.state;
          voiceSrc.splice(0, 1);
          const newArr = voiceSrc;
          this.setState({
            isPlay: false,
            voiceSrc: newArr,
          }, () => {
            if (newArr.length > 0) {
              playVioce(newArr[0]);
            }
            domAudio.removeEventListener('ended', mes);
          });
        };
        domAudio.addEventListener('ended', mes);
        // 10s看是否播放结束
        // setTimeout(() => {
        //   if (this.state.isPlay) {
        //     mes();
        //   }
        // }, 10000);
      });
    };
  };
  initDevice = async () => {
    //接收Android端身份证信息函数
    window.webGetDeviceId = (deviceId) => {
      this.setState({
        deviceID: deviceId,
      }, () => {
        this.loginInit();
      });
    };
    const ua = navigator.userAgent.toLowerCase();
    if (/android/.test(ua)) {
      window.JavaClientCall && window.JavaClientCall.getDeviceID();
    }
    // 测试环境无法从安卓获取数据
    const isDev = import.meta.env.MODE == 'development';
    if (isDev) {
      const fp = await FingerprintJS.load();
      const AndroidInfo = await fp.get();
      this.setState({
        deviceID: AndroidInfo.visitorId,
      }, () => {
        this.loginInit();
      });
    }
  };
  // 改变颜色
  changeSwitch = () => {
    let { colorName } = this.state;
    if (!colorName) {
      colorName = 'white-bg';
    } else if (colorName == 'white-bg') {
      colorName = 'dark-bg';
    } else {
      colorName = '';
    }
    this.setState({
      colorName,
    });
    localStorage.setItem('ZZJ-color', colorName);
    this.soundPaly('https://np.h03.p0551.com/images/wav/eba7ea72748b33c07d55ca7c443d6146.wav');
  };
  openLogin = (cache) => {
    if (!cache) {
      cache = {
        BASE_URL: 'http://10.1.?.29:8090',
        Address: '/bdhealth/',
        room: '',
        use: '',
        hospital: '',
      };
    }
    this.setState({
      cache,
      visibleLogin: true,
    });
  };
  hideLogin = () => {
     this.setState({
      visibleLogin: false,
    });
  };
  loginInit = async() => {
    let cache = localStorage.getItem('ZZJ-base');
    if (cache) {
      cache = JSON.parse(cache);
    }
    if (!cache || (cache && !cache.room)) {
      this.openLogin(cache);
      return;
    }
    const obj = await this.login(cache);
    if (!obj) {
      return;
    }
    obj.deviceID = this.state.deviceID;
    initSocket(obj, (data) => {
      // console.log('Room接收消息：',data );
      data = JSON.parse(data);
      if (data.callMsg) {
        const patList = [...data.callMsg.callPat, ...data.callMsg.waitPat.map(v => {
          return { ...v, status: 'waiting' };
        })];
        const { roomObj } = this.state;
        roomObj[data.roomDesc] = data;
        const newArray = Object.keys(roomObj).map(key => {
          return roomObj[key];
        });
        this.setState({
          userData: {
             ...data?.userData,
            areaDesc: data.locDesc, // 大屏诊区
            roomDesc: data.roomDesc, // 诊室
          },
          patList,
          waitPat: data.callMsg.waitPat,
          reWaitPat: data.callMsg.reWaitPat,
          patListArea: newArray,
          roomObj,
          delayPat: data.delayPat,
        });
        if (!data.path || !data.voiceFileName) {
          return;
        }
        this.state.voiceList.push(data.path + data.voiceFileName);
        this.setState({
          voiceList: this.state.voiceList,
        }, () => {
          if (!this.state.myStatus) {
            this.soundPaly();
          }
        });
        // this.initVoice(data.path + data.voiceFileName);
      }
    });
  };
  //登录事件
  login = async () => {
    let cache = localStorage.getItem('ZZJ-base');
    if (!cache) {
      return;
    }
    cache = JSON.parse(cache);

    return React.$fetchPost('04150020', {
      params: [{
        ip: cache.BASE_URL,
        identifyCode: this.state.deviceID,
      }],
    }, true).then((data) => {
      if (data) {
        const obj = {
          Loc: 'area',
          Room: 'doctor',
          OptomeRoom: 'doctor',
          OperLoc: 'operate',
        };
        this.setState({
          userData: data?.result[0] || {},
          // https://172.16.1.6/images/hoslogo/H02.png 医院logo
          hosLogo: `/images/hoslogo/${data?.result[0]?.hospCode}.png`
        });
        if (obj[data.code]) {
          this.setState({
            showType: obj[data.code], // Loc医生诊室 Room,OptomeRoom大屏 OperLoc 手术室
          });
          if (obj[data.code] == 'doctor') {
            document.querySelector('html').className = '';
          } else {
            document.querySelector('html').className = 'big';
          }
          return data?.result[0] || null;
        } else {
          this.openLogin();
          return null;
        }
      }
    });
  };
  render () {
    return (
    <>
      <div className={ this.state.colorName}>
        {/* 设备信息配置，选择医院 */}
        <Login
          visibleLogin={this.state.visibleLogin}
          formData={this.state.cache}
          hideLogin={this.hideLogin}
          loginInit={this.loginInit}
          deviceID={this.state.deviceID}
        />
        {/* 医生诊室呼叫 */}
        {this.state.showType == 'doctor'
          ? <DoctorScreen
              userData={this.state.userData}
              patList={this.state.patList}
              reWaitPat={this.state.reWaitPat}
              hosLogo={this.state.hosLogo}
            />
          : this.state.showType == 'operate'
            ? <OperateScreen
                patList={this.state.waitPat}
                userData={this.state.userData}
                hosLogo={this.state.hosLogo}
              />
            : < BigScreen
                userData={this.state.userData}
                patListArea={this.state.patListArea}
                delayPat={this.state.delayPat}
                hosLogo={this.state.hosLogo}
              />

        }
        </div>
      <span
        className='bottom-set'
      >
        <AntOutline
          style={{color: this.state.colorName == 'dark-bg' ? '#fff' : '#0D2764', marginLeft: '10px'}}
          onClick={this.changeSwitch}
        />
        <SetOutline
          onClick={this.openLogin}
          style={{color: this.state.colorName == 'dark-bg' ? '#fff' : '#0D2764', marginLeft: '10px'}}
        />
        </span>
        <audio controls id="audio"
          style={{ position: 'fixed', left: '-1000px', top: '100px' }}
        ></audio>
    </>
    );
  }
}
export default Home;
