/*
 * Creator:     ML
 * CreatDate:   2019-12-21
 * 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 moment from 'moment';
import fetchJsonp from 'fetch-jsonp';
import CommonPagination from 'components/pagination/index';
import ViewInsReportTarget from 'pages/workstation/component/ViewInsReportTarget';
import OrdersModel from "pages/nurse/orders/ordersModel";
import RangeDatePicker from 'components/rangePicker/index';
import { dayFormat } from 'tools/index';
const FormItem = Form.Item;
const formItemLayout = { // label 和input宽度
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}
  class HospitaDoctorAdAnExam extends React.Component {
    constructor(props) {
      super(props)
      var date = new Date();
      var userData = JSON.parse(sessionStorage.getItem('userData'));
      this.state = {
        userData: userData,
        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: "",
        startDate: moment(date).format(dayFormat),  // //开始日期
        endDate:  moment(date).format(dayFormat),  // //结束日期
      }
    }
    componentDidMount() {
      if (document.querySelector('.ant-table-body')) {
        if(this.props&&this.props.modal){
          //放置在弹窗上
          document.querySelector(".reportDom .ant-table-body").style.height =  store.getState().tableHeight.y - 136 + 'px';
          document.querySelector(".reportDom .ant-table-body").style.maxHeight =  store.getState().tableHeight.y -136 + 'px';
        }else{
          //放置在普通页面上
          document.querySelector(".reportDom .ant-table-body").style.height =  store.getState().tableHeight.y -182+ 'px';
          document.querySelector(".reportDom .ant-table-body").style.maxHeight =  store.getState().tableHeight.y -182 + 'px';
        }
       
      }
      this.getMainTableColumns()
      setTimeout(()=>{
        this.getFindDate("search");
      },600)
    }
    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("该检查科室没有配置报告样式文件，请与系统管理员联系!")
    }
  }
  onRefsLift=(ref)=>{
    this.childRefLift= ref
  }
  handleOpenLife= (e,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 => {
              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) => {
                  // console.log("record--",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} 条`;
    }
    //获取查询数据
    getFindDate = (e) => {
      // console.log("this.propsthis.props",this.props)
      const { admID, years, yearsLog, startDate, endDate } = this.state;
      if (this.state.total == 0) {
        this.setState({
          searchLoading: true
        })
      }
      let { 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 : "",
          fromDate: startDate,//开始日期
          toDate: endDate,//截止日期
        }],
        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
          })
        }
      })
    }
    //--检查报告列表
    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
    }
     //开始日期
     startChange(date) {
      this.setState({
        StartDate: date,
      })
    }
    //结束日期
    endChange(date) {
      this.setState({
        EndDate: date,
      })
    }
    render() {
      const { getFieldDecorator } = this.props.form;
      const { searchLoading, widthTotal, columns } = this.state;
      let searchColConfig = {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: 10}
      }
      return (
        <div className="reportDom">
            <Row gutter={60} className="testResultDom" style={{ margin: "0" }}>
              <Col {...searchColConfig} style={{ padding: "4px 10px" }}>
              <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} style={{ paddingLeft: "0 !important" }}>
              <FormItem  {...formItemLayout}>
                {getFieldDecorator('export', {
                  initialValue: undefined,
                  rules: [{ required: false, message: '' }],
                })(
                  <Button onClick={this.findDatas} 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: store.getState().tableHeight.y + 51 }}
            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 -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.consuilationData}
            onChange={this.onChange.bind(this)} />
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='ExamineReport'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.getMainTableColumns}
          />
          <ViewInsReportTarget Onres={this.Onres}></ViewInsReportTarget>
          <OrdersModel onRefs={this.onRefsLift}></OrdersModel>
        </div>
      )
    }
  }
  export default Form.create()(HospitaDoctorAdAnExam);