/*
 * Creator:     ML
 * CreatDate:   2019-09-18
 * descripts：  查看检查报告
 * */
import React from 'react';
import { Form, Row, Col, Button, Table, message } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from '../../../containers/config/https';
import store from '../../../store';
import fetchJsonp from 'fetch-jsonp';
import { Util } from 'tools/index';
import CommonPagination from 'components/pagination/index';
import ViewSelectComponent from './ViewSelectComponent';
import ViewInsReportTarget from './ViewInsReportTarget';
import OrdersModel from "pages/nurse/orders/ordersModel";

const FormItem = Form.Item;

const formItemLayout = { // label 和input宽度
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}
class ViewInspectionReport extends React.Component {
  constructor(props) {
    super(props)
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    var titleData = JSON.parse(sessionStorage.getItem('titleData'));
    this.state = {
      userData: userData,
      titleData: titleData,
      loading: false,
      visible: false,
      total: 0,//表格总数据
      consuilationData: [],//查询出来的检查报告数据
      values: {},//查询条件数据
      searchLoading: false,//查询请求
      rowIds: '',//表格行选中 页面数据
      columns: [],//检查报告表头
      widthTotal: 0,//宽
      columnsVisible: false,//配置表头显隐
      page: 1,
      pageSize: 10,
      starNoVisible: false,
      startNoMessage: "",
      search: "",
      size: "small",
      years: "",
      yearsLog: "",
      starData: "",
      endData: ""
    }
  }
  componentDidMount() {
    this.getMainTableColumns()
    setTimeout(() => {
      this.getFindDate("search");
    }, 600)
    this.child.getRequireds()
  }
  onColumnRef = (ref) => {
    this.columnRef = ref;
  }
  Onres = (ref) => {
    this.childs = ref
  }
  handleOpen = (e, url) => {
    this.childs.showModals(url)
  }
  //调起本地服务 --imgUrl
  handleOpenImg = (e, url) => {
    if (url && url.length > 0) {
      let address = 'path:"C:/ProgramData/XYS/XYSService/plugins/PacsRead/",';
      let param = url.replace(/\&/g, "%26");
      let inputObj = '{ inputDir:"PacsRead/OpenExe.dll", clsName:"OpenExe.ExeObj",funcName:"CreateProcess",dllInput:{' + address + 'exeName:"OpenPacs.exe",parameter:"' + param + '"}}';
      fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?input=' + inputObj)
        .then(res => res.json())
      // .then(data =>
      //    console.log(data));
    } else {
      message.warning("该检查科室没有配置报告样式文件，请与系统管理员联系!", this.state.userData && this.state.userData.messageTime)
    }
  }
  onRefsLift = (ref) => {
    this.childRefLift = ref
  }
  handleOpenLife = (e, ordID) => {
    if (ordID != "") {
      this.childRefLift.showModal(ordID)
    }
  }
  // 获取主列表columns
  getMainTableColumns = () => {
    let data = {
      params: [{
        compontName: "ExamineReport", // 检查报告
        reactCode: ['ExamineReport'],
        type: 'C', // 卡类型id
      }]
    }
    $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 => {
            if (item.dataIndex == 'imagePath') {
              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.descripts : item.title}</div>,
                display: item.display,
                key: item.seqNo,
                render: (text, record) => {
                  return <a href={record.imagePath} target='_blank'>{text}</a>
                }
              }
            } if (item.dataIndex == 'pacsImg') {
              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.descripts : item.title}</div>,
                display: item.display,
                key: item.seqNo,
                render: (text, record) => {
                  return <a href={'Holi.Pacs://' + record.patNo} target='_blank'>{record.patNo}</a>
                }
              }
            } else {
              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.descripts : item.title}</div>,
                display: item.display,
                key: item.seqNo,
                render: (text, record) => {
                  if (item.code == "TOpenRpt") {
                    return (
                      <span style={{ cursor: "pointer" }} onClick={(e) => this.handleOpen(e, record.TOpenRptUrl)}><span style={{ color: "#096dd9" }}>{record.TOpenRpt}</span></span>
                    )
                  } if (item.code == "TImgBrowse") {
                    return (
                      <span style={{ cursor: "pointer" }} onClick={(e) => this.handleOpenImg(e, record.ImageUrl)}><span style={{ color: "#096dd9" }}>{record.TImgBrowse}</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' });
          // console.log("filterArr",filterArr)
          this.setState({ localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN, columns: filterArr, widthTotal: parseInt(res.totalWidth) })
        }
      }
    })
  }
  //国际化
  setMessage(name, message) {
    return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
  }
  // 修改page和pageSize 跳转至---
  onChange = (page, pageSize) => {
    this.setState({ page: page, pageSize: this.state.pageSize }, () => {
      // 重新调用查询方法
      this.getFindDate();
    })
  }
  //下拉选择页数
  onShowSizeChange = (page, pageSize) => {
    this.setState({ page: 1, pageSize: pageSize }, () => {
      // 重新调用查询方法
      if (this.state.consuilationData && this.state.consuilationData.length > 0) {
        this.getFindDate("search");
      }
    })
  }
  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }
  getValue = (years, yearsLog, starData, endData) => {
    // console.log(years, yearsLog, starData, endData)
    this.setState({
      years,
      yearsLog,
      starData,
      endData
    })
  }
  //获取查询数据
  getFindDate = (e) => {
    const { admID, years, yearsLog, starData, endData } = this.state;
    if (this.state.total == 0) {
      this.setState({
        searchLoading: true
      })
    }
    let { page, pageSize, } = this.state;
    let data = {}
    data = {
      params: [{
        years: years || "",
        admID: yearsLog || "",
        // admID:1,
        fromDate: starData || "",//开始日期
        toDate: endData || "",//截止日期
        patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
      }]
    }
    $http.post('urlS', this, {
      code: '03050145',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            searchLoading: false,
            rowId: "",
          })
          this.setState({ consuilationData: res.result, search: e, total: res.totalCount && res.totalCount != undefined ? res.totalCount : 0, }, () => {
          })
        } else {
          this.setState({
            searchLoading: false
          })
        }
      },
      error: function () {
        this.setState({
          searchLoading: false
        })
      }
    })
  }
  findData = () => {
    this.child.handleVail()
  }
  //--检查报告列表
  findDatas = () => {
    this.setState({
      rowIds: ""
    })
    this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
      this.getFindDate("search")
    })
  }
  handleCancel = () => {
    this.handleRest()
    this.setState({
      visible: false,
      bindMoreInfo: false,
      bindVail: true
    });
  }
  //隐藏提示信息
  visibleTip = () => {
    this.setState({
      starNoVisible: false,
    })
  }
  onRefs = (ref) => {
    this.child = ref
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { searchLoading, widthTotal, columns } = this.state;
    return (
      <div style={{ padding: '4px 2px' }} className="reportDom table-body-height">
        <Row gutter={60} style={{ margin: '0' }}>
          <ViewSelectComponent modal={this.props && this.props.modal ? this.props.modal : ""} getValue={this.getValue} handleFind={this.findDatas} onRefs={this.onRefs} locale={this.state.userData.language}></ViewSelectComponent>
          <Col span={2} style={{ paddingLeft: "0 !important" }}>
            <FormItem  {...formItemLayout}>
              {getFieldDecorator('export', {
                initialValue: undefined,
                rules: [{ required: false, message: '' }],
              })(
                <Button onClick={this.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>
                  {this.state.localeProvider && this.state.localeProvider.ExamineReportSearch ? this.setMessage('ExamineReportSearch', 'descripts') : "查询"}
                </Button>

              )}
            </FormItem>
          </Col>
        </Row>
        <Table
          scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: this.props && this.props.modal ? store.getState().tableHeight.y - 232 : store.getState().tableHeight.y }}
          columns={columns && columns.length > 0 ? columns : []}
          dataSource={this.state.consuilationData}
          pagination={false}
          rowKey={record => record.key}
          bordered
          style={{ height: this.props && this.props.modal ? store.getState().tableHeight.y - 182 + '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.consuilationData}
          onChange={this.onChange.bind(this)} />
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName='ExamineReport'
          configType="C"
          onRef={this.onColumnRef}
          reloadData={this.getMainTableColumns}
        />
        <ViewInsReportTarget Onres={this.Onres}></ViewInsReportTarget>
        {
          this.state.consuilationData && this.state.consuilationData.length > 0 ? <OrdersModel onRefs={this.onRefsLift}></OrdersModel> : ""
        }
      </div>
    )
  }
}
export default Form.create()(ViewInspectionReport);
