// 诊断查询 - 集团病种IDC对照
import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, Table, message, Icon, Divider, Popconfirm, Tabs } from 'antd';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import Moment from 'moment';
import RequestForm from './CBICDDiagnosDirLinkPopu';
import CommonPagination from "../../components/pagination";
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
const { TabPane } = Tabs;

class ICDDiagDirLink extends Component {
  constructor(props) {
    super(props);
    this.state = {
      diagnosisDesc: undefined,
      startDate: Moment(),
      endDate: undefined,
      locID: undefined,
      directoryID: undefined,
      basicHeight: 0,
      tableData: [],
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      medicalType: [],
      visible: false,
      userData: React.$getSessionData(),
      proData: {},
      ICDObj: {},
      selectData: {},
      active: '1', // 默认ICD对照
      depRelatedDisColumns: [],
      depRelatedDisTotalWidth: 0,
      depRelatedDisTableData: [],
      depRelatedDisTotal: [],
      depRelatedDisFormData: [],
      depRelatedDisRowData: {},
      depRelatedDisDirectoryID: undefined, // 病种
      depRelatedDisLocID: undefined, // 科室
      depRelatedDisPageSize: 20,
      depRelatedDisPage: 1,
    };

    this.columns = [
      {
        title: '病种名称',
        dataIndex: 'directoryDesc',
        width: 120,
        align: 'center'
      },
      {
        title: '科室名称',
        dataIndex: 'locDesc',
        width: 120,
        align: 'center'
      },
      {
        title: 'ICD10诊断代码',
        dataIndex: 'iCDCode',
        width: 120,
        align: 'center'
      },
      {
        title: 'ICD10诊断描述',
        dataIndex: 'iCDDesc',
        width: 200,
        align: 'center'
      },
      {
        title: '生效日期',
        dataIndex: 'startDate',
        width: 100,
        align: 'center'
      },
      {
        title: '失效日期',
        dataIndex: 'stopDate',
        width: 100,
        align: 'center'
      },
      {
        title: '操作',
        align: "center",
        width: 100,
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            <Divider type="vertical"></Divider>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleCompile(record, "2")} >
              <span className='span' style={{ color: "red" }}>删除</span>
            </Popconfirm>
          </span>
        ),
      }
    ]
  }

  componentDidMount() {
    this.setState({ basicHeight: document.getElementById("diagnostic-query").clientHeight }, () => {
      this.getSelectData();
      this.getTableData()
    });
  }

  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '01070008');
      let result = res?.result || {};
      this.setState({
        selectData: result,
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 诊断名称
  handleDiagnosisDescChange = e => {
    this.setState({ diagnosisDesc: e.target.value })
  }

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

  // 重置表单
  resetFields = () => {
    this.setState({
      proData: '',
      locID: '',
      diagnosisDesc: '',
      directoryID: '',
      ICDObj: {}
    })
  };

  // 编辑
  handleCompile = (record, num) => {
    if (num == "2") {
      if (record.ID === "") {
        return;
      }
      let { userData } = this.state
      let data = {
        params: [{
          ID: record.rowId,
          updateUserID: userData.userID
        }],
      }
      let that = this
      $http.post("urlS", this, {
        code: "01070003",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success("删除成功")
            that.resetFields();
            that.handleQuery();
          }
        }
      })
    }
    else {
      var ICDObj = { id: record.iCDID, code: record.iCDCode, descripts: record.iCDDesc }
      this.setState({ proData: record, ICDObj: ICDObj }, () => {
        this.showPopu();
      });
    }
  }

  loadMedicalType() {
    var params = {
      params: [{}]
    }
    $http.post('urlDeault', this, {
      code: "05100389",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            medicalType: res.result,
          })
        }
      }
    });
  }

  /**
   * @ByYQL:分页功能
   * 添加分页功能
   * Create 2021-11-30
   */
  // 条数改变的回调
  handleShowSizeChange = (current, size) => {
    this.setState({ page: current, pageSize: size, loading: true }, () => {
      this.getTableData();
    });
  }

  //页码改变的回调
  handlePageChange = (page, pageSize) => {
    this.setState({ page: page, pageSize, loading: true }, () => {
      this.getTableData();
    });
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      this.setState({ loading: true });
      let { diagnosisDesc, directoryID, locID, page, pageSize, active, depRelatedDisPageSize, depRelatedDisPage, depRelatedDisDirectoryID, depRelatedDisLocID } = this.state
      let data = {
        params: [{
          diagnosisDesc: active === '1' ? diagnosisDesc : undefined, // 科室关联病种没有诊断检索
          directoryID: active === '1' ? directoryID : depRelatedDisDirectoryID,
          locID: active === '1' ? locID : depRelatedDisLocID,
        }],
        pagination: [{
          pageSize: active === '1' ? pageSize : depRelatedDisPageSize,
          currentPage: active === '1' ? page : depRelatedDisPage
        }]
      }
      let res = await React.$asyncPost(this, active === '1' ? '01070001' : '01070005', data);
      let tableData = res.result?.rows || [];
      let total = res.result?.total || 0;
      this.state[active === '1' ? 'tableData' : 'depRelatedDisTableData'] = Util.addKeyValueToDataSource(tableData);
      this.state[active === '1' ? 'total' : 'depRelatedDisTotal'] = total;
      this.setState({
        loading: false
      })
    } catch (error) {
      this.setState({
        loading: false
      });
    }
  }

  //弹框
  showPopu = () => {
    let { proData, ICDObj } = this.state
    this.childSelect.showModal(proData, ICDObj);
  };

  handleAdd = () => {
    const { active, depRelatedDisRowData } = this.state;
    switch (active) {
      case '1':
        this.childSelect.showModal();
        break;
      case '2':
        if (depRelatedDisRowData && 'locDiseaseDirLinkID' in depRelatedDisRowData && depRelatedDisRowData.locDiseaseDirLinkID) {
          this.setState({ depRelatedDisRowData: {} })
        }
        this.depRelatedDisRef && this.depRelatedDisRef.modifyVisible(true);
        break;
    }
  };

  onSelectRef = (ref) => {
    this.childSelect = ref;
  };

  // 患者查询页签切换
  handleTabsChange = (key) => {
    this.setState({ active: key }, () => {
      if (key === '2') {
        const { depRelatedDisColumns, depRelatedDisTableData } = this.state; // 获取科室关联病种表头数据
        if (!(depRelatedDisColumns && depRelatedDisColumns.length > 0)) {
          this.getDepRelatedDiseasesColumns();
        }
        if (!(depRelatedDisTableData && depRelatedDisTableData.length > 0)) {
          this.getTableData();
        }
      }
    });
  };

  // 获取科室关联病重表头数据
  getDepRelatedDiseasesColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'DepartmentalRelatedDiseases',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          depRelatedDisColumns: columns,
          depRelatedDisTotalWidth: res.totalWidth
        })
      }
      this.setState({ depRelatedDisFormData: res?.result?.formData || [] });
    } catch (error) {
      console.log(error)
    }
  };

  // 科室关联病种保存
  handleDepRelatedDisSave = async (values) => {
    try {
      const { depRelatedDisRowData } = this.state;
      let data = {
        params: [{
          ...values,
          id: depRelatedDisRowData?.locDiseaseDirLinkID || ''
        }]
      }
      let res = await React.$asyncPost(this, '01070006', data);
      message.success(res?.errorMessage || '保存成功');
      this.depRelatedDisRef && this.depRelatedDisRef.modifyVisible(false, 'Y');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  };

  // 编辑
  handleDepRelatedDisModify = record => {
    this.setState({ depRelatedDisRowData: record }, () => {
      this.depRelatedDisRef && this.depRelatedDisRef.modifyVisible(true);
    })
  };

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

  render() {
    let { diagnosisDesc, basicHeight, tableData, page, total, loading, active, depRelatedDisColumns, depRelatedDisTotalWidth, depRelatedDisFormData, depRelatedDisRowData, selectData, locID, directoryID,
      depRelatedDisDirectoryID, depRelatedDisLocID, depRelatedDisPage, depRelatedDisTotal, depRelatedDisTableData
    } = this.state;

    let operationObj = {
      width: '100px',
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span>
          <Icon type="edit" className="span"></Icon>
          <span className="span" onClick={() => this.handleDepRelatedDisModify(record)}>编辑</span>
          <Divider type="vertical" />
          <Icon type="delete" className="common-record-delete-span"></Icon>
          <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDepRelatedDisDelete(record)} >
            <span className="span common-record-delete-span">删除</span>
          </Popconfirm>
        </span>
      ),
    };
    return (
      <div style={{ height: '100%', padding: '0 12px' }}>
        <Tabs
          activeKey={active}
          onChange={this.handleTabsChange}
        >
          <TabPane tab="ICD对照" key="1" disabled={!!loading}></TabPane>
          <TabPane tab="科室关联病种" key="2" disabled={!!loading}></TabPane>
        </Tabs>
        <Row id="diagnostic-query" style={{ padding: '12px' }}>
          <Col span={20}>
            病种名称：
            <Select
              showSearch
              allowClear
              className="common-query-input"
              optionFilterProp="search"
              placeholder="请选择"
              value={active === '1' ? directoryID : depRelatedDisDirectoryID}
              onChange={Util.handleSelectChange.bind(this, active === '1' ? 'directoryID' : 'depRelatedDisDirectoryID')}
            >
              {React.$SelectOptions(selectData?.dirData || [])}
            </Select>
            {active === '1' && (
              <>
                诊断名称：
                <Input
                  allowClear
                  id="diagnosisDesc"
                  placeholder="请输入"
                  className="common-query-input"
                  value={diagnosisDesc}
                  onChange={this.handleDiagnosisDescChange}
                  onPressEnter={this.handleQuery}
                />
              </>
            )}
            科室名称：
            <Select
              showSearch
              allowClear
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              value={active === '1' ? locID : depRelatedDisLocID}
              onChange={Util.handleSelectChange.bind(this, active === '1' ? 'locID' : 'depRelatedDisLocID')}
            >
              {React.$SelectOptions(selectData?.locData || [])}
            </Select>
            <Button type="primary" onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <Button icon="plus" className="add-btn add-btn-noHover" onClick={this.handleAdd}>新增</Button>
          </Col>
        </Row>
        <div>
          <Table
            columns={active === '1' ? this.columns : [...depRelatedDisColumns, operationObj]}
            dataSource={active === '1' ? tableData : depRelatedDisTableData}
            style={{ height: store.getState().tableHeight.y + 136 - basicHeight + 'px' }}
            scroll={{ x: active === '1' ? 860 : depRelatedDisTotalWidth, y: store.getState().tableHeight.y + 86 - basicHeight }}
            bordered
            loading={loading}
            pagination={false}
            className="table-body-height"
          />
          {/*新增分页功能*/}
          <CommonPagination
            pageSize="20"
            size="small"
            search="search"
            complete={true}
            loading={loading}
            current={active === '1' ? page : depRelatedDisPage}
            total={active === '1' ? total : depRelatedDisTotal}
            dataSource={active === '1' ? tableData : depRelatedDisTableData}
            onShowSizeChange={this.handleShowSizeChange}
            onChange={this.handlePageChange}
          />
        </div>
        <RequestForm selectData={selectData} onRef={this.onSelectRef} handleThis={this} />

        {/* 科室关联病种 */}
        <PublicModalFormHooks
          title="科室关联病种"
          onRef={ref => this.depRelatedDisRef = ref}
          selectData={selectData}
          formData={depRelatedDisFormData}
          rowData={depRelatedDisRowData}
          handleSave={this.handleDepRelatedDisSave}
        />
      </div>
    );
  }
};

export default ICDDiagDirLink;
