/*
 * Creator:     ML
 * CreatDate:   2019-08-20
 * descripts：  个人信息  更换登录角色
*/
import React from 'react';
import { Form, Modal, Table, message, Tooltip, Switch, Input, Icon } from 'antd';
import { $http } from '../../containers/config/https';
import { withRouter } from 'react-router-dom';
import store from '../../store';
import './css/index.less';

const ChangeRoles = Form.create()(
  class ChangeRoles extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        userData: {},
        visible: false,//是否弹切换信息
        rowId: '', // 选中行id
        patientInfo: {},
        status: {},//操作状态
        Info: {},//病人所有基本信息
        columnData: [],//角色arr
        toolTipVis: true,//默认 当前 显示
        localeProvider: [],
        filterVal: undefined
      }
    }

    componentDidMount() {
      this.props.Onrefs(this)
      this.getMainTableColumns()
    }

    componentWillUnmount() {
      // 组件销毁前将静止让setState修改state的状态
      this.setState = (state, callback) => { return; }
    }

    //获取可切换角色
    getLocArr = () => {
      let data = {
        "params": [{
          userCode: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userCode : "",
          currentLocFlag: "Y"
        }],
        "session": [{
          "loginIp": window.location && window.location.protocol && window.location.host ? (window.location.host.split(":")[0]) : (window.location && window.location.origin ?
            (window.location.origin.split(":")[0] + window.location.origin.split(":")[1]).split("//")[1] : "")
        }]
      };
      $http.post('urlDeault', this, {
        code: "01040043",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            for (var i = 0; i < res.result.logonLocAry.length; i++) {
              let currentRecord = res.result.logonLocAry[i];
              res.result.logonLocAry[i].key = i;
              res.result.logonLocAry[i].searchDesc = currentRecord.logonHospDesc + '^' + (currentRecord.logonHospDescSPCode || '') + '^' + currentRecord.logonLocDesc + '^' + (currentRecord.logonLocDescSPCode || '') + '^' + currentRecord.logonGroupDesc + '^' + (currentRecord.logonGroupDescSPCode || '');
              if (res.result.logonLocAry[i].logonLocID == JSON.parse(sessionStorage.userData).locID && currentRecord.logonGroupID == JSON.parse(sessionStorage.userData).groupID) {
                this.setState({
                  rowId: currentRecord.logonLocID + currentRecord.logonGroupID
                })
              }
            }
            this.setState({
              columnData: res.result.logonLocAry,
              visible: true,
              toolTipVis: true,
            })
          }
        }
      });
    }

    //展示弹窗
    showModals = () => {
      this.getLocArr()
      this.setState({
        userData: JSON.parse(sessionStorage.getItem('userData'))
      }, () => {
        this.getMainTableColumns()
      })
    }

    //关闭关联信息弹窗
    handleCancel = () => {
      this.setState({
        visible: false,
        toolTipVis: false,
        rowId: '',
      })
    }

    //是否默认
    handleSwithChange = (val, record) => {
      let data = {
        params: [{
          userID: JSON.parse(sessionStorage.userData).userID,
          updateUserID: JSON.parse(sessionStorage.userData).userID,
          power: "defaultLogonLoc",
          currentDefLogLocID: record.logonLocLogID,
        }],
      };
      $http.post('urlS', this, {
        code: "01040090",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            if (val == true) {
              message.success(this.state.localeProvider && this.state.localeProvider.ChangeRolesSetUpSuccessfully ? this.setMessage('ChangeRolesSetUpSuccessfully', 'descripts') : "设置成功");
            }
            this.getLocArr()
          }
        }
      });
    }

    //切换菜单
    toMain = (record, sessionID) => {
      //清除patientData 防止病人信息带入其他不相关页面
      if (sessionStorage && sessionStorage.patientData) {
        window.sessionStorage.removeItem("patientData");
      }
      window.sessionStorage.setItem("loginIsSession", 'Y');
      //取值需要 JSON.parse(userData);
      window.sessionStorage.setItem("userData",
        JSON.stringify({
          ...JSON.parse(sessionStorage.getItem('userData')),
          path: record.path,
          defaultMenuType: record.defaultMenuType,
          groupID: record.logonGroupID,
          groupDesc: record.logonGroupDesc,
          locID: record.logonLocID,
          locDesc: record.logonLocDesc,
          hospID: record.logonHospID,
          hospDesc: record.logonHospDesc,
          hospCode: record.logonHospCode,
          sessionID: sessionID && sessionID ? sessionID : JSON.parse(sessionStorage.getItem('userData')).sessionID,
        }));
      store.dispatch({
        type: 'userData',
        value: { loginIs: 'Y' }
      })
      store.dispatch({
        type: 'breadcrumDeleteArr',
        value: {}
      })
      document.title = record && record.logonGroupDesc ? record.logonGroupDesc : "互联网医院综合管理系统"; // 修改项目title
      if (record.path != '') {
        this.props.history.push({ pathname: record.path, state: { params: record?.paras || '' } });
      } else {
        this.props.history.push("/001");
      }

      this.setState({
        visible: false,
        rowId: record.logonLocID + record.logonGroupID,
      })
      this.props.initData();
      /** 重置tabs */
      this.props.resetTabs();
    }

    //设置行属性
    onClickRow = (record) => {
      return {
        // 单击行选中
        onClick: () => {
          if (this.state.rowId === '') {
            // 保存行数据以及ID
            this.setState({ rowId: record.logonLocID + record.logonGroupID })
          } else {
            if (this.state.rowId !== record.logonLocID + record.logonGroupID) {
              this.setState({
                rowId: record.logonLocID + record.logonGroupID,
              })
            } else {
              this.setState({
                rowId: "",
              });
            }
          }
        },
        onDoubleClick: () => {
          // let sWinName = "LR" + parseInt(Math.random() * 100000000);//利用随机数处理WinName
          // window.open('#/001', sWinName, 'width=' + (window.screen.availWidth - 10) + ',height=' + (window.screen.availHeight - 30) + ',top=0,left=0,resizable=yes,status=yes,menubar=no,scrollbars=yes,fullscreen=1');
          // window.sessionStorage.setItem("loginIs", 'N');   // 避免同时存在登录注册和主界面
          if (record && record.logonGroupType) {
            this.getWindowOpenData(record);
          } else {
            this.handleConfirmSwitchingRoles(record);
          }
        }
      }
    }

    // 根据角色类型获取第三方跳转地址
    getWindowOpenData = async (record) => {
      try {
        const userData = React.$getSessionData();
        let data = {
          params: [{
            userCode: userData?.userCode || '',
            groupID: record?.logonGroupID || '',
          }]
        }
        let res = await React.$asyncPost(this, '01040309', data);
        let jumpUrl = res.result?.jumpUrl || '';
        let target = res.result?.target || '_blank';
        if (jumpUrl) {
          window.open(jumpUrl, target); // _self: 当前窗口打开  _blank: 新窗口打开
        } else {
          this.handleConfirmSwitchingRoles(record);
        }
      } catch (error) {
        console.log(error);
      }
    }

    // 切换角色
    handleConfirmSwitchingRoles = (record) => {
      if (this.state.rowId == record.logonLocID + record.logonGroupID) {
        this.toMain(record)
        return
      }
      let ipConfig = React.$getSessionData('ipConfig');
      //更新sessionID
      let data = {
        params: [{
          hospID: record.logonHospID,
          groupID: record.logonGroupID,
          locID: record.logonLocID,
          deviceID: ipConfig?.hostName || '',
          IP: ipConfig?.ipv4 || '',
          mac: ipConfig?.mac || '',
        }],
      };
      $http.post('urlS', this, {
        code: "01040099",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            //更新sessionID 切换菜单
            this.toMain(record, res.result.sessionID)
          }
        }
      })
    }

    // 表格行的类名
    setRowClassName = (record) => {
      return record.logonLocID + record.logonGroupID === this.state.rowId ? 'clickRowStyle' : '';
    }

    resetEditFieldData = () => {
      this.setState({
        rowId: "",
      });
    }

    // 获取主列表columns
    getMainTableColumns = () => {
      let data = {
        params: [{
          compontName: "ChangeRoles", // 切换角色
          reactCode: ['ChangeRoles'],
          type: 'C',
        }]
      }
      $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              // columns: arr, widthTotal: res.totalWidth
              localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
            })
          }
        }
      })
    }

    //国际化
    setMessage(name, message) {
      return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
    }

    // 回车检索角色数据
    handlePressEnter = (e) => {
      this.setState({ filterVal: e.target.value })
    }

    handleFilterTableData = () => {
      let { filterVal, columnData } = this.state;
      return columnData && columnData.filter(item => (item.searchDesc).indexOf((filterVal || '')) > -1)
    }

    render() {
      const { } = this.state
      const columns = [{
        key: '1',
        title: '科室',
        dataIndex: 'logonLocDesc',
        width: 140,
        align: 'center',
        render: (text, record, index) => {
          if (JSON.parse(sessionStorage.userData).locDesc == text && JSON.parse(sessionStorage.userData).groupID == record.logonGroupID && JSON.parse(sessionStorage.userData).hospID == record.logonHospID) {
            return (
              <div className="nowDom" style={{ position: "relative" }}>
                <Tooltip getPopupContainer={() => document.querySelector('.nowDom')} overlayClassName="tooltipDom" placement="left" overlayStyle={{ zIndex: "9999" }} visible={this.state.toolTipVis} title={this.state.localeProvider && this.state.localeProvider.ChangeRolesCurrent ? this.setMessage('ChangeRolesCurrent', 'descripts') : "当前"}>
                  {text}
                </Tooltip>
              </div>
            )
          }
          return (
            text
          )
        }
      }, {
        key: '2',
        title: '角色',
        dataIndex: 'logonGroupDesc',
        width: 130,
        align: 'center'
      }, {
        key: '3',
        title: '所属医院',
        dataIndex: 'logonHospDesc',
        width: 150,
        align: "center",
      }, {
        title: '默认',
        dataIndex: 'operation',
        key: 'action',
        align: "center",
        width: 60,
        render: (text, record, index) => {
          return (
            <Switch checked={record.logLocIsDefault && record.logLocIsDefault == "Y" ? true : false} checkedChildren={this.state.localeProvider && this.state.localeProvider.ChangeRolesYes ? this.setMessage('ChangeRolesYes', 'descripts') : "是"} unCheckedChildren={this.state.localeProvider && this.state.localeProvider.ChangeRolesNo ? this.setMessage('ChangeRolesNo', 'descripts') : "否"} onChange={(val) => this.handleSwithChange(val, record)} />
          )
        }
      }];
      return (
        <div
          tabIndex={1}
          onKeyDown={this.handleOnKeydown}
          style={{ outline: 'none' }}
        >
          <Modal
            width='800px'
            visible={this.state.visible}
            title={this.state.localeProvider && this.state.localeProvider.ChangeRolesChangeTitle ? this.setMessage('ChangeRolesChangeTitle', 'descripts') : "切换角色"}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            pagination='false'
            footer={null}
            className="changeRolesDom"
          >
            <div style={{ minHeight: '226px' }}>
              <div className="flex-between-center" style={{ marginBottom: '8px' }}>
                <div style={{ color: 'rgba(0, 0, 0, 0.85)' }}>
                  {this.state.localeProvider && this.state.localeProvider.ChangeRolesTips ? this.setMessage('ChangeRolesTips', 'descripts') : "请选择需要切换的角色"}
                  <span style={{ color: "#F5222D", fontWeight: "600", marginLeft: '4px' }}>
                    {this.state.localeProvider && this.state.localeProvider.ChangeRoleseditTips ? this.setMessage('ChangeRoleseditTips', 'descripts') : "(如确认选择，请双击确认 )"}
                  </span>
                </div>
                <Input
                  title="可输入科室/角色/医院回车查询，支持首拼检索"
                  prefix={
                    <Icon
                      type="search"
                    />
                  }
                  style={{ width: 300 }}
                  placeholder="科室/角色/医院回车检索（支持首拼）"
                  onPressEnter={this.handlePressEnter}
                />
              </div>
              <Table
                rowKey={record => record.key}
                pagination={false}
                columns={columns}
                dataSource={this.handleFilterTableData()}
                bordered
                onRow={this.onClickRow}
                rowClassName={this.setRowClassName}
                scroll={{ y: 250 }}
                style={{
                  height: '300px', overflow: 'auto'
                }}
              />
            </div>
          </Modal>
        </div>
      )
    }
  });

export default withRouter(ChangeRoles);
