/*
 * Creator:     柿子
 * CreateDate:  2023-09-20
 * Describe：   Table列授权
 * */
import React, { Component } from 'react';
import { Modal, message, Input, Select, Button, Tooltip, Icon } from 'antd';
import { ArraySome } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import '../style/index.less';

class TableColumnAuthorization extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      hospID: userData?.hospID || undefined,
      visible: false,
      rowData: {},
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 0,
      selectData: {},
      defaultAuthID: undefined,
      authID: undefined,
      columnsObj: {},
      statusFlag: 'D', // 状态 - 默认显示
      alias: undefined, // 代码/描述
      selectedRowKeys: [],
      historySelectedKeys: [], // 历史勾选数据 - 用于对比是否修改过
      hospSelectData: [], // 医院
    };
    this.statusOption = [{
      id: 'D',
      descripts: '显示'
    }, {
      id: 'H',
      descripts: '隐藏'
    }]
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  // 修改弹窗状态
  modifyVisible = (visible, record = {}) => {
    let { rowData, userData, selectData, columns, defaultAuthID } = this.state;
    if (visible && !(columns && columns.length > 0)) {
      this.getTableColumns();
    }
    if (visible && defaultAuthID && rowData?.id !== record?.id) { // 默认类型
      this.state.authID = defaultAuthID;
      this.state.statusFlag = 'D';
      this.state.hospID = userData?.hospID || undefined;
      this.state.alias = undefined;
    }
    this.setState({ visible, rowData: record }, () => {
      if (visible && (selectData?.optionFlag !== 'Y')) {
        this.getSelectData();
        this.getHospSelectData();
      } else {
        visible && this.getTableData();
      }
    })
  }

  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '01040094');
      let authList = res?.result?.authList || [], authID = undefined;
      if (authList && authList.length > 0) {
        authID = authList[0]?.id || authList[0]?.value || undefined; // 默认类型
      }
      this.setState({ selectData: { ...(res?.result || {}), optionFlag: 'Y' }, authID, defaultAuthID: authID }, () => {
        this.getTableData();
      });
    } catch (error) {
      console.log(error);
    }
  }

  getHospSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '01040102');
      this.setState({ hospSelectData: res?.result?.data || [] });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'TableColumnAuthorization',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      this.setState({ columns: res.result?.C || [], totalWidth: res?.totalWidth || '1000px' });
    } catch (error) {
      console.log(error);
    }
  }

  handleStatusChange = e => {
    this.setState({ statusFlag: e });
  }

  handlePreInputChange = (e, dataIndex) => {
    const { historySelectedKeys, selectedRowKeys } = this.state;
    console.log('historySelectedKeys', historySelectedKeys, selectedRowKeys)
    if (JSON.stringify(historySelectedKeys) !== JSON.stringify(selectedRowKeys)) {
      Modal.confirm({
        title: '保存提醒',
        content: '数据操作未保存，是否需要保存？',
        okText: '是 -> 保存',
        cancelText: '否 -> 不保存',
        onOk: () => this.handleOk(this.handleInputChange, e, dataIndex),
        onCancel: () => this.handleInputChange(e, dataIndex),
      });
    } else {
      this.handleInputChange(e, dataIndex);
    }
  }

  // 切换类型
  handleInputChange = (e, dataIndex) => {
    this.state[dataIndex] = e;
    this.setState({}, () => {
      this.handleQuery();
    });
  }

  handleQuery = () => {
    this.state.statusFlag = 'D';
    this.state.alias = undefined;
    this.setState({}, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      const { rowData, authID, hospID } = this.state;
      this.setState({ loading: true });
      let data = {
        params: [{
          tableColID: rowData?.id || '',
          type: authID,
          // alias, // 前端过滤
          hospID
        }]
      }
      let res = await React.$asyncPost(this, '01040298', data);
      let tableData = res.result?.rows || [];
      for (let i = 0; i < tableData.length; i++) {
        tableData[i].key = tableData[i]?.id || (i + 1);
        tableData[i].alias = (tableData[i]?.code || '') + '^' + (tableData[i]?.descripts || '')
      }
      let selectedRowKeys = ArraySome.ArrayWeigh(res.result?.authData || [], 'remove'); // 先去重，后台返回存在相同的情况
      this.setState({
        loading: false,
        tableData,
        copyTableData: JSON.parse(JSON.stringify(tableData)),
        statusFlag: res?.result?.authMode || 'D'
      }, () => {
        setTimeout(() => {
          this.setState({ // 回显问题
            historySelectedKeys: JSON.parse(JSON.stringify(selectedRowKeys)),
            selectedRowKeys: [...selectedRowKeys],
          });
        }, 0)
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  }

  handleAliasChange = e => {
    const { copyTableData } = this.state;
    let alias = e.target.value;
    if (!alias) {
      this.state.tableData = copyTableData;
    }
    this.setState({ alias });
  }

  handleFilterTableData = () => {
    const { copyTableData, alias } = this.state;
    let tableData = copyTableData && copyTableData.filter(item => item.alias.indexOf(alias) > -1);
    this.setState({ tableData });
  }

  // 保存
  handleOk = async (callback, params1, params2) => {
    try {
      const { rowData, authID, statusFlag, hospID, selectedRowKeys, historySelectedKeys } = this.state;
      console.log('historySelectedKeys', historySelectedKeys);
      console.log('selectedRowKeys', selectedRowKeys)
      let data = {
        params: [{
          hospID,
          tableColID: rowData?.id || '',
          authMode: statusFlag,
          authType: authID,
          authDataIDArr: selectedRowKeys,
          invalidArr: historySelectedKeys.filter(item => !selectedRowKeys.includes(item)), // 失效数据传给后台过滤
        }]
      }
      let res = await React.$asyncPost(this, '01040299', data);
      message.success(res?.errorMessage || '保存成功');
      this.setState({ historySelectedKeys: JSON.parse(JSON.stringify(selectedRowKeys)) })
      callback && callback(params1, params2);
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    const { rowData, visible, loading, tableData, columns, totalWidth, authID, selectData, statusFlag, hospID, alias, selectedRowKeys, hospSelectData } = this.state;
    let rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
        })
      },
    };

    return (
      <Modal
        title={'【' + (rowData?.descripts || '') + '】列授权'}
        width="720px"
        okText="保存"
        visible={visible}
        bodyStyle={{ padding: '12px' }}
        onCancel={() => this.modifyVisible(false)}
        onOk={() => this.handleOk()}
      >
        <div className="table-body-height">
          <div style={{ marginBottom: '12px' }}>
            <Select
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              style={{ width: '120px' }}
              value={authID}
              onChange={(e) => this.handlePreInputChange(e, 'authID')}
            >
              {React.$SelectOptions(selectData?.authList || [], 'value')}
            </Select>
            {authID !== 'H' && authID !== 'G' ? ( // 按角色和按医院保存不需要选择医院
              <>
                操作医院
                <Tooltip title="选择对应医院处理科室和用户授权，默认是当前登录医院！">
                  <Icon style={{ marginLeft: '4px', color: '#999' }} type="question-circle" />
                </Tooltip>
                ：
                <Select
                  showSearch
                  placeholder="请选择"
                  optionFilterProp="search"
                  className="common-query-input"
                  style={{ width: '200px' }}
                  value={hospID}
                  onChange={(e) => this.handlePreInputChange(e, 'hospID')}
                >
                  {React.$SelectOptions(hospSelectData)}
                </Select>
              </>
            ) : ''}
            授权状态
            <Tooltip title="根据勾选的数据设置对应状态。栗子：状态选择隐藏，勾选了一个数据，就代表勾选的数据隐藏，其他的数据显示；反之一样">
              <Icon style={{ marginLeft: '4px', color: '#999' }} type="question-circle" />
            </Tooltip>：<Select
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              style={{ width: '80px' }}
              value={statusFlag}
              onChange={this.handleStatusChange}
            >
              {React.$SelectOptions(this.statusOption)}
            </Select>
          </div>
          <div className="flex-between-center" style={{ border: '1px solid #e8e8e8', borderBottom: 0, padding: '8px 12px', borderRadius: '4px 4px 0 0' }}>
            <div className="flex-align-items">
              别名：
              <Input
                placeholder="输入代码/描述检索"
                className="common-query-input"
                style={{ width: '160px' }}
                value={alias}
                onChange={this.handleAliasChange}
                onPressEnter={this.handleFilterTableData}
              />
              <Button
                type="primary"
                onClick={this.handleFilterTableData}
              >
                查询
              </Button>
            </div>
            <span className="span" style={{ fontWeight: 'normal' }}>已勾选 <strong>{selectedRowKeys.length}</strong> 个</span>
          </div>
          <PublicTablePagination
            param={{
              loading,
              columns, // 表头配置
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: store.getState().tableHeight.y - 200,
              height: store.getState().tableHeight.y - 150 + 'px',
              componentName: 'TableColumnAuthorization',
            }}
            rowSelectionPublic={rowSelection}
            getColumns={this.getTableColumns}
          />
        </div>
      </Modal>
    )
  }
};

export default TableColumnAuthorization;