import React from 'react';
import { Input, Form, Modal, Selector, Toast } from 'antd-mobile';
const formRef = React.createRef();
/**
 * @刘丹: 登录公用
 */
class Login extends React.Component {
  constructor() {
    super();
    this.state = {
      hospitalLists: [], // 医院列表
      useLists: [], // 用途列表
      roomLists: [], //医院的诊室列表
      visibleHopSet: false, // 显示医院选择等
      timer: null,
    };
  }
  componentDidUpdate(prev) {
    if (prev.visibleLogin != this.props.visibleLogin && this.props.visibleLogin) {
      setTimeout(() => {
        this.resetData();
      }, 100);
    }
  }
  onCacel = () => {
    this.props.hideLogin();
  };
  // 根据缓存回显数据
  resetData = async() => {
    let cache = localStorage.getItem('ZZJ-base');
    if (!cache) {
      return;
    }
    cache = JSON.parse(cache);
    this.setState({
      visibleHopSet: !!cache.room,
    });
    formRef.current.setFieldsValue(cache);
    this.getHospList();
    if (cache.hospital[0]) {
      this.getUseList(cache.hospital[0]);
    }
    if (cache.use[0]) {
      this.getRoomList(cache.use[0]);
    }
  };
  // 获取医院列表数据
  getHospList = () => {
    React.$fetchPost('05100208', {
      params: [{}],
    }, true).then((res) => {
      this.setState({
        hospitalLists: res?.result?.Data || [],
      });
    });
  };
  // 获取用途列表
  getUseList = (hospID) => {
    return React.$fetchPost('04150021', {
      params: [{
        hospID,
      }],
    }, true).then((res) => {
      this.setState({
        useLists: res?.result?.Data || [],
      });
      return res?.result?.Data;
    });
  };
  // 获取医院下的诊室
  getRoomList = (purposeID) => {
    React.$fetchPost('04150022', {
      params: [{
        purposeID,
      }],
    }, true).then((res) => {
      // 诊室
      this.setState({
        roomLists: res?.result?.Data || [],
      });
    });
  };
  // 设备绑定
  bindDevice = async (flag) => {
    let cache = localStorage.getItem('ZZJ-base');
    if (cache) {
      cache = JSON.parse(cache);
    }
    const values = await formRef.current.validateFields();
    const cacheData = {
      ...cache,
      ...values,
    };
    if (!this.state.visibleHopSet) {
      localStorage.setItem('ZZJ-base', JSON.stringify(cacheData));
      this.setState({
        visibleHopSet: true,
      });
      this.getHospList();
      return;
    }
    const item = this.state.roomLists.find((v) => v.id == cacheData.room);
    React.$fetchPost('04150006', {
      params: [{
        hospID: cacheData.hospital[0] || '',  // 医院ID
        deviceDesc: '叫号屏', // 设备名称
        deviceIP: cacheData.BASE_URL,
        deviceIdentifyCode: this.props.deviceID, // 设备生成的ID
        purposeID: cacheData.use[0] || '', // 用途ID 未使用
        rebindFlag: flag || item.rebindFlag || '',
        deviceDataID: cacheData.room[0] || '', // 诊室设ID
      }],
    }, false).then((res) => {
      localStorage.setItem('ZZJ-base', JSON.stringify(cacheData));
      this.onCacel();
      this.props.loginInit();
    }).catch((err) => {
      // 重新绑定
      if (err.errorCode == '04070009') {
        Modal.confirm({
          content: `设备码:${this.props.deviceID} : ${err.errorCode} ${err.errorMessage}`,
          onConfirm: () => {
            this.bindDevice('1');
          },
        });
      } else {
        Toast.show({
          icon: 'fail',
          duration: 3000,
          content: err.errorMessage || err.errorCode || '请求出错',
        });
      }
    });
  };
  render() {
    return (
      <Modal
        visible={this.props.visibleLogin}
        style={{width: '90%'}}
        title={'设备ID：' + this.props.deviceID}
        okText='确认'
        closeOnMaskClick={true}
        onAction={(itme) => {
          if (itme.key == 'confirm') {
            this.bindDevice();
          } else {
            this.onCacel();
          }
        }}
        onClose={this.onCacel}
        actions={[
          {
            key: 'confirm',
            text: '确认',
          },
          {
            key: 'cancel',
            text: '取消',
          },
        ]}
        content={<>
          <Form
            ref={formRef}
            initialValues={{
              ...this.props.formData,
            }}
            // layout="horizontal"
          >
            <Form.Item
              name="BASE_URL"
              label="域名"
              rules={[{ required: true, message: '请输入域名!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="Address"
              label="地址"
              rules={[{ required: true, message: '请输入地址!' }]}
            >
              <Input />
            </Form.Item>
            {this.state.visibleHopSet && <>
            <Form.Item
              name="hospital"
              label="医院"
              rules={[{ required: true, message: '请选择医院!' }]}
              >
                <Selector
                  columns={2}
                  fieldNames={{
                    label: 'hospDesc',
                    value: 'hospID',
                  }}
                  options={this.state.hospitalLists}
                  onChange={(arr, extend) => {
                    this.getUseList(arr[0]);
                    formRef.current.setFieldValue('use', '');
                    formRef.current.setFieldValue('room', '');
                  }}
                />
            </Form.Item>
            <Form.Item
              name="use"
              label="用途"
              rules={[{ required: true, message: '请选择用途!' }]}
              >
                <Selector
                  columns={2}
                  fieldNames={{
                    label: 'descripts',
                    value: 'id',
                  }}
                  options={this.state.useLists}
                  onChange={(arr, extend) => {
                    this.getRoomList(arr[0]);
                    formRef.current.setFieldValue('room', '');
                  }}
                />
            </Form.Item>
            <Form.Item
              name="room"
              label="诊室"
              rules={[{ required: true, message: '请选择诊室!' }]}
            >
                <Selector
                  columns={2}
                  fieldNames={{
                    label: 'descripts',
                    value: 'id',
                  }}
                  options={this.state.roomLists}
                />
            </Form.Item>
          </>}
          </Form>
        </>}
      >
      </Modal>
    );
  }
}

export default Login;
