/*
 * Creator:     ML
 * CreatDate:   2019-12-21
 * descripts：  医嘱查询--查找(住院) 检验结果
 * */
import React from 'react';
import moment from 'moment';
import { Form, Row, Col, Table, Select, Button, } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
// import './style/index.less';
// import './style/doctorAdviceFind.less';
import { dayFormat } from 'tools/index';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import TestResultModal from "pages/workstation/component/TestResultModal.jsx";
import RangeDatePicker from 'components/rangePicker/index';
import OrdersModel from "pages/nurse/orders/ordersModel";
const formItemLayout = { // label 和input宽度
  labelCol: { span: 7 },
  wrapperCol: { span: 17 }
}
const FormItem = Form.Item;
const Option = Select.Option;
const HospitaDoctorAdTest = Form.create()(
  class HospitaDoctorAdTest extends React.Component {
    cacheOriginData = {};
    constructor() {
      super()
      var date = new Date();
      var userData = JSON.parse(sessionStorage.getItem('userData'));
      this.state = {
        userData: userData,
        size: "small",
        search: "",
        page: 1,
        pageSize: 10,
        total: 0,
        columns: [],
        values: {},
        localeProvider: [],
        recordData: [],
        StartDate: moment(date).format(dayFormat),  // //开始日期
        EndDate: moment(date).format(dayFormat),  // //结束日期
      }
    }
    componentDidMount = () => {
      // 初始化设置table的高度以及表体的高度
      if (document.querySelector('.ant-table-body')) {
        if(this.props&&this.props.modal){
          //放置在弹窗上
          document.querySelector(".testResultDom .ant-table-body").style.height =  store.getState().tableHeight.y - 136 + 'px';
          document.querySelector(".testResultDom .ant-table-body").style.maxHeight =  store.getState().tableHeight.y -136 + 'px';
        }else{
          //放置在普通页面上
          document.querySelector(".testResultDom .ant-table-body").style.height =  store.getState().tableHeight.y  - 182 + 'px';
          document.querySelector(".testResultDom .ant-table-body").style.maxHeight =  store.getState().tableHeight.y  - 182 + 'px';
        }
      }
      this.getMainTableColumns()
      setTimeout(() => {
        this.findDatas()
      }, 600);

    }
    onColumnRef = (ref) => {
      this.columnRef = ref;
    }
    onRef = (ref) => {
      this.childRef = ref
    }
    //国际化
    setMessage(name, message) {
      return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
    }
    //开始日期
    startChange(date) {
      this.setState({
        StartDate: date,
      })
    }
    //结束日期
    endChange(date) {
      this.setState({
        EndDate: date,
      })
    }
    // 获取主列表columns
    getMainTableColumns = () => {
      let data = {
        params: [{
          compontName: "LISReport", // 检验报告表头
          reactCode: ['LISReport'],
          type: 'C',
        }]
      }
      $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
              return {
                align: item.align,
                widthNum: parseInt(item.width),
                width: item.width,
                dataIndex: item.dataIndex,
                title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{this.state.userData.language == 'EN' ? item.enDescripts : item.title}</div>,
                display: item.display,
                key: item.seqNo,
                render: (text, record) => {
                  if (item.code == "resultStatus") {
                    return (
                      <span style={{ cursor: "pointer",display:(record.statusNormal==""?"none":"inline-block") }} onClick={(e) => this.handleOpen(e, record)}><span style={{ color: "#ffffff", background: (record.statusNormal == "Y" ? "#096dd9" :(record.statusNormal=="N"? "#F6A724":"")), padding: "2px", borderRadius: "2px", marginRight: "2px" }}>{record.statusNormal == "Y"&&this.state.userData.language=="EN" ? "nor" :(record.statusNormal == "Y"&&this.state.userData.language=="CN" ? "正":(record.statusNormal == "N"&&this.state.userData.language=="EN"?"abn":"异" ) )}</span><span style={{ color: (record.statusNormal == "Y" ? "#096dd9" : "#F6A724") }}>
                        {this.state.localeProvider&&this.state.localeProvider.LISReportReportResults?this.setMessage('LISReportReportResults', 'descripts'):"报告结果"}
                        </span></span>
                    )
                  }
                  if (item.code == "lifeCycle") {
                    return (
                    <span style={{ cursor: "pointer" }} onClick={(e) => this.handleOpenLife(e,record.execOrdID)}><span style={{ color: "#096dd9"}}>{record.lifeCycle}</span></span>
                    )
                  }
                  return text
                }
              }
            }) : '';
            let filterArr = arr.filter(function (item) { return item.display === 'Y' });
            this.setState({
              columns: filterArr, widthTotal: res.totalWidth, localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
            })
          }
        }
      })
    }
    //点击查询检验报告
    findDatas = () => {
      this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
        this.handleQuery("search")
      })
    }
    //查找检验报告
    handleQuery = (e) => {
      const {StartDate, EndDate, page, pageSize, } = this.state
      let data = {}
      data = {
        params: [{
          patID:this.props&&this.props.patID?this.props.patID:sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
          admID: this.props&&this.props.admID?this.props.admID:sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
          formDate: StartDate, 
          toDate: EndDate ,
        }],
        pagination: [{
          pageSize: parseInt(pageSize),
          currentPage: parseInt(page),
        }]
      }
      $http.post('urlS', this, {
        code: '03050134',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result.data) {
              res.result.data && res.result.data.map((item, index) => {
              res.result.data[index].key = Number(index)
            })
            this.setState({
              leftData: res.result.data,
              total: res.result.totalCount,
              search:e
            })
          }
        }
      })
    }
    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }
    // 修改page和pageSize 跳转至---
    onChange = (e, ) => {
      this.setState({ page: e, pageSize: this.state.pageSize }, () => {
        // 重新调用查询方法
        this.handleQuery();
      })
    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (e, ) => {
      this.setState({ page: e, pageSize: this.state.pageSize }, () => {
        // 重新调用查询方法
        this.handleQuery();
      });
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
      this.setState({ page: 1, pageSize: pageSize }, () => {
        // 重新调用查询方法
        this.handleQuery("search");
      })
    }
    //点击Row 左侧表格
    onClickRow = (record) => {
      return {
        onClick: () => {
          if (record.ID) {
            if (this.state.rowId === "") {
              this.setState({
                rowId: record.ID,
                recordData: record
              });
            } else {
              if (this.state.rowId !== record.ID) {
                this.setState({
                  rowId: record.ID,
                  recordData: record
                });
              } else {
                this.setState({
                  rowId: "",
                  ID: "",
                  recordData: []
                });
              }
            }
          }
        },
        onDoubleClick: () => {
          this.setState({
            rowId: record.ID,
            recordData: record
          });
        }
      };
    }
    //打开报告结果
    handleOpen = (e, record) => {
      e.stopPropagation();
      this.setState({
        recordData: record
      }, () => {
        this.getPatInfo(record)
        this.childRef.showModal(this.state.recordData.ID)
      })
    }
    onRefsLift=(ref)=>{
      this.childRefLift= ref
    }
    handleOpenLife= (e,ordID) => {
      this.childRefLift.showModal(ordID)
    }
    //设置点击row颜色 --左侧表格
    setRowClassName = (record) => {
      return record.ID === this.state.rowId ? 'clickRowStyle' : '';
    }
    //获取病人基本信息
    getPatInfo = (record) => {
      let data = {}
      data = {
        params: [{
          reportID: record.ID,
        }],
      }
      $http.post('urlS', this, {
        code: '03050136',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.childRef.getInfo(res.result)
          }
        }
      })
    }
    render() {
      let { widthTotal, adviceLogArr, columns,yearArr } = this.state
      const { getFieldDecorator } = this.props.form;
      let searchColConfig = {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: 10}
      }
      return (
        <div>
          <Row gutter={60} className="testResultDom" style={{ margin: "0" }}>
            <Col span={24} style={{ padding: "0" }}>
              <Row style={{ padding: "10px 0 0 10px" }}>
              <Col {...searchColConfig} style={{ padding: "4px 0" }}>
              <RangeDatePicker isChange={true} label={ this.state.userData.language == 'EN' ? '	Medical date：' : '申请日期：' } format='YYYY-MM-DD' width={300}
                startDate={this.state.StartDate} endDate={this.state.EndDate}
                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)}  />
            </Col>
                <Col span={2} >
                  <FormItem  {...formItemLayout}>
                    {getFieldDecorator('find', {
                      initialValue: undefined,
                      rules: [{ required: false, message: '' }],
                    })(
                      <Button onClick={this.findDatas} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.LISReportSearch? this.setMessage('LISReportSearch', 'descripts') : ""}</Button>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Table
                scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: store.getState().tableHeight.y - 231 }}
                columns={columns && columns.length > 0 ? columns : []}
                dataSource={this.state.leftData}
                pagination={false}
                rowKey={record => record.key}
                rowClassName={this.setRowClassName}
                bordered
                style={{ height: this.props&&this.props.modal?store.getState().tableHeight.y -82 + 'px':store.getState().tableHeight.y - 133 + 'px',overflow:"auto" }}
              />
              <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.leftData}
                onChange={this.PageChange.bind(this)} />
            </Col>
          </Row>
          <TestResultModal onRef={this.onRef} getReaultPop={this.getReaultPop}></TestResultModal>
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='LISReport'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.getMainTableColumns}
          />
           <OrdersModel onRefs={this.onRefsLift}></OrdersModel>
        </div>
      )
    }
  })
export default HospitaDoctorAdTest