/*
 * Create:      shizi
 * CreateDate:  2022/06/24
 * Describe：   诊断维护
 * */
import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, message } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';

class DiagnosticMaintenance extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      hospID: userData?.hospID,
      alias: undefined, // 别名
      eyesMark: '', // 眼科诊断
      status: '',
      subCatSelectData: [], // 医嘱子类下拉数据
      columns: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      loading: false,
      totalWidth: 2200,
      formData: [], // 表单数据
      rowData: {}, // 行数据
      ICDSelectData: [],
      selectData: [], // 主诊断类型
    };

    this.staticColumns = [{
      key: 1,
      title: '序号',
      dataIndex: 'key',
      align: 'center',
      width: 80
    }, {
      key: 2,
      title: '代码',
      dataIndex: 'code',
      align: 'center',
      width: 150
    }, {
      key: 3,
      title: '描述',
      dataIndex: 'descripts',
      align: 'center',
      width: 300
    }, {
      key: 4,
      title: 'ICD诊断',
      dataIndex: 'iCDDesc',
      align: 'center',
      width: 300
    }, {
      key: 16,
      title: '眼科诊断',
      dataIndex: 'eyesMark',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '损伤中毒标识',
      dataIndex: 'injuryMark',
      align: 'center',
      width: 150
    }, {
      key: 6,
      title: '病理学标识',
      dataIndex: 'pathologicalMark',
      align: 'center',
      width: 100
    }, {
      key: 7,
      title: '中医诊断标志',
      dataIndex: 'diagnosticMark',
      align: 'center',
      width: 150
    }, {
      key: 8,
      title: '年龄开始',
      dataIndex: 'stAge',
      align: 'center',
      width: 100
    }, {
      key: 9,
      title: '年龄结束',
      dataIndex: 'endAge',
      align: 'center',
      width: 100
    }, {
      key: 10,
      title: '默认性别',
      dataIndex: 'sexDesc',
      align: 'center',
      width: 100
    }, {
      key: 11,
      title: '开始日期',
      dataIndex: 'startDate',
      align: 'center',
      width: 100
    }, {
      key: 12,
      title: '失效日期',
      dataIndex: 'stopDate',
      align: 'center',
      width: 100
    }, {
      key: 13,
      title: '主诊断标识',
      dataIndex: 'mainTypeDesc',
      align: 'center',
      width: 120
    }, {
      key: 14,
      title: '门诊诊断标识',
      dataIndex: 'outPatFlag',
      align: 'center',
      width: 150
    }, {
      key: 15,
      title: '英文描述',
      dataIndex: 'eNDesc',
      align: 'center',
      width: 100
    }];

    this.eyesMarkSelectData = [{
      id: '',
      descripts: '全部',
      descriptsSPCode: 'qb'
    }, {
      id: 'Y',
      descripts: '是',
      descriptsSPCode: 's'
    }, {
      id: 'N',
      descripts: '否',
      descriptsSPCode: 'f'
    }];

    this.statusSelectData = [{
      id: '',
      descripts: '全部',
      descriptsSPCode: 'qb'
    }, {
      id: 'Y',
      descripts: '生效',
      descriptsSPCode: 'sx'
    }, {
      id: 'N',
      descripts: '失效',
      descriptsSPCode: 'sx'
    }];

    this.timeout = null;
  }

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

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

  // 获取列表columns
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: "DiagnosticMaintenance",
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let arr = res.result && res.result.C && Array.isArray(res.result.C) ? res.result.C : [];
      let filterArr = arr.filter(function (item) { return item.display === 'Y' });
      if (filterArr && filterArr.length > 0) {
        this.setState({
          columns: filterArr,
          totalWidth: 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 { eyesMark, alias, status, pageSize, page } = this.state;
      let data = {
        params: [{
          alias,
          eyesMark,
          status
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '03050287', data);
      let tableData = res.result && res.result.rows && Array.isArray(res.result.rows) ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ tableData, total: res.result.total, loading: false });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false })
    }
  }

  // 获取表单数据
  getFormData = () => {
    let { ICDSelectData, selectData } = this.state;
    let formData = [{
      title: '代码',
      dataIndex: 'code',
      typeCode: 'Input',
      required: 'Y',
    }, {
      title: '描述',
      dataIndex: 'descripts',
      typeCode: 'Input',
      required: 'Y',
    }, {
      title: 'ICD诊断',
      dataIndex: 'iCDDesc',
      typeCode: 'SearchSelect',
      valueindex: 'descripts', // 下拉value对应的值
      valueID: 'iCDID', // 选择的valueID
      onSearch: this.handleChargeSearch,
      detailItem: ICDSelectData,
      loading: false
    }, {
      title: '年龄开始',
      dataIndex: 'stAge',
      typeCode: 'InputNumber',
    }, {
      title: '年龄结束',
      dataIndex: 'endAge',
      typeCode: 'InputNumber',
    }, {
      title: '开始日期',
      dataIndex: 'startDate',
      typeCode: 'Date',
      required: 'Y',
      default: 0,
    }, {
      dataIndex: 'stopDate',
      title: '结束日期',
      typeCode: 'Date'
    }, {
      title: '默认性别',
      dataIndex: 'sexID',
      typeCode: 'Select',
      detailItem: selectData?.sex || [],
    }, {
      title: '主诊断标识',
      dataIndex: 'mainTypeID',
      typeCode: 'Select',
      detailItem: selectData?.mainType || [],
    }, {
      title: '英文描述',
      dataIndex: 'eNDesc',
      typeCode: 'Input',
    }, {
      title: '损伤中毒标识',
      dataIndex: 'injuryMark',
      typeCode: 'Switch',
      col: 8,
      formItemCol: { labelCol: 12, wrapperCol: 12 }
    }, {
      title: '病理学标识',
      dataIndex: 'pathologicalMark',
      typeCode: 'Switch',
      col: 8,
      formItemCol: { labelCol: 12, wrapperCol: 12 }
    }, {
      title: '中医诊断标志',
      dataIndex: 'diagnosticMark',
      typeCode: 'Switch',
      col: 8,
      formItemCol: { labelCol: 12, wrapperCol: 12 }
    }, {
      title: '门诊诊断标识',
      dataIndex: 'outPatFlag',
      typeCode: 'Switch',
      col: 8,
      formItemCol: { labelCol: 12, wrapperCol: 12 }
    }, {
      title: '眼科诊断',
      dataIndex: 'eyesMark',
      typeCode: 'Switch',
      col: 8,
      formItemCol: { labelCol: 12, wrapperCol: 12 }
    }];
    this.setState({ formData })
  }

  // ICD诊断搜索事件
  handleChargeSearch = (value) => {
    this.state.formData[2].loading = true;
    this.setState({});
    this.fetchCharge(value, ICDSelectData => this.setState({ ICDSelectData }, () => {
      this.state.formData[2].loading = false;
      this.getFormData();
    }));
  }

  fetchCharge = (value, callback) => {
    value = value.replace(/^\s+/, "").replace(/\s+$/, "");
    if (value === "") {
      let resData = [];
      callback(resData);
      return;
    }
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    function fakeCharge() {
      let data = {
        params: [{
          alias: value
        }],
        pagination: [{
          pageSize: 500,
          currentPage: 1
        }]
      }
      $http.post('urlS', this, {
        code: "05100260",
        data,
        success: function (res) {
          if (res.errorCode === '0') {
            let resData = res.result && 'Data' in res.result && Array.isArray(res.result.Data) ? res.result.Data : res.result;
            callback(resData);
          }
        }
      });
    }
    this.timeout = setTimeout(fakeCharge, 300);
  }

  // 医嘱大类change事件
  handleOrderCatChange = async e => {
    try {
      let data = {
        params: [{
          orderCatID: e,
        }],
      }
      let res = await React.$asyncPost(this, '05100260', data);
      let subCatSelectData = res.result && 'Data' in res.result && Array.isArray(res.result.Data) ? res.result.Data : res.result;
      this.setState({ subCatSelectData }, () => {
        this.getFormData();
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 记录表单的值
  recordFormInput = record => {
    this.setState({ rowData: { ...this.state.rowData, ...record } })
  }

  // 新增
  handleAdd = () => {
    let { rowData } = this.state;
    if (rowData && 'id' in rowData && rowData.id) {
      this.setState({ rowData: {} })
    }
    this.modalFormRef && this.modalFormRef.modifyVisible(true);
  }

  // 编辑
  handleModify = record => {
    record && 'orderCatID' in record && record.orderCatID && this.handleOrderCatChange(record.orderCatID); // 获取医嘱子类下拉数据
    this.setState({ rowData: record }, () => {
      this.modalFormRef && this.modalFormRef.modifyVisible(true);
    })
  }

  // 删除
  handleDelete = async record => {
    try {
      if (!(record && record.id)) return;
      let data = {
        params: [{
          id: record?.id
        }]
      }
      let res = await React.$asyncPost(this, '05100410', data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 保存
  handleSave = async values => {
    try {
      let { rowData } = this.state;
      let data = {
        params: [{
          ...values,
          id: rowData?.id
        }]
      }
      let res = await React.$asyncPost(this, '03050286', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.modalFormRef && this.modalFormRef.modifyVisible(false, 'Y');
      this.setState({ rowData: {} }, () => {
        this.getTableData();
      });
    } catch (error) {

    }
  }

  render() {
    let { eyesMark, alias, status, columns, tableData, total, page, loading, totalWidth, formData, rowData } = this.state;
    let columsOperation = {
      title: '操作',
      dataIndex: 'operation',
      align: 'center',
      fixed: 'right',
      width: 80,
      render: (text, record) => (
        <span>
          <span className='span' onClick={(e) => this.handleModify(record, e)}>编辑</span>
        </span>
      ),
    };

    // 组件所需参数
    const param = {
      // 表头配置
      columns: columns && columns.length > 0 ? [...columns, columsOperation] : [...this.staticColumns, columsOperation],
      // 表格数据
      data: tableData,
      // 数据总条数
      total,
      // 当前页数
      page,
      loading,
      pageSize: '20',
      componentName: 'DiagnosticMaintenance',
      // 表格的宽度
      x: totalWidth,
      y: store.getState().tableHeight.y + 108 - 75,
      height: store.getState().tableHeight.y + 158 - 75 + 'px'
    }
    return (
      <div className='hospital-information'>
        <Row className='query-table-header'>
          <Col span={18}>
            别名：<Input
              placeholder="请输入代码/描述"
              value={alias}
              onChange={Util.commonInputChange.bind(this, 'alias')}
              style={{ width: '150px', marginRight: '12px' }}
              onPressEnter={this.handleQuery}
            />
            眼科诊断：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={eyesMark}
              onChange={Util.handleSelectChange.bind(this, 'eyesMark')}
              style={{ width: '150px', marginRight: '12px' }}
            >
              {React.$SelectOptions(this.eyesMarkSelectData)}
            </Select>
            状态：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={status}
              onChange={Util.handleSelectChange.bind(this, 'status')}
              style={{ width: '150px', marginRight: '20px' }}
            >
              {React.$SelectOptions(this.statusSelectData)}
            </Select>
            <Button onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={6} style={{ textAlign: 'right' }}>
            <Button
              className="add-btn-nohover"
              icon="plus"
              style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}
              onClick={this.handleAdd}
            >
              新增诊断
            </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}
            getColumns={this.getTableColumns}
          />
        </div>

        <PublicModalFormHooks
          onRef={ref => this.modalFormRef = ref}
          formData={formData}
          rowData={rowData}
          formItemCol={{ labelCol: 8, wrapperCol: 16, col: 12 }}
          recordFormInput={this.recordFormInput}
          handleSave={this.handleSave}
        />
      </div>
    )
  }
};

export default DiagnosticMaintenance;