/*
 * Creator:     ML
 * CreatDate:   
 * descripts：预约查询
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Modal, Table, Icon, Pagination, message, TimePicker, Checkbox, Tooltip, Switch } from 'antd';
import moment, { relativeTimeThreshold } from 'moment';
import { handleExcel } from 'tools/handleExcel.js';
import { $http } from '../../containers/config/https';
import store from '../../store';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import './css/PatientAppInfoFind.less';
import CommonPagination from 'components/pagination/index';
import CardTypeRead from 'components/cardType/index';

console.log(CardTypeRead);

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

const formItemLayout = { // label 和input宽度
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}
const formItemLayoutTimer = { // label 和input宽度
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
}
const formItemLayoutInfo = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
}
const formItemLayoutTime = { // label 和input宽度
  labelCol: { span: 9 },
  wrapperCol: { span: 8 },
}

const PatientAppInfoFind = Form.create()(
  class PatientAppInfoFind extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        loading: false,
        visible: false,
        total: 0,//表格总数据
        orderPatData: [],//查询出来的预约数据
        values: {},//查询条件数据
        searchLoading: false,//查询请求
        exportLoading: false,//导出请求
        rowIds: '',//表格行选中 页面数据
        locId: "",//科室Id
        localArr: [],//loc下拉框数据
        doctorArr: [],//医生数据
        jobLeverArr: [],//挂号职称/排班类型
        orderTypeArr: [],//预约方式
        orderTimeDayArr: [],//预约时段
        columns: [],//预约查询表头
        widthTotal: 0,//
        starNoVisible: false,
        startNoMessage: "",
        size: "big"

      }
    }
    componentDidMount () {
      let self = this
      // 初始化设置table的高度以及表体的高度
      document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 35 + 'px';
      document.querySelector('.ant-table-body').style.maxHeight = store.getState().tableHeight.y + 35 + 'px';
      this.getOptions()
      this.getjobLever()
      this.getOrderType()
      this.getOrderTimeDay()
      this.getMainTableColumns()
      if (this.state.size == "small") {
        this.setState({
          pageSize: 10
        })
      } else {
        this.setState({
          pageSize: 50
        })
      }
      this.getFindDate()
    }
    //获取预约时段
    getOrderTimeDay (id) {
      var params = {
        params: [{
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : ""//hospId--> hospID
        }]
      }
      $http.post('urlDeault', this, {
        code: "01040010",
        data: params,
        success: function (res) {
          if (res.errorCode === '0') {
            this.setState({
              orderTimeDayArr: res.timeRange
            })
          }
        }
      });
    }
    //获取预约方式
    getOrderType = () => {
      let data = {}
      data = {
        params: [{

        }]
      }
      $http.post('urlS', this, {
        code: '01040033',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              orderTypeArr: res.method
            })
          }
        }
      })
    }
    onColumnRef = (ref) => {
      this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
      let data = {
        params: [{
          compontName: "BookInfoList", // 预约查询
          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()}>{item.title}</div>,
                display: item.display,
                key: item.seqNo
              }
            }) : '';
            let filterArr = arr.filter(function (item) { return item.display === 'Y' });
            // let widthTotal = 0;
            // for(var i = 0; i < filterArr.length; i++) {
            //     // widthTotal += filterArr[i].widthNum
            // }
            // console.log("res.totalWidth",res.totalWidth)
            this.setState({ columns: filterArr, widthTotal: res.totalWidth })
          }
        }
      })
    }

    //获取科室
    getOptions = () => {
      let data = {}
      data = {
        params: [{
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
        }]
      }
      $http.post('urlS', this, {
        code: "03020046",
        data: data,
        success: function (res) {
          if (res.errorCode === '0') {
            // console.log("科室",res.result.Data)
            this.setState({
              localArr: res.result.Data,
            })
          } else {
            message.error('查询失败：' + res.errorMessage);
          }
        }
      })
    }
    //获取坐诊医生
    getDoctor () {
      let data = {}
      data = {
        params: [{
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "", // 医院id
          locID: this.state.locID ? this.state.locID : "", // 科室id
          groupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "", // 角色id
          depDoctorID: "", // 科室医生id
        }]
      }
      $http.post('urlS', this, {
        code: "03020049",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              doctorArr: res.depDoctor
            })
          }
        }
      });
    }
    //获取挂号职称/排班类型
    getjobLever () {
      var params = {
        params: [
          { hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "" }
        ],
        pagination: [{
          pageSize: 1000,
          currentPage: 1
        }]
      }
      $http.post('urlDeault', this, {
        code: "03020004",
        data: params,
        success: function (res) {
          if (res.errorCode === '0') {
            this.setState({
              jobLeverArr: res.result.Data,
            })
          }
        }
      });
    }
    //导出查询到的所有数据
    getAllData = () => {
      let { values } = this.state;
      let data = {}
      data = {
        params: [{
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",//医院Id
          locID: values.locaId,//科室
          docID: values.doctorId,//医生
          regTitleID: values.jobLeverId,//挂号职称/排班类型
          number: values.patInfo,//病人基本信息
          bookDateFlag: values.isTime == true ? "Y" : "N",//是否按预约时间
          dateFrom: values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : undefined,//开始日期
          dateTo: values.dateTo ? moment(values.dateTo).format('YYYY-MM-DD') : undefined,//截止日期
          bookMethodID: values.orderTypeId,//预约方式
          timeRangeID: values.orderTimeDayId,//预约时段
        }],
        pagination: [{
          pageSize: 10000,
          currentPage: 1,
        }]
      }
      $http.post('urlS', this, {
        code: '03040020',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              allPatData: res.result.data,
            })
          }
        },
      })
    }
    //导出预约查询表格
    exportData = () => {
      const { columns } = this.state
      this.setState({
        exportLoading: true,
      })
      // console.log("columns",columns)
      this.getAllData()
      columns && columns.map((item, index) => {
        if (item.title.props && item.title.props) {
          columns[index].title = columns[index].title.props.children
        }
      })
      //请求
      setTimeout(() => {
        this.setState({
          exportLoading: false,
        })
        handleExcel.exportExcel(columns, this.state.allPatData, '预约查询表格')
      }, 1000)
    }
    // 修改page和pageSize 跳转至---
    onChange = (e) => {
      this.setState({ page: e, pageSize: this.state.pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        this.getFindDate(values);
      })
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
      this.setState({ page: 1, pageSize: pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        this.getFindDate(values, "search");
      })
    }
    // 显示分页总条数
    showTotal (total) {
      return `共 ${total} 条`;
    }
    getValue = (cardType, patCardNo) => {
      this.setState({
        cardType,
        patCardNo,
      })
    }
    //获取查询数据
    getFindDate = (values, e) => {
      const overTime = moment().add(7, 'days').format('YYYY-MM-DD')
      if (this.state.total == 0) {
        this.setState({
          searchLoading: true
        })
      }
      let { page, pageSize, cardType, patCardNo, } = this.state;
      let data = {}
      data = {
        params: [{
          cardTypeID: cardType,
          cardNo: patCardNo,
          hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",//医院Id
          locID: values && values.locaId || "",//科室
          docID: values && values.doctorId || "",//医生
          regTitleID: values && values.jobLeverId || "",//挂号职称/排班类型
          number: values && values.patInfo || "",//病人基本信息
          bookDateFlag: values && values.isTime == true ? "Y" : (values && values.isTime == false ? "N" : "Y"),//是否按预约时间
          dateFrom: values && values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),//开始日期
          dateTo: values && values.dateTo ? moment(values.dateTo).format('YYYY-MM-DD') : moment(overTime).format('YYYY-MM-DD'),//截止日期
          bookMethodID: values && values.orderTypeId || "",//预约方式
          timeRangeID: values && values.orderTimeDayId || "",//预约时段
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      $http.post('urlS', this, {
        code: '03040020',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              searchLoading: false,
              rowId: "",
              search: e
            })
            this.setState({
              orderPatData: res.result.data, total: res.result.totalCount,
            }, () => {
            })
          } else {
            this.setState({
              searchLoading: false
            })
          }
        },
        error: function () {
          this.setState({
            searchLoading: false
          })
        }
      })
    }
    //点击查询---预约列表
    findData = () => {
      this.props.form.validateFields((err, values) => {
        if ((values.dateFrom && values.dateFrom) && (values.dateTo && values.dateTo)) {
          if (moment(values.dateFrom).format('YYYYMMDD') > moment(values.dateTo).format('YYYYMMDD')) {
            this.setState({
              starNoVisible: true,
              startNoMessage: "开始日期大于结束日期",
            }, () => {
              setTimeout(() => {
                this.visibleTip()
              }, 1500)
            })
            return
          }
        }
        if (!err) {
          this.setState({
            values: values,
            rowIds: ""
          })
          this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
            let { values } = this.state;
            this.onShowSizeChange("1", this.state.pageSize)
          })
        }
      })
    }
    handleOk = (e) => {
      this.setState({ loading: true });
      setTimeout(() => {
        this.setState({ loading: false, visible: false });
      }, 3000);
    }
    //点击是否生效按门诊日期查询
    handleSwithChange = (v) => {
      // this.findData()
    }
    //点击查询后 表格行
    setRowClassNames = (record) => {
      //   return record.patNo === this.state.rowIds ? 'clickRowStyle' : '';
    }
    //点击Row
    onClickRow = (record) => {
      return {
        onClick: () => {
          this.setState({
            parms: record,
          })
          if (this.state.rowId === "") {
            this.setState({
              rowIds: record.patNo,
            });
          } else {
            if (this.state.rowId !== record.patNo) {
              this.setState({
                rowIds: record.patNo,
              });
            } else {
              this.setState({
                rowIds: "",
                detailInfo: {},
              });
            }
          }
        },
      };
    }
    //选择科室类型  清空医生 
    selectLocId = (data) => {
      this.props.form.setFieldsValue({ doctorId: undefined })
      this.setState({
        locID: data
      }, () => {
        this.getDoctor()
      })
    }
    //隐藏提示信息
    visibleTip = () => {
      this.setState({
        starNoVisible: false,
      })
    }
    render () {
      const { getFieldDecorator } = this.props.form;
      const { baseParms, searchLoading, localArr, doctorArr, jobLeverArr, exportLoading, widthTotal, columns, orderTypeArr, orderTimeDayArr } = this.state;
      const mesIcon = <Icon type="exclamation-circle" />
      const overTime = moment().add(7, 'days').format('YYYY-MM-DD')
      //科室
      let localArrOp = []
      localArr && localArr.map(item => {
        localArrOp.push(<Option key={item.id} disabled={item.disabled} value={item.id} title={item.descripts}>{item.descripts}</Option>)
      })

      //医生
      let doctorArrOp = []
      doctorArr && doctorArr.map(item => {
        doctorArrOp.push(<Option title={item.descripts} key={item.id} value={item.id}>{item.descripts}</Option>)
      })

      //排班类型
      let jobLeverArrOp = []
      jobLeverArr && jobLeverArr.map(item => {
        jobLeverArrOp.push(<Option title={item.descripts} key={item.id} value={item.id}>{item.descripts}</Option>)
      })

      //预约方式
      let orderTypeArrOp = []
      orderTypeArr && orderTypeArr.map(item => {
        orderTypeArrOp.push(<Option key={item.id} title={item.descripts} value={item.id}>{item.descripts}</Option>)
      })

      //预约时段
      let orderTimeDayOp = []
      orderTimeDayArr && orderTimeDayArr.map(item => {
        orderTimeDayOp.push(<Option key={item.id} value={item.id}>{item.descripts}</Option>)
      })
      return (
        <div style={{ padding: '4px 2px' }} className="patientAppDom">
          <Form>
            <Row gutter={60} style={{ margin: '0' }}>
              <Col span={6}>
                <FormItem label='人员标识' {...formItemLayoutInfo}>
                  {getFieldDecorator('patInfo', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }]
                  })(
                    <Input
                      allowClear
                      placeholder='病人ID/姓名/身份证号码/手机号码'
                      onPressEnter={this.findData}
                      style={{ width: '100%' }}
                    />
                  )}
                </FormItem>
              </Col >
              <CardTypeRead getValue={this.getValue} getQuery={this.findData}></CardTypeRead>
              <Col span={3} style={{ padding: "0" }}>
                <FormItem label='科室' {...formItemLayout}>
                  {getFieldDecorator('locaId', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select
                      showSearch
                      allowClear
                      optionFilterProp="title"
                      placeholder='请选择科室'
                      style={{ width: '100%' }}
                      onChange={this.selectLocId}
                    >
                      {localArrOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={3} >
                <FormItem label='医生' {...formItemLayout}>
                  {getFieldDecorator('doctorId', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }]
                  })(
                    <Select
                      showSearch
                      allowClear
                      optionFilterProp="title"
                      placeholder='请先选择科室'
                      style={{ width: '100%' }}
                      onSelect={this.patCardType}
                    >
                      {doctorArrOp}
                    </Select>
                  )}
                </FormItem>
              </Col >
              <Col span={4}>
                <FormItem label='排班类型' {...formItemLayout}>
                  {getFieldDecorator('jobLeverId', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }]
                  })(
                    <Select
                      showSearch
                      allowClear
                      optionFilterProp="title"
                      placeholder='请选择排班类型'
                      style={{ width: '100%' }}
                    // onSelect={this.patCardType} 
                    >
                      {jobLeverArrOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={5}>
                <FormItem label='预约方式' {...formItemLayout}>
                  {getFieldDecorator('orderTypeId', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }]
                  })(
                    <Select
                      showSearch
                      allowClear
                      optionFilterProp="title"
                      placeholder='请选择预约方式'
                      style={{ width: '100%' }}
                    // onSelect={this.patCardType} 
                    >
                      {orderTypeArrOp}
                    </Select>
                  )}
                </FormItem>
              </Col >
              <Col span={4} className="starDataDom">
                <Tooltip getPopupContainer={() => document.querySelector('.starDataDom')} overlayStyle={{ zIndex: 999, }} overlayClassName="toolTipDom starData" title={<div className="titleIcon">{mesIcon}<span >{this.state.startNoMessage}</span></div>} visible={this.state.starNoVisible}>
                  <FormItem label='开始日期' {...formItemLayout}>
                    {getFieldDecorator('dateFrom', {
                      initialValue: moment(),
                      rules: [{ required: false, message: '' }],
                    })(
                      <DatePicker onFocus={this.visibleTip} onChange={this.visibleTip} style={{ width: '100%' }} placeholder={'起始日期'} />
                    )}
                  </FormItem>
                </Tooltip>
              </Col>
              <Col span={4}>
                <FormItem label='截止日期' {...formItemLayout}>
                  {getFieldDecorator('dateTo', {
                    initialValue: moment(overTime, 'YYYY-MM-DD'),
                    rules: [{ required: false, message: '' }],
                  })(
                    <DatePicker style={{ width: '100%' }} placeholder={'截止日期'} />
                  )}
                </FormItem>
              </Col >
              <Col span={3}>
                <FormItem label='时段' {...formItemLayoutTimer}>
                  {getFieldDecorator('orderTimeDayId', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }]
                  })(
                    <Select
                      showSearch
                      allowClear
                      optionFilterProp="title"
                      placeholder='请选择时段'
                      style={{ width: '100%' }}
                    // onSelect={this.patCardType} 
                    >
                      {orderTimeDayOp}
                    </Select>
                  )}
                </FormItem>
              </Col >
              <Col span={5} style={{ padding: 0 }}>
                <FormItem label="按预约时间查询" {...formItemLayoutTime}>
                  {getFieldDecorator('isTime', {
                    initialValue: true,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={true} onChange={(val) => this.handleSwithChange(val,)} />
                  )}
                </FormItem>
              </Col>
              <Col span={1} style={{ paddingLeft: "0 !important" }}>
                <FormItem  {...formItemLayout}>
                  {getFieldDecorator('export', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button
                      onClick={this.exportData}
                      loading={exportLoading}
                      type="primary"
                      disabled={this.state.orderPatData && this.state.orderPatData.length == 0}
                    >
                      导出
                    </Button>
                  )}
                </FormItem>
              </Col>
              <Col span={2} style={{ paddingLeft: "0" }}>
                <FormItem  {...formItemLayout}>
                  {getFieldDecorator('findData', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button onClick={this.findData} loading={searchLoading} type="primary">查询</Button>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Table
            scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: store.getState().tableHeight.y - 32 }}
            columns={columns && columns.length > 0 ? columns : []}
            dataSource={this.state.orderPatData}
            pagination={false}
            rowKey={record => record.key}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassNames}
            bordered
            style={{ height: store.getState().tableHeight.y + 84 + 'px', marginTop: '9px', }}
          />
          <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.orderPatData}
            onChange={this.onChange.bind(this)} />
          {/* {
            this.state.orderPatData&&this.state.orderPatData.length>0?<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", }}
          />:""
          } */}
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='BookInfoList'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.getMainTableColumns}
          />
        </div>
      )
    }
  })
export default PatientAppInfoFind    