/*
 * Creator:     ML
 * CreatDate:   
 * LastModifiedDate:2019-11-23
 * descripts：就诊历史查询
 * */
import React from 'react';
import { Form, Row, Col, Select, Button } from 'antd';
import moment from 'moment';
import { $http } from '../../../containers/config/https';
import { Util } from 'tools/index';
import store from '../../../store';
// import CommonPagination from 'components/pagination/index';
import { dayFormat } from 'tools/index';
import RangeDatePicker from 'components/rangePicker/index';
import ShowMedicalRecordModal from './ShowMedicalRecordModal';
import RecordCompoent from '../../nurse/MedicalRecord/RecordCompoent';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const FormItem = Form.Item;
const Option = Select.Option;

const formItemLayout = { // label 和input宽度
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}
const ConsultationHistory = Form.create()(
  class ConsultationHistory extends React.Component {
    constructor(props) {
      super(props)
      var userData = JSON.parse(sessionStorage.getItem('userData'));
      var date = new Date()
      this.state = {
        userData: userData,
        loading: false,
        visible: false,
        total: 0,//表格总数据
        consuilationData: [],//查询出来的就诊历史数据
        values: {},//查询条件数据
        searchLoading: false,//查询请求
        rowIds: '',//表格行选中 页面数据
        columns: [],//就诊历史表头
        widthTotal: 0,//宽
        columnsVisible: false,//配置表头显隐
        page: 1,
        pageSize: 10,
        typeArr: [],
        search: "",
        size: "small",
        StartDate: moment().subtract(3, "months").format("YYYY-MM-DD"),  // //开始日期 前3个月
        EndDate: moment(date).format(dayFormat),  // //结束日期
        localeProvider: [],
        historyAdmID: "", // 历史就诊ID
        rowData: {},
      }

    }

    componentDidMount () {
      this.getMainTableColumns()
      this.findData()
      // this.getFindDate()
      this.getConsulSelect()
    }

    //获取就诊类型下拉框数据
    getConsulSelect = () => {
      let data = {}
      data = {
        params: [{
        }],
      }
      $http.post('urlS', this, {
        code: '03050088',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              typeArr: res.result.Data,
            })
          }
        },
      })
    }

    //查看病历
    handleMedicalRecord = (e, row) => {
      // message.warning("正在开发....")
      // console.log(row)
      if (row.admTypeCode == 'O' || row.admTypeCode == 'I') {
        this.setState({
          admTypeCode: row.admTypeCode,
          historyAdmID: row.admID,
          isShowMedicalRecordModal: true,
          rowData: row,
        })
      } else {
        this.childConsumeSome.showModal(row)
      }
    }

    // 获取主列表columns
    getMainTableColumns = () => {
      let data = {
        params: [{
          compontName: "ConsultationHistory", // 就诊历史
          reactCode: ['ConsultationHistory'],
          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>{this.state.userData.language == 'EN' ? item.enDescripts : item.title}</div>,
                display: item.display,
                key: item.seqNo
              }
            }) : '';
            let filterArr = arr.filter(function (item) { return item.display === 'Y' });
            let seqArr = {
              align: "center",
              widthNum: 140,
              width: "150px",
              code: "edit",
              dataIndex: "edit",
              title: this.state.localeProvider && this.state.localeProvider.ConsultationHistoryEdit ? this.setMessage('ConsultationHistoryEdit', 'descripts') : "操作",
              display: "Y",
              fixed: 'right',
              render: (value, row, index) => {
                return (
                  <span style={{ color: "rgb(24, 144, 255)", cursor: "pointer" }}>
                    <span onClick={(e) => this.handleMedicalRecord(e, row)}>{this.state.localeProvider && this.state.localeProvider.ConsultationHistoryMedicalRecord ? this.setMessage('ConsultationHistoryMedicalRecord', 'descripts') : "查看病历"}</span>
                  </span>
                )
              },
            }
            filterArr.push(seqArr)
            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 跳转至---
    compilePage = (page, pageSize) => {
      this.setState({ page, pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        this.getFindDate(values);
      })
    }

    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
      this.setState({ page: 1, pageSize: pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        if (this.state.consuilationData && this.state.consuilationData.length > 0) {
          this.getFindDate(values, "search");
        }
      })
    }

    // 显示分页总条数
    showTotal (total) {
      return `共 ${total} 条`;
    }

    //获取查询数据
    getFindDate = (values, mes) => {
      this.setState({
        searchLoading: true
      })
      let { page, pageSize, } = this.state;
      let data = {}
      data = {
        params: [{
          patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : {},
          admTypeID: values && values.type && values.type ? values.type : "",//就诊类型
          startDate: this.state.StartDate || "",
          endDate: this.state.EndDate || "",
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      $http.post('urlS', this, {
        code: '03050085',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              consuilationData: Util.addKeyValueToDataSource(res.result.Data),
              total: res.result.TotalCount && res.result.TotalCount != undefined ? res.result.TotalCount : 0,
              searchLoading: false,
              rowId: "",
              search: mes
            })
          } else {
            this.setState({
              searchLoading: false
            })
          }
        },
        error: function () {
          this.setState({
            searchLoading: false
          })
        }
      })
    }

    //选择就诊类型直接调起查询
    handleType = () => {
      this.findData()
    }

    //---就诊历史列表
    findData = () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          this.setState({
            values: values,
            rowIds: ""
          })
          this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
            let { values } = this.state;
            this.getFindDate(values)
          })
        }
      })
    }

    handleCancel = () => {
      this.handleRest()
      this.setState({
        visible: false,
        bindMoreInfo: false,
        bindVail: true
      });
    }

    //点击查询后 表格行
    setRowClassNames = (record) => {
      return record.admID === this.state.rowIds ? 'clickRowStyle' : '';
    }

    //点击Row
    onClickRow = (record) => {
      return {
        onClick: () => {
          this.setState({
            parms: record,
          })
          if (this.state.rowId === "") {
            this.setState({
              rowIds: record.admID,
            });
          } else {
            if (this.state.rowId !== record.admID) {
              this.setState({
                rowIds: record.admID,
              });
            } else {
              this.setState({
                rowIds: "",
                detailInfo: {},
              });
            }
          }
        },
      };
    }

    //开始日期
    startChange (date) {
      this.setState({
        StartDate: date,
      })
    }
    //结束日期
    endChange (date) {
      this.setState({
        EndDate: date,
      })
    }

    onConsumeSomeRef = (ref) => {
      this.childConsumeSome = ref
    }

    hideModal (name) {
      this.setState({
        [name]: false
      })
    }

    render () {
      const { getFieldDecorator } = this.props.form;
      const { consuilationData, total, page, searchLoading, widthTotal, columns, typeArr, historyAdmID } = this.state;
      let searchColConfig = {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: this.props && this.props.modal ? 8 : 5 }
      }
      let typeOption = []
      typeArr && typeArr.map(item => {
        typeOption.push(<Option key={item.admTypeID} value={item.admTypeID} onClick={this.handleType}>{item.admDesc}</Option>)
      })
      // this.props.modal存在的话放置在弹窗上
      let param = {
        // 表头配置
        columns: columns && columns.length > 0 ? columns : [],
        // 表格数据
        data: consuilationData,
        // 数据总条数
        total,
        // 当前页数
        page,
        pageSize: "20",
        loading: searchLoading,
        isOnRow: true,
        rowClassName: true,
        componentName: 'ConsultationHistory',
        // 表格的宽度
        x: columns && columns.length > 0 ? widthTotal : 4000,
        y: this.props && this.props.modal ? store.getState().tableHeight.y - 198 : store.getState().tableHeight.y,
        height: this.props && this.props.modal ? store.getState().tableHeight.y - 144 + 'px' : store.getState().tableHeight.y + 54 + 'px'
      }
      return (
        <div style={{ padding: '4px 2px', width: '100%', height: '100%', position: 'relative' }} className="hisDom">
          {(this.state.admTypeCode == 'O' || this.state.admTypeCode == 'I') ? (
            this.state.isShowMedicalRecordModal && <ShowMedicalRecordModal
              viewEMRFlag="Y"
              isShow={this.state.isShowMedicalRecordModal}
              admTypeCode={this.state.admTypeCode}
              historyAdmID={historyAdmID}
              rowData={this.state.rowData}
              onHide={this.hideModal.bind(this, 'isShowMedicalRecordModal')}>
            </ShowMedicalRecordModal>
          ) : (
            <RecordCompoent
              onRef={this.onConsumeSomeRef}
            ></RecordCompoent>
          )}
          <Form>
            <Row gutter={60} style={{ margin: '0' }}>
              <Col span={7} className="starDataDom">
                <FormItem label={this.state.localeProvider && this.state.localeProvider.ConsultationHistoryTypeOfTreatment ? this.setMessage('ConsultationHistoryTypeOfTreatment', 'descripts') : "就诊类型"} {...formItemLayout}>
                  {getFieldDecorator('type', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select allowClear placeholder={this.state.localeProvider && this.state.localeProvider.ConsultationHistoryTypeOfTreatment ? this.setMessage('ConsultationHistoryTypeOfTreatment', 'message') : "请选择就诊类型"}>
                      {typeOption}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col {...searchColConfig} style={{ padding: "4px 0" }}>
                <RangeDatePicker label={this.state.localeProvider && this.state.localeProvider.ConsultationHistoryDateOfVisit ? this.setMessage('ConsultationHistoryDateOfVisit', 'descripts') : "就诊日期"} format='YYYY-MM-DD' width={300}
                  startDate={this.state.StartDate} local={this.state.userData.language} 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.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.ConsultationHistorySearch ? this.setMessage('ConsultationHistorySearch', 'descripts') : "查询"}</Button>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
          <div className='table-body-height'>
            <PubilcTablePagination
              param={param}
              getColumns={this.getMainTableColumns}
              compilePage={this.compilePage}
              onClickRowPublic={this.onClickRow}
              setRowClassNamePublic={this.setRowClassNames}
            />
            {/* <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}
              onRow={this.onClickRow}
              rowClassName={this.setRowClassNames}
              bordered
              // style={{ height: this.props && this.props.modal ? store.getState().tableHeight.y - 82 + 'px' : store.getState().tableHeight.y + 54 + 'px', overflow: "auto" }}
            />
            <CommonPagination style={{ position: "absolute", bottom: "0", right: "0" }} 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)} /> */}
          </div>
          {/* <Pagination
            showTotal={() => this.showTotal(this.state.total)}
            size="small"
            showQuickJumper
            showSizeChanger
            defaultCurrent={1}
            current={this.state.page ? this.state.page : 1}
            total={this.state.total ? this.state.total : 0}
            onChange={this.onChange}
            onShowSizeChange={this.onShowSizeChange}
            style={{ textAlign: "right", }}
          /> */}
          {/* <RecordCompoent
            onRef={this.onConsumeSomeRef}
          ></RecordCompoent> */}

        </div>
      )
    }
  })
export default ConsultationHistory;