/*
 * Creater:     shizi
 * CreateDate:  2022/05/05
 * Describe：   材料发放
 * */
import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, message } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools';
import store from 'store';
import moment from 'moment';
import { dayFormat } from 'tools/index';
import RangeDatePicker from 'components/rangePicker/index';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const { Option } = Select;

class MaterialDistribution extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      startDate: moment().subtract('days', 6).format(dayFormat),  // //开始日期
      endDate: moment().format(dayFormat),  // //结束日期
      locID: undefined,
      areaID: undefined,
      patNo: undefined,
      patID: '',
      metStockID: undefined,
      selectData: {}, // 下拉数据
      columns: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      loading: false,
      totalwidth: 800,
      selectedRowKeys: [],
      materialSelectData: []
    };

    this.staticColumns = [{
      key: 1,
      title: '科室',
      dataIndex: 'ordLocDesc',
      align: "center",
    }, {
      key: 2,
      title: '病区',
      dataIndex: 'wardDesc',
      align: "center",
    }, {
      key: 3,
      title: '床号',
      dataIndex: 'bedNo',
      align: "center",
    }, {
      key: 4,
      title: '登记号',
      dataIndex: 'patNo',
      align: "center",
    }, {
      key: 5,
      title: '姓名',
      dataIndex: 'patName',
      align: "center",
    }, {
      key: 6,
      title: '开单医生',
      dataIndex: 'doctorName',
      align: "center",
    }, {
      key: 7,
      title: '开单时间',
      dataIndex: 'ordDate',
      align: "center",
    }, {
      key: 8,
      title: '材料代码',
      dataIndex: 'medCode',
      align: "center",
    }, {
      key: 9,
      title: '材料名称',
      dataIndex: 'medDesc',
      align: "center",
    }, {
      key: 10,
      title: '数量',
      dataIndex: 'qty',
      align: "center",
    }, {
      key: 11,
      title: '单位',
      dataIndex: 'unitDesc',
      align: "center",
    }, {
      key: 12,
      title: '单价',
      dataIndex: 'sp',
      align: "center",
    }, {
      key: 13,
      title: '金额',
      dataIndex: 'amt',
      align: "center",
    }, {
      key: 14,
      title: '要求执行日期',
      dataIndex: 'reqExecDate',
      align: "center",
    }, {
      key: 15,
      title: '要求执行时间',
      dataIndex: 'reqExecTime',
      align: "center",
    }];

    this.timeout = null;
  }

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

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

  // 获取列表columns
  getTableColumns = async () => {
    let { userData } = this.state;
    try {
      let data = {
        params: [{
          compontName: "MaterialDistribution",
          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>
        }
      }) : '';
      let filterArr = arr.filter(function (item) { return item.display === 'Y' });
      this.setState({
        columns: filterArr,
        totalwidth: parseInt(res.totalWidth)
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 查询
  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 { startDate, endDate, locID, areaID, patID, metStockID, pageSize, page } = this.state;
      let data = {
        params: [{
          startDate,
          endDate,
          ordLocID: locID,
          wardID: areaID,
          patID,
          metStockID
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '02060210', 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 = tableData[i].execID;
        tableData[i].reqExecDateTime = tableData[i].reqExecDate + ' ' + tableData[i].reqExecTime;
      }
      this.setState({ tableData, total: res.result.total, loading: false, selectedRowKeys: [] });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false, selectedRowKeys: [] })
    }
  }

  // 发放
  handleGrant = async () => {
    let { userData, selectedRowKeys } = this.state;
    try {
      let data = {
        params: [{
          execIDArr: selectedRowKeys
        }]
      }
      let res = await React.$asyncPost(this, '02060211', data);
      message.success(res && res.errorMessage ? res.errorMessage : '操作成功', userData && userData.messageTime);
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 表格数据选择
  handleRowSelectionChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys: selectedRowKeys
    })
  }

  handleStartChange = e => {
    this.setState({ startDate: e })
  }

  handleEndChange = e => {
    this.setState({ endDate: e })
  }

  // 病人id
  handlePatientOnChange = (e) => {
    if (!e.target.value) {
      console.log("触发了")
      setTimeout(() => {
        this.setState({ patID: '' })
      }, 300)
    }
    this.setState({ patNo: e.target.value })
  }

  // 查询病人id
  handlePatient = (e, name) => {
    if (!e.target.value) {
      this.setState({ patID: '' })
      return;
    }
    if (this.isNumber(e.target.value)) {
      this.getPatientInformation(e.target.value, name);
    }
  }

  isNumber = (val) => {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
      return true;
    } else {
      return false;
    }
  }

  // 3.2.1.3.13.根据卡号取病人信息
  getPatientInformation = (value, name) => {
    const { userData } = this.state;
    let data = {
      params: [{
        number: value, // 病人登记号/证件号
        cardTypeID: "",   // 卡类型id
        cardNo: "",    // 卡号
      }]
    }
    $http.post('urlS', this, {
      code: '03040004',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ patID: res.data && res.data.patID ? res.data.patID : '' }, () => {
            if (name === 'enter') {
              this.setState({ patNo: res.data && res.data.patNo ? res.data.patNo : '' });
              this.getTableData();
            }
          })
        } else if (res.errorFlag === 'N') {
          this.setState({ tableData: [], total: 0, patID: '', loading: false, patNo: undefined });
          message.error(res.errorMessage, userData && userData.messageTime);
        } else {
          this.setState({ loading: false, patID: '', patNo: undefined });
        }
      },
      error: function () {
        this.setState({ loading: false, patID: '', patNo: undefined });
      }
    })
  }

  // 材料名称搜索
  handleSearch = value => {
    this.getMaterialSelectData(value, materialSelectData => this.setState({ materialSelectData }));
  }

  // 获取材料名称下拉数据
  getMaterialSelectData = (value, callback) => {
    value = value.replace(/^\s+/, "").replace(/\s+$/, "");
    if (value === "") {
      let data = [];
      callback(data);
      return;
    }
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    function getData() {
      let data = {}
      data = {
        params: [{
          alias: value,
          searchType: "Loc"
        }],
      }
      $http.post('urlS', this, {
        code: "02060212",
        data: data,
        success: function (res) {
          if (res.errorCode === '0') {
            callback(res.result);
          }
        }
      })
    }
    this.timeout = setTimeout(getData, 300);
  }

  render() {
    let { selectData, materialSelectData, startDate, endDate, locID, areaID, patNo, metStockID, columns, tableData, loading, totalwidth, selectedRowKeys } = this.state;

    // 组件所需参数
    const param = {
      // 表头配置
      columns: columns && columns.length > 0 ? columns : this.staticColumns,
      // 表格数据
      data: tableData,
      // 数据总条数
      // total,
      // page,
      // pageSize: "20",
      loading,
      isRowSelection: true,
      // 表格的宽度
      x: totalwidth,
      y: store.getState().tableHeight.y + 158 - 102,
      height: store.getState().tableHeight.y + 158 - 102 + 'px'
    }

    let rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectionChange,
    };
    return (
      <div className='hospital-information'>
        <Row className='query-table-header'>
          <Col span={22} style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ marginRight: '12px' }}>
              <RangeDatePicker
                isChange={true}
                label="日期："
                format="YYYY-MM-DD"
                width={320}
                startDate={startDate}
                endDate={endDate}
                startChange={this.handleStartChange}
                endChange={this.handleEndChange}
              />
            </div>
            科室：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={locID}
              onChange={Util.handleSelectChange.bind(this, 'locID')}
              style={{ width: '150px', marginRight: '12px' }}
            >
              {selectData && 'ordLoc' in selectData && selectData.ordLoc ? React.$SelectOptions(selectData.ordLoc) : ''}
            </Select>
            病区：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={areaID}
              onChange={Util.handleSelectChange.bind(this, 'areaID')}
              style={{ width: '150px', marginRight: '12px' }}
            >
              {selectData && 'ward' in selectData && selectData.ward ? React.$SelectOptions(selectData.ward) : ''}
            </Select>
            人员标识：<Input
              title="回车触发病人ID查询"
              allowClear
              placeholder="病人信息回车查询"
              style={{ width: '180px', marginRight: '12px' }}
              value={patNo}
              onBlur={(e) => this.handlePatient(e, 'blur')}
              onChange={this.handlePatientOnChange}
              onPressEnter={(e) => this.handlePatient(e, 'enter')}
            />
            材料名称：<Select
              allowClear
              showSearch
              placeholder="输入名称检索"
              style={{ width: '250px', marginRight: '12px' }}
              defaultActiveFirstOption={false}
              showArrow={false}
              filterOption={false}
              value={metStockID}
              onChange={Util.handleSelectChange.bind(this, 'metStockID')}
              onSearch={this.handleSearch}
              notFoundContent={null}
            >
              {materialSelectData && Array.isArray(materialSelectData) && materialSelectData.map((item, index) => {
                return (
                  <Option
                    value={item.id}
                    key={index}
                    title={item.descripts}
                    seachprop={item.descripts + '^' + item.descriptsSPCode}
                  >
                    {item.descripts}
                  </Option>
                )
              })}
            </Select>
            <Button onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={2} style={{ textAlign: 'right' }}>
            <Button type="primary" disabled={selectedRowKeys && selectedRowKeys.length > 0 ? false : true} onClick={this.handleGrant}>
              发放
            </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} rowSelectionPublic={rowSelection} />
        </div>

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

export default MaterialDistribution;