// 医嘱项对照 -特殊医嘱项目对照
import React, { Component } from 'react';
import { Card, Row, Col, Input, Select, Button, Table, DatePicker, message } from 'antd';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import Moment from 'moment';
import iconListvisits from 'assets/images/icon_listvisits.png';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import PublicListHead from 'pages/common/PublicListHead'

const { Option } = Select;

class ComparisonOfMedicalOrders extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      unionValue: undefined, // 名称
      subCatID: undefined, // 医嘱子类
      statusCode: undefined, // 状态
      page: 1,
      pageSize: 20,
      tableData: [],
      total: 0,
      loading: false,
      basicHeight: 0,
      detailColumns: [],
      detailTableData: [],
      detailWidth: 0,
      detailPage: 1,
      detailPageSize: 20,
      detailTotal: 0,
      detailLoading: false,
      languageCode: userData && userData.language ? userData.language : "CN", // 国际化语言标识
      hospID: userData && userData.hospID ? userData.hospID : "CN",
      payReasonID: undefined,
      insuItemDesc: undefined,
      stDate: undefined,
      hospSelect: [],
      payReasonSelect: [],
      rowId: "",
      top: 0,
      left: 0,
      insuItemData: [],
      tableColumns: [],
      insuItemID: "",
      detailRowId: ""
    };

    this.columns = [
      {
        title: '代码',
        dataIndex: 'medCode',
        width: 100,
        align: 'center',
      },
      {
        title: '描述',
        dataIndex: 'medDesc',
        width: 150,
        align: 'left',
      },
      {
        title: '简称',
        dataIndex: 'medShortDesc',
        width: 150,
        align: 'left',
      },
      {
        title: '医嘱子类',
        dataIndex: 'subCatDesc',
        width: 100,
        align: 'center',
      },
      {
        title: '状态',
        dataIndex: 'statusDesc',
        width: 80,
        align: 'center',
      }
    ]
  }

  componentDidMount() {
    this.setState({ basicHeight: document.getElementById("comparison-of-medical-orders").clientHeight }, () => {
      // setTimeout(() => {
      //   this.myRef1.current.focus();
      // }, 300)
    });
    this.loadSelectData();
    this.getDetailColumns(); // 医保对照columns
    this.handleHospSelect();
    this.handlpayReasonSelect();
  }

  /***下拉框***/
  //医院下拉框
  handleHospSelect = () => {
    let data = {}
    data = {
      params: [{}]
    }
    $http.post('urlS', this, {
      code: '01040078',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.data) {
          let hospSelect = []
          for (var i = 0; i < res.data.length; i++) {
            hospSelect.push(<Option key={res.data[i].id} seatchprop={res.data[i].descripts + '^' + res.data[i].descriptsSPCode} title={res.data[i].descripts}>{res.data[i].descripts}</Option>)
          }
          this.setState({
            hospSelect
          })
        }
      }
    })
  }

  //费别下拉框
  handlpayReasonSelect = () => {
    let data = {}
    data = {
      params: [{
        hospID: this.state.hospID
      }]
    }
    $http.post('urlS', this, {
      code: '05100129',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.data) {
          let payReasonSelect = []
          for (var i = 0; i < res.data.length; i++) {
            payReasonSelect.push(<Option key={res.data[i].id} seatchprop={res.data[i].descripts + '^' + res.data[i].descriptsSPCode} title={res.data[i].descripts}>{res.data[i].descripts}</Option>)
          }
          this.setState({
            payReasonSelect,
            payReasonID: "3"
          })
        }
      }
    })
  }

  // 获取下拉列表数据
  loadSelectData = () => {
    let { userData } = this.state;
    var params = {
      params: [{
        logonHospID: userData && userData.hospID ? userData.hospID : "",
        logonGroupID: userData && userData.groupID ? userData.groupID : "",
        subCatFlag: 'Y',
        statusFlag: 'Y'
      }]
    }
    $http.post('urlDeault', this, {
      code: "03010037",
      data: params,
      success: function (res) {
        var status = res.result.status
        var statusCode = ''
        if (!Util.isEmpty(status)) {
          for (var i = 0; i < status.length; i++) {
            if (status[i].defaultFlag == 'Y') {
              statusCode = status[i].id
              break
            }
          }
        }
        if (res.errorCode == '0') {
          this.setState({
            subCat: res.result.subCat,
            status: res.result.status,
            statusCode: statusCode
          }, () => {
            this.getTableData()
          })
        }
      }
    });
  }

  // 名称
  handleUnionValueChange = e => {
    this.setState({ unionValue: e.target.value })
  }

  // 医嘱子类
  handleSubCatIDChange = e => {
    this.setState({ subCatID: e })
  }

  // 状态
  handleStatusCodeChange = e => {
    this.setState({ statusCode: e })
  }

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

  // 患者列表 -- 条数改变的回调
  handleLeftShowSizeChange = (current, size) => {
    this.setState({ page: current, pageSize: size }, () => {
      this.getTableData();
    });
  }

  // 患者列表 -- 页码改变的回调
  handleLeftChange = (page, pageSize) => {
    this.setState({ page: page, pageSize }, () => {
      this.getTableData();
    });
  }

  // 查询医嘱项列表
  getTableData = () => {
    let { subCatID, unionValue, statusCode, page, pageSize } = this.state;
    var params = {
      params: [{
        subCatID,
        unionValue,
        statusCode
      }],
      pagination: [{
        pageSize,
        currentPage: page
      }]

    }
    $http.post('urlDeault', this, {
      code: "05100169",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            tableData: res.data,
            total: res.total,
            loading: false,
            rowId: "",
            detailTableData: [],
            detailTotal: 0,
            detailRowId: ""
          })
        } else {
          this.setState({
            tableData: [],
            total: 0,
            loading: false,
            rowId: "",
            detailTableData: [],
            detailTotal: 0,
            detailRowId: ""
          })
        }
      }
    });
  }

  // 操作行 --- 患者列表
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowId === '') {
          // 保存行数据以及ID
          this.setState({ rowId: record.medID }, () => {
            this.handleQueryDetail()
          })
        } else {
          if (this.state.rowId !== record.medID) {
            this.setState({ rowId: record.medID }, () => {
              this.handleQueryDetail()
            })
          }
        }
      }
    }
  }

  setRowClassNamePublic = (record) => {
    return record.medID === this.state.rowId ? 'clickRowStyle' : "";
  }

  // 查询医保对照列表数据
  handleQueryDetail = () => {
    this.setState({ detailPage: 1 }, () => {
      this.getDetailTableData();
    })
  }

  getDetailTableData = () => {
    let { rowId, detailPage, detailPageSize, hospID, insuItemDesc, payReasonID, stDate } = this.state;
    let data = {
      params: [{
        itmID: rowId,
        insuItemDesc: insuItemDesc,
        hospID: hospID,
        payReasonID: payReasonID,
        stDate: stDate ? Moment(stDate).format("YYYY-MM-DD") : undefined
      }],
      pagination: [{
        pageSize: detailPageSize,
        currentPage: detailPage,
        sortColumn: "Code",
        sortOrder: "asc"
      }]
    }

    $http.post('urlS', this, {
      code: '05100373',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.data) {
          for (var i = 0; i < res.data.length; i++) {
            res.data[i].key = i;
          }
          this.setState({ detailTableData: res.data, detailTotal: res.data.length, detailLoading: false, detailRowId: "" })
        } else {
          this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false, detailRowId: "" })
        }
      },
      error: function () {
        this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false, detailRowId: "" })
      }
    })
  }

  // 患者列表 -- 条数改变的回调
  handleRightShowSizeChange = (current, size) => {
    this.setState({ detailPage: current, detailPageSize: size }, () => {
      this.getDetailTableData();
    });
  }

  // 患者列表 -- 页码改变的回调
  handleRightChange = (page, pageSize) => {
    this.setState({ detailPage: page, detailPageSize: pageSize }, () => {
      this.getDetailTableData();
    });
  }

  // 获取一包对照列表columns
  getDetailColumns = () => {
    var data = {
      params: [{
        "reactCode": ["InsuLinkMed"],
        "compontName": "InsuLinkMed",
        "type": "C"
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let resC = res.result.C;
          let { languageCode } = this.state
          for (var i = 0; i < resC.length; i++) {
            resC[i].key = i;
          }
          if (languageCode === "EN") {
            resC.map((item, i) => {
              item.title = item.enDescripts
            })
          }

          if (languageCode === "CN") {
            resC.map((item, i) => {
              item.title = item.descripts
            })
          }
          let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map((item, index) => {
            return {
              align: item.align,
              widthNum: parseInt(item.width),
              width: item.width,
              dataIndex: item.dataIndex,
              title: item.title,
              display: item.display,
              key: index
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          this.setState({
            detailColumns: filterArr,
            detailWidth: res.totalWidth
          })
        }
      }
    })
  }

  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

  // 医院
  handleHospIDChange = e => {
    this.setState({ hospID: e })
  }

  // 费别
  handlePayReasonIDChange = e => {
    this.setState({ payReasonID: e })
  }

  // 医保目录信息
  handleInsuItemDescChange = e => {
    this.setState({ insuItemDesc: e.target.value })
  }

  handleStartChange = e => {
    this.setState({ stDate: e.target.value })
  }

  onRef = ref => {
    this.child = ref;
  }

  // 描述回车事件
  insuItemOnPressEnter = (e) => {
    console.log(e)
    let value = e && e.target && e.target.value ? e.target.value : ""
    this.infoTableList("N");
    ///let top = 0+ 'px';
    // let top =document.getElementById('insuItemInput').getBoundingClientRect().top + 40 + 'px';
    // let left = document.getElementById('insuItemInput').getBoundingClientRect().left + 60 + 'px';
    let top = document.getElementById('insuItemInput').getBoundingClientRect().top + 42 + 'px';
    let left = document.getElementById('insuItemInput').getBoundingClientRect().left - 572 + 'px';
    this.setState({
      top,
      left
    }, () => {
      this.handleInsuQuery(value);
      this.child && this.child.showModal && this.child.showModal();
    });
  }

  // 获取医保信息列表columns
  infoTableList = (isQuery) => {
    let { tableColumns } = this.state;
    if (tableColumns && tableColumns.length > 0 && isQuery === "N") {
      return;
    }
    var data = {
      params: [{
        "reactCode": ['MedicalInsuranceInformation'],
        "compontName": 'MedicalInsuranceInformation',
        "type": "C"
      }]
    }
    console.log(1, data)
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let resC = res.result.C
          let { languageCode } = this.state
          for (var i = 0; i < resC.length; i++) {
            resC[i].key = i;
          }
          if (languageCode === "EN") {
            resC.map((item, i) => {
              item.title = item.enDescripts
            })
          }

          if (languageCode === "CN") {
            resC.map((item, i) => {
              item.title = item.descripts
            })
          }
          let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
            return {
              align: item.align,
              widthNum: parseInt(item.width),
              width: item.width,
              dataIndex: item.dataIndex,
              title: <div onDoubleClick={() => this.child.handleShowOne()}>{item.title}</div>,
              display: item.display,
              key: item.seqNo
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          this.setState({
            tableColumns: filterArr,
          })
        }
      }
    })
  }

  //医保项目明细
  handleInsuQuery = (title) => {
    let { rowId, page, pageSize, hospID, payReasonID } = this.state;
    let data = {
      params: [{
        itmID: rowId,
        insuCode: title,
        insuDesc: title,
        hospID: hospID,
        payReasonID: payReasonID,
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: "Code",
        sortOrder: "asc"
      }]
    }

    $http.post('urlS', this, {
      code: '05100123',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.data) {
          for (var i = 0; i < res.data.length; i++) {
            res.data[i].key = i;
          }
          this.setState({ insuItemData: res.data, insuTotal: res.data.length, loading: false })
        }
      }
    })
  }

  handleModalClickRowPublic = record => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.insuItemID === '') {
          // 保存行数据以及ID
          this.setState({ insuItemID: record.id })
        } else {
          if (this.state.insuItemID !== record.id) {
            this.setState({ insuItemID: record.id })
          }
        }
      },
      onDoubleClick: () => {
        this.confirmSelection(record);
      }
    }
  }

  handleModalRowClassNamePublic = record => {
    return record.id === this.state.insuItemID ? 'clickRowStyle' : '';
  }

  // 双击选中行数据的回调
  confirmSelection = (record) => {
    //this.resetFields();
    this.setState({ insuItemID: record.id, insuItemDesc: record.descripts, modalRowData: record }, () => {
      // 关闭弹窗
      this.child.handleCancel();
    })
  }

  //添加对照
  handleAdd = () => {
    let { rowId, insuItemID, hospID, stDate, payReasonID, userData } = this.state;
    if (insuItemID === "") {
      message("请用选择的医保目录的信息");
      return false;
    }
    let data = {}
    data = {
      params: [{
        itmID: rowId,
        insuItemID,
        hospID,
        updateUserID: userData && userData.userID ? userData.userID : "",
        stDate: stDate ? Moment(stDate).format("YYYY-MM-DD") : undefined,
        payReasonID,
      }]
    }
    $http.post('urlADS', this, {
      code: "05100374",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('对照成功');
          // 刷新列表数据*/
          this.handleQueryDetail();
        }
      },
      error: function (error) {
        message.error('对照失败：' + error);
      }
    })
  }

  // 取消对照
  handleDelete = () => {
    let { detailRowId, userData } = this.state;
    let data = {
      params: [{
        linkID: detailRowId,
        updateUserID: userData && userData.userID ? userData.userID : "",
      }]
    }
    $http.post('urlADS', this, {
      code: '05100376',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('取消对照成功');
          // 刷新列表数据
          this.handleQuery()
        }
      },
      error: function (error) {
        message.error('删除失败：' + error);
      }
    })
  }

  // 医保对照列表行操作
  handleDetailClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowId === '') {
          // 保存行数据以及ID
          this.setState({ detailRowId: record.linkID })
        } else {
          if (this.state.detailRowId !== record.linkID) {
            this.setState({ detailRowId: record.linkID })
          }
        }
      }
    }
  }

  handleDetailRowClassNamePublic = record => {
    return record.linkID === this.state.detailRowId ? 'clickRowStyle' : '';
  }

  render() {
    let { unionValue, subCatID, statusCode, subCat, status, tableData, page, total, basicHeight, loading, detailTableData, detailPage, detailTotal, detailLoading, detailColumns,
      detailWidth, hospID, payReasonID, insuItemDesc, stDate, hospSelect, payReasonSelect, top, left, insuItemData, tableColumns
    } = this.state;

    //医嘱子类
    var subCatOption = [];
    subCat && subCat.map((item, index) => {
      subCatOption.push(<Option key={index} value={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    var statusOption = [];
    status && status.map((item, index) => {
      statusOption.push(<Option key={index} value={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts}>{item.descripts}</Option>)
    })

    let param = {
      width: '1100px',
      top,
      left,
      //columns: this.insuColumns,
      columns: tableColumns,
      data: insuItemData,
      isOnRow: true,
      TableClassName: 'tab-placeholder',
      rowClassName: true,
    }
    return (
      <div className="comparison-of-medical-orders">
        <Row id="comparison-of-medical-orders" style={{ padding: '0 24px' }}>
          <Col span={18} className="input-padding-right">
            <Row style={{ marginBottom: '12px' }}>
              名称：
              <Input value={unionValue} allowClear
                onChange={this.handleUnionValueChange}
                placeholder='输入代码/描述'
                onPressEnter={this.handleQuery}
                style={{ width: '200px', margin: '12px 10px 0 0' }}
              />
              医嘱子类：
              <Select value={subCatID} onChange={this.handleSubCatIDChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择医嘱子类" style={{ width: '200px', margin: '12px 10px 0 0' }}>
                {subCatOption}
              </Select>
              状态：
              <Select value={statusCode} onChange={this.handleStatusCodeChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" style={{ width: '150px', margin: '12px 10px 0 0' }}>
                {statusOption}
              </Select>
              <Button style={{ marginTop: '8px' }} onClick={this.handleQuery}>查询</Button>
            </Row>
          </Col>
          <Col span={6} style={{ textAlign: 'right' }}>
            <Button type="primary" style={{ marginTop: '12px', marginRight: "12px" }} onClick={this.handleAdd}>对照</Button>
            <Button type="danger" style={{ marginTop: '12px' }} onClick={this.handleDelete}>取消对照</Button>
          </Col>
        </Row>
        <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
        <Row>
          <Col span={8}>
            <div style={{ paddingRight: '6px', position: 'relative' }}>
              <Card
                size="small"
                title={<div className="card-title-left-img" style={{ height: '26px' }}><img src={iconListvisits} alt="" />医嘱项列表</div>}
              >
                <div>
                  <Table
                    columns={this.columns}
                    dataSource={tableData}
                    style={{ height: store.getState().tableHeight.y + 91 - basicHeight + 'px', }}
                    scroll={{ x: 480, y: store.getState().tableHeight.y + 41 - basicHeight }}
                    // rowSelection={rowSelection}
                    onRow={this.onClickRowPublic}
                    rowClassName={this.setRowClassNamePublic}
                    // onHeaderRow={() => {
                    //   return {
                    //     onDoubleClick: () => {
                    //       this.columnRef.onOpenModel()
                    //     },
                    //   };
                    // }}
                    bordered
                    rowKey={(data) => {
                      return data.medID
                    }}
                    pagination={false}
                    className="table-body-height" />
                  <CommonPagination current={page} total={total} search="search" pageSize="20"
                    onShowSizeChange={this.handleLeftShowSizeChange} complete={true} dataSource={tableData} size='small'
                    loading={loading} onChange={this.handleLeftChange} />
                </div>
              </Card>
              <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
            </div>
          </Col>
          <Col span={16}>
            <Row style={{ marginLeft: '10px' }}>
              <Col span={22}>
                <Col span={6}>
                  医院：<Select
                    showSearch optionFilterProp="seatchprop" allowClear
                    placeholder="请选择"
                    style={{ width: "190px", margin: '12px 15px 0 0' }}
                    value={hospID}
                    onChange={this.handleHospIDChange}
                  >{hospSelect}</Select></Col>
                <Col span={6}>
                  费别： <Select
                    showSearch optionFilterProp="seatchprop" allowClear
                    style={{ width: '170px', margin: '12px 15px 0 0' }}
                    value={payReasonID}
                    placeholder="请选择"
                    onChange={this.handlePayReasonIDChange}
                  >{payReasonSelect}</Select></Col>
                <Col span={6}>
                  医保目录信息：<Input
                    style={{ width: '130px', margin: '12px 15px 0 0' }}
                    placeholder="请输入"
                    allowClear
                    onChange={this.handleInsuItemDescChange} value={insuItemDesc}
                    onPressEnter={this.insuItemOnPressEnter} id="insuItemInput"
                  />
                </Col>
                <Col span={6}>
                  生效日期：<DatePicker
                    style={{ width: '150px', margin: '12px 15px 0 0' }}
                    format="YYYY-MM-DD"
                    placeholder="请选择生效日期"
                    value={stDate}
                    allowClear
                    onChange={this.handleStartChange}
                  /></Col>
              </Col>
              <Col span={1} style={{ margin: '12px 15px 12px 0', }} >
                <Button onClick={this.handleQueryDetail}>查询</Button>
              </Col>
            </Row>
            <div style={{ padding: '0 12px' }}>
              <PublicListHead
                onClickRowPublic={this.handleModalClickRowPublic}
                setRowClassNamePublic={this.handleModalRowClassNamePublic}
                param={param}
                onRef={this.onRef}
                reloadData={this.infoTableList}
              />
              <Table
                columns={detailColumns}
                dataSource={detailTableData}
                style={{ height: store.getState().tableHeight.y + 91 - basicHeight + 'px', }}
                scroll={{ x: detailWidth ? detailWidth : 1000, y: store.getState().tableHeight.y + 41 - basicHeight }}
                bordered
                rowKey={(data) => {
                  return data.linkID
                }}
                onHeaderRow={() => {
                  return {
                    onDoubleClick: () => {
                      this.columnRef.onOpenModel()
                    },
                  };
                }}
                onRow={this.handleDetailClickRowPublic}
                rowClassName={this.handleDetailRowClassNamePublic}
                pagination={false}
                className="table-body-height" />
              <CommonPagination current={detailPage} total={detailTotal} search="search" pageSize="20"
                onShowSizeChange={this.handleRightShowSizeChange} complete={true} dataSource={detailTableData} size='small'
                loading={detailLoading} onChange={this.handleRightChange} />
            </div>
          </Col>
        </Row>
        <ColumnAuthoritysModel
          clientWidth='900px'
          compontName='InsuLinkCharge'
          configType="C"
          onRef={this.onColumnRef}
          reloadData={this.getDetailColumns}
        />
      </div>
    );
  }
}

export default ComparisonOfMedicalOrders;