/*
 * Creater:     shizi
 * CreateDate:  2022/05/12
 * Describe：   抗菌药物权限配置
 * */
import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, message, Checkbox } from 'antd';
// import { $http } from 'containers/config/https';
import { Util } from 'tools';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

class AntibioticsPermissionConfig extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      modifyData: [], // 修改的数据
      hospID: userData?.hospID,
      locID: undefined,
      titleID: undefined, // 职称
      doctorID: undefined,
      selectData: {}, // 下拉数据
      locDocSelectData: {}, // 科室医生下拉数据
      columns: [],
      tableData: [],
      historyTableData: [], // 历史table数据
      total: 0,
      page: 1,
      pageSize: 20,
      loading: false,
      totalwidth: 800,
    };

    this.staticColumns = [{
      key: 1,
      title: '科室',
      dataIndex: 'locDesc',
      align: "center",
      width: 150
    }, {
      key: 2,
      title: '职称',
      dataIndex: 'titleDesc',
      align: "center",
      width: 150
    }, {
      key: 3,
      title: '医生姓名',
      dataIndex: 'doctorName',
      align: "center",
      width: 150
    }, {
      key: 4,
      title: '一级抗菌药物使用标志（门诊）',
      dataIndex: 'KSS1OPFlag',
      align: "center",
    }, {
      key: 5,
      title: '二级抗菌药物使用标志（门诊）',
      dataIndex: 'KSS2OPFlag',
      align: "center",
    }, {
      key: 6,
      title: '三级抗菌药物使用标志（门诊）',
      dataIndex: 'KSS3OPFlag',
      align: "center",
    }, {
      key: 7,
      title: '一级抗菌药物使用标志（住院）',
      dataIndex: 'KSS1IPFlag',
      align: "center",
    }, {
      key: 8,
      title: '二级抗菌药物使用标志（住院）',
      dataIndex: 'KSS2IPFlag',
      align: "center",
    }, {
      key: 9,
      title: '三级抗菌药物使用标志（住院）',
      dataIndex: 'KSS3IPFlag',
      align: "center",
    }];
  }

  componentDidMount() {
    this.getTableColumns();
    this.getSelectData();
    this.getLocDocSelectData();
    this.handleQuery();
  }

  // 获取下拉列表数据
  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '03050282');
      this.setState({ selectData: res.result })
    } catch (error) {
      console.log(error)
    }
  }

  // 根据医院获取科室和医生下拉数据
  getLocDocSelectData = async () => {
    try {
      let { hospID } = this.state;
      let data = {
        params: [{
          hospID
        }]
      }
      let res = await React.$asyncPost(this, '03050283', data);
      this.setState({ locDocSelectData: res.result })
    } catch (error) {
      console.log(error)
    }
  }

  // 获取列表columns
  getTableColumns = async () => {
    let { userData } = this.state;
    try {
      let data = {
        params: [{
          compontName: "AntibioticsPermissionConfig",
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
        return {
          ...item,
          key: index + 1,
          title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
          render: (text, rRecord, rIndex) => {
            return (
              (text === 'Y' || text === 'N') ? (
                <Checkbox
                  checkedChildren="是"
                  unCheckedChildren="否"
                  checked={text === 'Y' ? true : false}
                  onChange={(e) => this.handleCheckoutChange(e, rIndex, item.dataIndex)}
                />
              ) : text
            )
          }
        }
      }) : '';
      let filterArr = arr.filter(function (item) { return item.display === 'Y' });
      this.setState({
        columns: filterArr,
        totalwidth: parseInt(res.totalWidth)
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 修改checkout状态
  handleCheckoutChange = (e, index, dataIndex) => {
    let ksFlag = ['KSS1OPFlag', 'KSS1IPFlag', 'KSS2OPFlag', 'KSS2IPFlag', 'KSS3OPFlag', 'KSS3IPFlag']
    let tableData = JSON.parse(JSON.stringify(this.state.tableData));
    let checked = e.target.checked ? 'Y' : 'N';
    tableData[index][dataIndex] = checked;
    if (dataIndex === 'all') { // 全选联动其他选择
      for (var j = 0; j < ksFlag.length; j++) {
        tableData[index][ksFlag[j]] = checked;
      }
    } else { // 单个选择数据联动全选反选
      if (checked === 'N') {
        tableData[index].all = 'N';
      } else {
        for (var i = 0; i < ksFlag.length; i++) {
          tableData[index].all = 'Y';
          if (ksFlag[i] !== dataIndex && (tableData[index][ksFlag[i]] === 'N')) {
            tableData[index].all = 'N';
            break;
          }
        }
      }
    }
    this.setState({ tableData }, () => {
      this.getModifyData();
    })
  }

  // 获取待保存数据
  getModifyData = () => {
    let { historyTableData, tableData } = this.state;
    let modifyData = [];
    for (var i = 0; i < tableData.length; i++) {
      for (var j = 0; j < historyTableData.length; j++) {
        if ((tableData[i].key === historyTableData[j].key) && (JSON.stringify(tableData[i]) !== JSON.stringify(historyTableData[j]))) {
          modifyData.push(tableData[i]);
        }
      }
    }
    this.setState({ modifyData })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, loading: true }, () => {
      this.getTableData();
    })
  }

  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    // 修改page，或者pageSize
    this.setState({ page, pageSize, loading: true }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      let { hospID, locID, titleID, doctorID, pageSize, page } = this.state;
      let data = {
        params: [{
          hospID,
          locID,
          titleID,
          doctorID,
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '03050284', data);
      let tableData = res.result && res.result.rows && Array.isArray(res.result.rows) ? res.result.rows : [];
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].key = i + 1;
        tableData[i].all = 'N';
        if (tableData[i].KSS1OPFlag === 'Y' && tableData[i].KSS1IPFlag === 'Y' && tableData[i].KSS2OPFlag === 'Y' && tableData[i].KSS2IPFlag === 'Y' && tableData[i].KSS3OPFlag === 'Y' && tableData[i].KSS3IPFlag === 'Y') {
          tableData[i].all = 'Y'
        }
      }
      this.setState({ tableData, historyTableData: tableData, total: res.result.total, loading: false, selectedRowKeys: [], modifyData: [] });
    } catch (error) {
      this.setState({ tableData: [], historyTableData: [], total: 0, loading: false, selectedRowKeys: [], modifyData: [] })
    }
  }

  // 保存
  handleSave = async () => {
    try {
      let { modifyData, userData } = this.state;
      let data = {
        params: modifyData
      }
      let res = await React.$asyncPost(this, '03050285', data);
      message.success(res && res.errorMessage ? res.errorMessage : '保存成功', userData && userData.messageTime);
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 医院下拉时间
  handleHospChange = e => {
    this.setState({ hospID: e, locID: undefined, doctorID: undefined }, () => {
      this.getLocDocSelectData();
    })
  }

  render() {
    let { modifyData, selectData, locDocSelectData, hospID, locID, titleID, doctorID, columns, tableData, total, page, loading, totalwidth } = this.state;
    // 组件所需参数
    const param = {
      // 表头配置
      columns: columns && columns.length > 0 ? columns : this.staticColumns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total,
      page,
      pageSize: "20",
      loading,
      // 表格的宽度
      x: totalwidth,
      y: store.getState().tableHeight.y + 6,
      height: store.getState().tableHeight.y + 56 + 'px'
    }

    return (
      <div className='hospital-information'>
        <Row className='query-table-header'>
          <Col span={22} style={{ display: 'flex', alignItems: 'center' }}>
            医院：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={hospID}
              onChange={this.handleHospChange}
              style={{ width: '220px', marginRight: '12px' }}
            >
              {selectData && 'hosp' in selectData && selectData.hosp ? React.$SelectOptions(selectData.hosp) : ''}
            </Select>
            科室：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={locID}
              onChange={Util.handleSelectChange.bind(this, 'locID')}
              style={{ width: '150px', marginRight: '12px' }}
            >
              {locDocSelectData && 'loc' in locDocSelectData && locDocSelectData.loc ? React.$SelectOptions(locDocSelectData.loc) : ''}
            </Select>
            职称：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={titleID}
              onChange={Util.handleSelectChange.bind(this, 'titleID')}
              style={{ width: '150px', marginRight: '12px' }}
            >
              {selectData && 'title' in selectData && selectData.title ? React.$SelectOptions(selectData.title) : ''}
            </Select>
            医生：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={doctorID}
              onChange={Util.handleSelectChange.bind(this, 'doctorID')}
              style={{ width: '150px', marginRight: '12px' }}
            >
              {locDocSelectData && 'doctor' in locDocSelectData && locDocSelectData.doctor ? React.$SelectOptions(locDocSelectData.doctor) : ''}
            </Select>
            <Button onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={2} style={{ textAlign: 'right' }}>
            <Button type="primary" onClick={this.handleSave} disabled={modifyData && modifyData.length > 0 ? false : true}>
              保存
            </Button>
          </Col>
        </Row>
        <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: "24px 24px 12px 24px" }} className="table-body-height">
          {/* handelThis将夫组件的属性与方法给子组件访问 */}
          <PubilcTablePagination param={param} compilePage={this.compilePage} />
        </div>

        {/* 修改表头信息 */}
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName='AntibioticsPermissionConfig'
          configType="C"
          onRef={ref => this.columnRef = ref}
          reloadData={this.getTableColumns}
        />
      </div>
    )
  }
};

export default AntibioticsPermissionConfig;