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';

// // 安卓相关处理

window.webGetDeviceId = function (callback) {
  window.callback = callback;
};
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleLogin: false,
      userData: {}, // 用户及房间数据
      patList: [], // 就诊等待数据
      waitPat: [],
      patListArea: [], //区域等待就诊患者数据
      roomObj: {},
      delayPat: [], //候诊数据
      showType: 'doctor', // doctor医生诊室 area诊区叫号 operate手术室
      cache: {},
      colorName: localStorage.getItem('ZZJ-color'), // white-bg白色 dark-bg深色
      audioSrc: '', // 音频路径
      deviceID: '',
      hosLogo: '',
    };
  }
  componentDidMount() {
    this.initDevice();
  }
  initDevice = async () => {
    //接收Android端身份证信息函数
    window.webGetDeviceId = (deviceId) => {
      Toast.show({
        duration: 10000,
        content: deviceId + '安卓',
      });
      this.setState({
        deviceID: deviceId,
      }, () => {
        this.loginInit();
      });
    };
    const ua = navigator.userAgent.toLowerCase();
    if (/android/.test(ua)) {
      window.JavaClientCall && window.JavaClientCall.getDeviceID();
    }
    // const fp = await FingerprintJS.load();
    // const AndroidInfo = await fp.get();
    
  };
  // 改变颜色
  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);
  };
  openLogin = (cache) => {
    if (!cache) {
      cache = {
        BASE_URL: 'http://10.1.42.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,
          patListArea: newArray,
          roomObj,
          delayPat: data.delayPat,
        });
        if (!data.path || !data.voiceFileName) {
          return;
        }
        this.setState({
          audioSrc: data.path + data.voiceFileName,
        }, () => {
          const domAudio = document.querySelector('#audio');
          domAudio.currentTime = 0;
          domAudio.play();
        });
      }
    });
  };
  //登录事件
  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 手术室
          });
          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}
              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
        style={{ position: 'fixed', right: 0, bottom: 0, padding: '1rem' }}
      >
        <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 src={this.state.audioSrc} controls id="audio" style={{display: 'none'}}></audio>
    </>
    );
  }
}
export default Home;