/*
 * Creator:     ML
 * CreatDate:   2019-12-01
 * descripts：  就诊年份 就诊记录 日期 搜索条件 
 * */
import React from 'react';
import moment from 'moment';
import { dayFormat } from 'tools/index';
import { Form, Col, Select, Icon, Tooltip } from 'antd';
import RangeDatePicker from 'components/rangePicker/index';
import { $http } from 'containers/config/https';
import "../style/doctorAdviceFind.less"

//组件const
const Option = Select.Option;
const FormItem = Form.Item;
const padding = {
  padding: "0px"
}
const formItemLayoutYear = {
  labelCol: { span: 11 },
  wrapperCol: { span: 13 }
}

const formItemLayout = { // label 和input宽度
  labelCol: { span: 6 },
  wrapperCol: { span: 17 }
}
const ViewSelectComponent = Form.create()(
  class ViewSelectComponent extends React.Component {
    constructor(props) {
      super(props);
      var date = new Date();
      this.state = {
        yearArr: [],
        adviceLogArr: [],
        typeArr: [],
        StartDate: undefined,  // //开始日期
        EndDate: moment(date).format(dayFormat),  // //结束日期
        advicelogMessage:"",
        advicelogVisible:false,
        requid:this.props.requireds,
        requireds:true
      };
    }

    componentWillReceiveProps(nextProps) {
    }
    componentDidMount = () => {
      this.getAllSelect()
      this.props.onRefs(this)
    }
    //就诊年份 -- 获取就诊记录
    handleYears = (years) => {
      if (years) {
        this.yearsToLog(years)
        this.props.getValue(this.props.form.getFieldValue('adviceYear'),"" ,this.state.StartDate,this.state.EndDate)
      } else {
        this.yearsToLog("")
        this.props.getValue("","" ,this.state.StartDate,this.state.EndDate)
      }
      this.props.form.setFieldsValue({ adviceLog: undefined })
    }
    //就诊记录--自动获取开始医嘱日期
    handleLog = (data, years,id) => {
      this.setState({
        StartDate: "",
      }, () => {
        this.props.form.setFieldsValue({
          adviceYear: years
        })
        this.setState({
          StartDate: data,
        }, () => {
            this.props.getValue(years,id,this.state.StartDate,this.state.EndDate)
            setTimeout(()=>{
              this.props.handleFind()
            },300)
          }
        )
      })
    }
    handleClear=(id)=>{
      if(!id){
        this.setState({
          StartDate:undefined,
          EndDate:undefined
        },()=>{
          this.props.form.setFieldsValue({adviceYear:undefined})
          this.props.getValue(this.props.form.getFieldValue("adviceYear"),"",this.state.StartDate,this.state.EndDate)
          setTimeout(()=>{
            this.props.handleFind()
          },300)
        })
      }
    }
       //就诊记录tips
       adviceLogTip = () => {
        this.props.form.validateFields(['adviceLog',], (errors, values) => {
            if (!errors) {
                this.props.handleFind()
                this.setState({
                    advicelogVisible: false
                })
                
            } else {
                this.setState({
                    advicelogVisible: true,
                    advicelogMessage: errors.adviceLog.errors[0].message,
                })
                setTimeout(() => {
                    this.setState({
                        advicelogVisible: false
                    })
                }, 1500)
            }
        });
    }
    //验证必填项
    handleVail=()=>{
        this.adviceLogTip()
    }
    //隐藏错误提示
    visibled=()=>{
      this.setState({
        advicelogVisible: false
    })
    }
    //开始日期
    startChange(date) {
      this.setState({
        StartDate: date,
      },()=>{
        this.props.getValue(this.props.form.getFieldValue('adviceYear'),this.props.form.getFieldValue('adviceLog') ,this.state.StartDate,this.state.EndDate)
      })
    }
    //结束日期
    endChange(date) {
      this.setState({
        EndDate: date,
      },()=>{
        this.props.getValue(this.props.form.getFieldValue('adviceYear'),this.props.form.getFieldValue('adviceLog') ,this.state.StartDate,this.state.EndDate)
      })
    }
    //获取查询条件下拉
    getAllSelect = () => {
      let data = {}
      data = {
        params: [{
          patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
          admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
          admYearsFlag: "Y",//就诊年限
          orderTypeFlag: "Y",//医嘱类型
          admRecordFlag: "Y",//就诊记录
          orderStatusFlag: "Y",//医嘱状态
          // AllFlag:"Y"
        }],
      }
      $http.post('urlS', this, {
        code: '03050130',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({
              yearArr: res.result.admYears,
              adviceLogArr: res.result.admRecord,
              typeArr: res.result.ordPriority,
              statusArr: res.result.ordStatus,
            }, () => {
              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)
                    this.props.getValue(this.props.form.getFieldValue('adviceYear'),this.props.form.getFieldValue('adviceLog') ,this.state.StartDate,this.state.EndDate)
                  })
                }
              })
            })
          }
        }
      })
    }
    //选择就诊年份获取急诊记录
    yearsToLog = (years) => {
      let data = {}
      data = {
        params: [{
          patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
          admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
          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,
            }, () => {

            })
          }
        }
      })
    }
    getRequireds=()=>{
      this.setState({
        requireds:false
      })
    }
    render() {
      const { getFieldDecorator } = this.props.form;
      const { collArr, yearArr, adviceLogArr, activeKey, typeArr, statusArr, columns, widthTotal } = this.state;
      var date = new Date();
      let searchColConfig = {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: this.props&&this.props.modal?8:5}
      }
      const mesIcon = <Icon type="exclamation-circle" />
      //就诊年份
      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>)
      })
      //就诊记录
      let adviceLogOp = []
      adviceLogArr && adviceLogArr.map(item => {
        adviceLogOp.push(<Option className="DoctorAdviceFind-optionLeft" key={item.admID} role={item.admStr + '^' + item.admStr} onClick={() => this.handleLog(item.admDate, item.years,item.admID)} title={item.admStr} value={String(item.admID)}>{item.thisTime=="Y"?<span style={{color:"#1999db",marginRight:"4px"}}>本次</span>:""}{item.admStr}</Option>)
      })
      // console.log("this.props.required",this.props.requireds,"this.state.requid",this.state.requid)
      return (
        <div className="viewSelectDom">
          <Form>
            <Col span={3} style={padding}>
              <FormItem {...formItemLayoutYear} label={this.props.locale == 'EN' ? 'Visit year' : '就诊年份'}>
                {getFieldDecorator('adviceYear', {
                  initialValue: undefined,
                  rules: [{ required: false, message: '' }],
                })(
                  <Select
                    style={{ width: "100%" }}
                    allowClear={true}
                    showSearch={true}
                    optionFilterProp="role"
                    onChange={this.handleYears}
                  >
                    {yearOp}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6} style={padding} className="select-item">
            <Tooltip getPopupContainer={() => document.querySelector('.select-item')} overlayStyle={{ zIndex: 999, }} overlayClassName="toolTipDom adviceLogNo" title={<div className="titleIcon">{mesIcon}<span >{this.state.advicelogMessage}</span></div>} visible={this.state.advicelogVisible}>
              <FormItem {...formItemLayout} label={this.props.locale == 'EN' ? 'Medical record' : '就诊记录'} >
                {getFieldDecorator('adviceLog', {
                  initialValue: undefined,
                  rules: [{ required: this.state.requireds, message:this.props.locale == 'EN' ? 'Please select the medical records you need to check' : '请选择需要查询的就诊记录' }],
                })(
                  <Select
                    className="logDom"
                    style={{ width: "100%", textAlign: "left", }}
                    showSearch={true}
                    optionFilterProp="role"
                    dropdownStyle={{
                      textAlign: "left",
                    }}
                    allowClear={!this.state.requireds}
                    onChange={this.handleClear}
                    onFocus={this.visibled}
                  >
                    {adviceLogOp}
                  </Select>
                )}
              </FormItem>
            </Tooltip>
            </Col>
            <Col {...searchColConfig} style={{ padding: "4px 0" }}>
              <RangeDatePicker isChange={true} label={this.props.locale == '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>
            </Form>
        </div>
      );
    }
  })
export default ViewSelectComponent
