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 BigScreenOld from '@pages/bigScreen/IndexOld.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 = {
      isGm: false,
      visibleLogin: false,
      userData: {}, // 用户及房间数据
      patList: [], // 就诊等待数据
      waitPat: [],
      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': '专家诊室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' },
            ],
          }
        },
        {
          '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' },
            ],
          }
        },
      ],
      roomObjtmp: {},
      patListArea: [],
      updateTime: '',
    };
  }
  componentDidMount() {
    this.initDevice();
    this.initAndroidVoice();
    const test = () => {
      var start = 0;
      setTimeout(() => {
        if (start > 12) {
          return;
        }
        const data = this.state.tempList[start];
        const patList = [...data.callMsg.callPat, ...data.callMsg.waitPat.map(v => {
          return { ...v, status: 'waiting' };
        })];
        const { roomObjtmp } = this.state;
        roomObjtmp[data.roomDesc] = data;
        const newArray = Object.keys(roomObjtmp).map(key => {
          return roomObjtmp[key];
        });
        this.setState({
          userData: {
            ...data?.userData,
            areaDesc: data.locDesc, // 大屏诊区
            roomDesc: data.roomDesc, // 诊室
          },
          patList,
          callPat: data.callMsg.callPat,
          waitPat: data.callMsg.waitPat,
          reWaitPat: data.callMsg.reWaitPat,
          roomObj: data,
          delayPat: data.delayPat,
          roomObjtmp: roomObjtmp,
          patListArea: newArray,
        });
        ++start;
      }, 1000);
    };
    //test();
  }
  initAndroidVoice() {
    window.mediaPlayOver = (flag) => {
      if (flag == 'success') {
        this.state.voiceList.splice(0, 1);
        this.setState({
          voiceList: this.state.voiceList,
        }, () => {
          this.soundPaly();
        });
      } else {
        Toast.show({
          duration: 10000,
          content: '播放失败',
        });
      }
    };
  }
  soundPaly() {
    const isDev = import.meta.env.MODE == 'development';
    if (isDev || (this.state.voiceList.length > 0)) {
      this.setState({
        myStatus: true,
      }, () => {
        const ua = navigator.userAgent.toLowerCase();
        if (/android/.test(ua)) {
          const src = isDev ? 'https://np.h03.p0551.com/images/wav/eba7ea72748b33c07d55ca7c443d6146.wav' : this.state.voiceList[0];
          window.JavaClientCall && window.JavaClientCall.mediaFilePlay(src);
        }
      });
    } else {
      this.setState({
        myStatus: false
      });
    }
  }

  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,
      isGm: !this.state.isGm,
    });
    // localStorage.setItem('ZZJ-color', colorName);
  };
  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 { roomObjtmp } = this.state;
        roomObjtmp[data.roomDesc] = data;
        const newArray = Object.keys(roomObjtmp).map(key => {
          return roomObjtmp[key];
        });
        this.setState({
          userData: {
            ...data?.userData,
            areaDesc: data?.locDesc || '', // 大屏诊区
            roomDesc: data?.roomDesc || '', // 诊室
          },
          patList,
          callPat: data?.callMsg?.callPat || [],
          waitPat: data?.callMsg?.waitPat || [],
          reWaitPat: data?.callMsg?.reWaitPat || [],
          updateTime: data?.callMsg?.updateTime || '',
          roomObj: data,
          delayPat: data.delayPat,
          roomObjtmp: roomObjtmp,
          patListArea: newArray,
        });
        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();
          }
        });
      }
    });
  };
  //登录事件
  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}
              callPat={this.state.callPat}
              waitPat={this.state.waitPat}
              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}
              />
              : this.state.isGm
                ? <BigScreen
                  userData={this.state.userData}
                  roomObj={this.state.roomObj}
                  delayPat={this.state.delayPat}
                  hosLogo={this.state.hosLogo}
                />
                : < BigScreen
                  userData={this.state.userData}
                  roomObj={this.state.roomObj}
                  patListArea={this.state.patListArea}
                  delayPat={this.state.delayPat}
                  hosLogo={this.state.hosLogo}
                />
          }
          <span
            className='bottom-set'
          >
            {/* 测试用，现在出现的问题就是显示的与实际的数据不符，不知道是没有监听到还是前端拿到了数据没更新 */}
            {!!(this.state?.updateTime) && (
              <span style={{ color: this.state.colorName == 'dark-bg' ? '#fff' : '#0D2764', marginLeft: '10px' }}>
                {this.state?.updateTime || ''}
              </span>
            )}
            <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>
        </div>
      </>
    );
  }
}
export default Home;
