/*
 * Creator:     ML
 * CreatDate:   2019-11-21
 * descripts：检验结果
 * */
import React from 'react';
import moment from 'moment';
import {Form, Row, Col, Table, Select, Button, Modal, Popover,} 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 "./component/TestResultModal.jsx";
import ViewSelectComponent from './component/ViewSelectComponent';
import OrdersModel from "pages/nurse/orders/ordersModel";
import { $loadTemplate } from '../lodop/Common/Print.js';
const formItemLayout = { // label 和input宽度
  labelCol: { span: 7 },
  wrapperCol: { span: 17 }
}
const FormItem = Form.Item;
const Option = Select.Option;
const TestResult = Form.create()(
    class TestResult 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: [],
          printData: [],
          selectedRowKeys_rightFry: [],
          StartDate: undefined,  // //开始日期
          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 + 8 + 'px';
            document.querySelector(".testResultDom .ant-table-body").style.maxHeight = store.getState().tableHeight.y + 8 + 'px';
          }
        }
        this.child.getRequireds()//就诊记录不必选
        this.getAllSelect()
        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) => {

                    /**
                     * @ByYQL：门诊Lis报告 替换原resultStatus逻辑
                     * Create 2021-11-23
                     * @ByYQL：门诊Lis报告 升级与住院Lis反参统一
                     * Create 2022-4-15
                     */
                    if (item.code === "lisRptURL"){
                      return (
                          record.lisRptURL && record.lisRptURL != "undefined" ?
                              <span style={{ cursor: "pointer" }}><span style={{ color: "#ffffff", background: (record.statusNormal == "Y" ? "#096dd9" : "#F6A724"), padding: "2px", borderRadius: "2px", marginRight: "2px" }}>{record.statusNormal == "Y" ? "正" : "异"}</span>
                                                <a href={record.lisRptURL} style={{color:(record.statusNormal == "Y" ? "#096dd9" : "#F6A724") }} target="_blank" rel="noopener noreferrer">{record.lisRptURL && record.lisRptURL != "undefined" ? "Lis报告查看" : ""}</a>
                                            </span> : "无报告"
                      )
                    }
                    if(item.code === 'orderDescFormat'){
                      const content = (
                          <div>
                            {record?.orderList && record?.orderList.length > 0 ?
                                record?.orderList.map((item,index) => {
                                  return (<p>{item.ordDesc}</p>)
                                }) : ''  }
                          </div>
                      );
                      return (
                          <Popover content={content} title="医嘱详情：">
                            <span style={{overflow:"hidden",whiteSpace:"nowrap",width:"100%",display:"inline-block",textOverflow:"ellipsis"}}>{record?.orderDescFormat}</span>
                          </Popover>
                      )
                    }
                    if(item.code === 'statusNormal'){
                      return (
                          record.lisRptURL && record.lisRptURL != "undefined" ?
                            <span style={{color:(record.statusNormal == "Y" ? "#096dd9" : "#F6A724") }}>{record.statusNormal == "Y" ? "正常" : "异常"}</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
              })
            }
          }
        })
      }


      //获取查询条件下拉
      getAllSelect = () => {
        let data = {}
        data = {
          params: [{
            patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
            admYearsFlag: "Y",//就诊年限
            admRecordFlag: "Y",//就诊记录
          }],
        }
        $http.post('urlS', this, {
          code: '03050130',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.result) {
              this.setState({
                adviceLogArr: res.result.admRecord,
                yearArr: res.result.admYears,
              }, () => {
                res.result.admRecord && res.result.admRecord.map((item, i) => {
                  if (sessionStorage.patientData && JSON.parse(sessionStorage.patientData).admID && JSON.parse(sessionStorage.patientData).admID == item.admID) {
                    this.props.form.setFieldsValue({ adviceLog: item.admID, adviceYear: item.years })
                    this.setState({
                      StartDate: item.admDate
                    }, () => {
                      this.yearsToLog(item.years)
                    })
                  }
                })
              })
            }
          }
        })
      }
      //就诊年份 -- 获取就诊记录
      handleYears = (years) => {
        if (years) {
          this.yearsToLog(years)
        } else {
          this.yearsToLog("")
        }
        this.props.form.setFieldsValue({ adviceLog: undefined })
      }
      //就诊记录--自动获取开始医嘱日期
      handleLog = (data, years) => {
        this.setState({
          StartDate: data
        })
        this.props.form.setFieldsValue({
          adviceYear: years
        })
      }
      //选择就诊年份获取急诊记录
      yearsToLog = (years) => {
        let data = {}
        data = {
          params: [{
            patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
            admRecordFlag: "Y",//就诊记录
            years,
          }],
        }
        $http.post('urlS', this, {
          code: '03050130',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.result) {
              this.setState({
                adviceLogArr: res.result.admRecord,
              }, () => {

              })
            }
          }
        })
      }
      findData = () => {
        this.child.handleVail()
      }
      //点击查询检验报告
      findDatas = () => {
        this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
          this.handleQuery("search")
        })
      }
      getValue = (years, yearsLog, starData, endData) => {
        this.setState({
          years,
          yearsLog,
          starData,
          endData
        })
      }
      onRefs = (ref) => {
        this.child = ref
      }
      //查找检验报告
      handleQuery = (e) => {
        const { years, yearsLog, starData, endData, page, pageSize, } = this.state
        let data = {}
        data = {
          params: [{
            patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
            years: years || "",
            admID: yearsLog || "",
            formDate: starData || "",
            toDate: endData || "",
          }],
          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)
              })
              //setLisReportUrl为拼装url函数，去除该函数时直接将res.result.data赋值即可
              let resultData = this.setLisReportUrl(res.result.data)
              this.setState({
                leftData: resultData,
                total: res.result.totalCount,
                search: e
              })
            }
          }
        })
      }

      /**
       * @ByYQL：Lis报告url拼装函数
       * Create 2021-11-23
       */
      setLisReportUrl = (data) => {
        let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
        for(let i=0;i<data.length;i++){
          if(data[i].lisRptURL && data[i].lisRptURL != "undefined"){
            data[i].lisRptURL = windowHost+"/pryklisrpt/TechReportWeb/ReportHtml/LisResult.aspx"+ data[i].lisRptURL
          }
        }
        return data
      }

      // 显示分页总条数
      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();
        // 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:[]
        //       });
        //     }
        //   }
        // }
        this.setState({
          recordData: record
        }, () => {
          this.getPatInfo(record)
          // console.log("this.state.recordData.reportID",this.state.recordData.reportID)
          this.childRef.showModal(this.state.recordData.reportID)
        })

      }
      onRefsLift = (ref) => {
        this.childRefLift = ref
      }
      handleOpenLife = (e, ordID) => {
        if (ordID != "") {
          this.childRefLift.showModal(ordID)
        }
      }
      //设置点击row颜色 --左侧表格
      setRowClassName = (record) => {
        return record.ID === this.state.rowId ? 'clickRowStyle' : '';
      }
      //获取病人基本信息
      getPatInfo = (record) => {
        let data = {}
        data = {
          params: [{
            reportID: record.reportID,
          }],
        }
        $http.post('urlS', this, {
          code: '03050136',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.result) {
              this.childRef.getInfo(res.result)
            }
          }
        })
      }
      getPrintInfo = (ID) => {
        let data = {}
        data = {
          params: [{
            reportID: ID,
          }],
        }
        $http.post('urlS', this, {
          code: '03050223',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              if (res.result && res.result.length > 0) {
                res.result.map((item, i) => {
                  $loadTemplate(item.template, item.printStr);
                })
              }
            }
          }
        })
      }
      //打印检验结果
      handlePrint = () => {
        const { selectedRowKeys_rightFry } = this.state
        if (selectedRowKeys_rightFry && selectedRowKeys_rightFry.length > 0) {
          selectedRowKeys_rightFry.map((item, i) => {
            this.getPrintInfo(item)
          })
        }
      }
      render() {
        let { widthTotal, adviceLogArr, columns, yearArr } = this.state
        const { getFieldDecorator } = this.props.form;
        //就诊年份
        let yearOp = []
        yearArr && yearArr.map(item => {
          yearOp.push(<Option key={item.admYears} role={item.admYears + '^' + item.admYears} title={item.admYears} onClick={() => this.handleYears(item.admYears)} value={String(item.admYears)}>{item.admYears}</Option>)
        })
        //就诊记录
        const rowSelection_rightFry = {
          selectedRowKeys: this.state.selectedRowKeys_rightFry,
          onChange: (selectedRowKeys, selectedRows) => {
            // console.log(selectedRowKeys)
            let selectrow = "";
            if (selectedRowKeys.length === 0) {
            } else {
              selectrow = selectedRowKeys[selectedRowKeys.length - 1];
            }
            let arr = []
            selectedRows.map((item, i) => {
              arr.push(item.id)
            })
            this.setState({ selectedRowIds_Fry: arr, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_rightFry: selectedRowKeys }, () => {
            });
          },
          getCheckboxProps: record => ({
            disabled: record.reportID === '', // Column configuration not to be checked
          }),
          onSelectAll: (selected, selectedRows, changeRows) => {
            let arr = []
            selectedRows.map((item, i) => {
              arr.push(item.id)
            })
            this.setState({ selectedRowIds_Fry: arr, selectedRow_right: selectedRows });
          }
        };
        return (
            <div>
              <Row gutter={60} className="testResultDom" style={{ margin: "0" }}>
                <Col span={24} style={{ padding: "0" }}>
                  <Row style={{ paddingTop: "10px" }}>
                    <ViewSelectComponent modal={this.props && this.props.modal ? this.props.modal : ""} getValue={this.getValue} handleFind={this.findDatas} locale={this.state.userData.language} onRefs={this.onRefs}></ViewSelectComponent>
                    <Col span={2} >
                      <FormItem  {...formItemLayout}>
                        {getFieldDecorator('find', {
                          initialValue: undefined,
                          rules: [{ required: false, message: '' }],
                        })(
                            <Button onClick={this.findData} type="primary">{this.state.localeProvider && this.state.localeProvider.LISReportSearch ? this.setMessage('LISReportSearch', 'descripts') : ""}</Button>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={2} >
                      <FormItem  {...formItemLayout}>
                        {getFieldDecorator('print', {
                          initialValue: undefined,
                          rules: [{ required: false, message: '' }],
                        })(
                            <Button onClick={this.handlePrint} disabled={this.state.selectedRowKeys_rightFry && this.state.selectedRowKeys_rightFry.length == 0} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.LISReportPrint ? this.setMessage('LISReportPrint', '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.reportID}
                      rowClassName={this.setRowClassName}
                      rowSelection={rowSelection_rightFry}
                      bordered
                      style={{ height: this.props && this.props.modal ? store.getState().tableHeight.y - 82 + 'px' : store.getState().tableHeight.y + 54 + '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}
              />
              {
                this.state.leftData && this.state.leftData.length > 0 ? <OrdersModel onRefs={this.onRefsLift}></OrdersModel> : ""
              }
            </div>
        )
      }
    })
export default TestResult
