import React, {Component} from 'react';
import {Button, Card, Col, Input, Row, Radio, Checkbox, Select, DatePicker, message} from "antd";
import './style/AppointmentRecordHandle.less'
import moment from "moment";
import {$http} from "../../containers/config/https";

const Option = Select.Option

class AppointmentRecordHandle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      radioValue: '', // 单选框value
      isHandleMethod: false, // 复选框状态
      isTemplateID: false,  // 复选框状态
      isNotifyRemark: false,  // 复选框状态
      handleMethod: '', // 复选框数据
      templateID: '', // 复选框数据
      notifyRemark: '', // 复选框数据
      dateSelect: moment(), // 日期重新选择
      cancelReason: '', // 取消原因
      noProcessingRemark: '', // 待处理备注
      appointStatics: [], // 日期预约人数
      SMSTemolate: [],
      reason: [],
      appointTime: [],
    }
  }

  componentDidMount() {
    this.initialPropsValue()
    this.basicDataInitial()
  }

  initialPropsValue() {
    // 初始化数据
    const {patInfo} = this.props
    let statusID = patInfo && 'statusID' in patInfo ? patInfo.statusID : ''
    if (statusID === '2') {
      statusID = '1'
    } else if (statusID === '3') {
      statusID = '2'
    } else if (statusID === '4') {
      statusID = '3'
    }


    const isHandleMethod = statusID === '1' && patInfo && 'handleMethod' in patInfo && patInfo.handleMethod === 'M'
    const isTemplateID = statusID === '1' && patInfo && 'handleMethod' in patInfo && patInfo.handleMethod === 'S'
    const isNotifyRemark = statusID === '1' && patInfo && 'handleMethod' in patInfo && patInfo.handleMethod === 'O'
    const templateID = statusID === '1' && isTemplateID && patInfo && 'handleMethod' in patInfo && patInfo.handleMethod === 'S' ? '1' : ''
    const notifyRemark = statusID === '1' && isNotifyRemark && patInfo && 'remark' in patInfo ? patInfo.remark : ''

    const cancelID = statusID === '3' && patInfo && 'reasonID' in patInfo ? patInfo.reasonID : ''


    const dateSelect = statusID === '3' && patInfo && 'appointDate' in patInfo ? moment(patInfo.appointDate) : null

    const noProcessingRemark = statusID === '4' && patInfo && 'remark' in patInfo ? patInfo.remark : ''

    this.setState({
      radioValue: +statusID,
      noProcessingRemark,
      dateSelect,
      notifyRemark,
      isNotifyRemark,
      isTemplateID,
      isHandleMethod,
      templateID
    })
  }

  onChange = (e) => {
    this.setState({
      radioValue: e.target.value
    })
  }

  // 通知就诊复选框
  checkBox = (e) => {
    this.setState({isHandleMethod: false, isTemplateID: false, isNotifyRemark: false, handleMethod: ''})
    if (e.target.value === 'handleMethod') {
      this.setState({isHandleMethod: e.target.checked, handleMethod: 'M'})
    }
    if (e.target.value === 'templateID') {
      this.setState({isTemplateID: e.target.checked, handleMethod: 'S'})
    }
    if (e.target.value === 'remark') {
      this.setState({isNotifyRemark: e.target.checked, handleMethod: 'O'})
    }
  }

  // 短信提醒模板ID选择
  templateChange = (value) => {
    this.setState({templateID: value.props.id})
  }

  // 就诊通知备注
  notifyRemarkChange = (value) => {
    this.setState({notifyRemark: value.target.value})
  }

  // 修改预约时间
  dateOnChange = (value) => {
    const dateSelect = moment(value).format('YYYY-MM-DD')
    const nowDate = moment().format('YYYY-MM-DD')
    if (nowDate <= dateSelect) {
      this.setState({dateSelect: value})
    } else {
      message.error('不能预约过去日期！')
    }
  }

  // 取消预约原因选择
  cancelReasonChange = (value) => {
    this.setState({cancelReason: value.props.id})
  }

  // 暂不处理备注
  noProcessingRemarkChange = (value) => {
    this.setState({noProcessingRemark: value.target.value})
  }

  // 预约人数返回
  checkAppointmentTotal = (e) => {
    let total = 0
    this.state.appointStatics.map(item => {
      if (item.appointDate === e) {
        total = item.total
      }
    })
    return total
  }

  // 预约复诊界面初始化查询接口 -- 17030002
  basicDataInitial = () => {
    let data = {
      params: [
        {
          appointType: 'Y',  //预约类型下拉列表  Y
          appointTime: 'Y',  //预约时间段下拉列表  Y
          appointStatics: 'Y', //每日预约人数统计列表
          SMSTemolate: "Y", //短信模板
          reason: "Y"  //原因
        }
      ]
    }
    $http.post('urlS', this, {
      code: '17030002',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            appointType: res.result.appointType,
            appointTime: res.result.appointTime,
            appointStatics: res.result.appointStatics,
            optometryDoctor: res.result.optomeDoctor,
            SMSTemolate: res.result.SMSTemolate,
            reason: res.result.reason,
          })
        }
      }
    })
  };

  // 处理检查预约（通用）-- 17030004
  appointmentCheckProcessing = () => {
    const {handleMethod, radioValue, templateID, notifyRemark, dateSelect, cancelReason, noProcessingRemark} = this.state
    const appointArr = this.props.patInfo && 'glassesAppointID' in this.props.patInfo ? this.props.patInfo.glassesAppointID : ''
    let glassesAppointIDs = appointArr === '' ? this.props.appointArr : [appointArr]
    const notify = { //就诊通知 -- 标记未已处理
      enable: radioValue === 1 ? 'Y' : '',
      handleMethod: handleMethod,  //Mobile ,SMS,Other 首字母
      templateID: handleMethod === 'S' ? templateID : undefined, //短信模板ID 4.2接口查询下拉列表
      remark: handleMethod === 'O' ? notifyRemark : undefined, //handleMethod 为 Other填r填写
    }
    const modify = { //就诊通知 -- 标记为未处理
      enable: radioValue === 2 ? 'Y' : '',
      modifyToDate: dateSelect !== null && dateSelect.format('YYYY-MM-DD') //修改后的预约日期
    }
    const cancel = { //就诊通知 -- 标记未已处理
      enable: radioValue === 3 ? 'Y' : '',
      reason: cancelReason //取消的原因
    }
    const noProcessing = { //就诊通知 -- 标记为未处理
      enable: radioValue === 4 ? 'Y' : '',
      remark: noProcessingRemark //修改备注
    }
    let data = {
      params: [
        {
          glassesAppointIDs,
          notify: notify,
          modify: modify,
          cancel: cancel,
          noProcessing: noProcessing
        }
      ]
    };
    $http.post('urlS', this, {
      code: '17030004',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('处理成功')
          this.props.handleThis.handleOk()
        }
      }
    })
  };

  render() {
    const {patInfo} = this.props
    const {SMSTemolate, reason, radioValue, notifyRemark, noProcessingRemark, isHandleMethod, isTemplateID, isNotifyRemark, dateSelect} = this.state
    const appointDate = patInfo && 'appointDate' in patInfo ? patInfo.appointDate : '无'
    const appointInterDesc = patInfo && 'appointInterDesc' in patInfo ? patInfo.appointInterDesc : ''
    return (
      <div className="glasses-order-details" style={{backgroundColor: 'rgb(245, 247, 254)', padding: 5}}>
        <Radio.Group onChange={this.onChange} value={radioValue} style={{width: "100%"}}>
          <Card title={<p style={{textAlign: "center", width: "100%", margin: 0, fontWeight: 1000}}>标记为已处理</p>}
                size="small"
                bodyStyle={{
                  borderLeftColor: "rgb(24, 141, 244)",
                  borderLeftStyle: "solid",
                  borderWidth: 2,
                  padding: 0
                }}
          >
            <Card title={<div><Radio value={1}>通知就诊</Radio></div>} size="small" type="inner">
              <Row>
                <Col span={3}>
                  <Checkbox disabled={radioValue !== 1} value="handleMethod" checked={isHandleMethod}
                            onChange={this.checkBox} style={{height: 32, marginTop: 5, marginLeft: 20}}>电话提醒</Checkbox>
                </Col>
              </Row>
              <br/>
              <Row>
                <Col span={3}>
                  <Checkbox disabled={radioValue !== 1} value="templateID" checked={isTemplateID}
                            onChange={this.checkBox} style={{height: 32, marginTop: 5, marginLeft: 20}}>
                    短信提醒
                  </Checkbox>
                </Col>
                <Col span={21}>
                  <Select disabled={!isTemplateID || radioValue !== 1}
                          defaultValue={patInfo && 'templateID' in patInfo && patInfo.templateID}
                          onChange={(value, option) => this.templateChange(option)} style={{width: "100%"}}
                          placeholder="请选择短信模板"
                  >
                    {SMSTemolate.map(item => {
                      return <Option id={item.id} value={item.id} key={item.id}
                                     style={{textAlign: "left"}}>{item.descripts}</Option>
                    })}
                  </Select>
                </Col>
              </Row>
              <br/>
              <Row>
                <Col span={3}>
                  <Checkbox value="remark" disabled={radioValue !== 1} checked={isNotifyRemark} onChange={this.checkBox}
                            style={{height: 32, marginTop: 5, marginLeft: 20}}>其他</Checkbox>
                </Col>
                <Col span={21}>
                  <Input disabled={!isNotifyRemark || radioValue !== 1} value={notifyRemark}
                         onChange={this.notifyRemarkChange} placeholder="请输入"/>
                </Col>
              </Row>
            </Card>
            <Card title={<div><Radio value={3}>取消预约</Radio></div>} size="small" type="inner">
              <Col span={3} style={{height: 32}}>
                <p style={{textAlign: "right", height: 32, marginTop: 5}}>取消原因：</p>
              </Col>
              <Col span={21}>
                <Select defaultValue={patInfo && 'reasonID' in patInfo && patInfo.reasonID} disabled={radioValue !== 3}
                        onChange={(value, option) => this.cancelReasonChange(option)} style={{width: "55%"}}
                        placeholder="请选择">
                  {reason.map(item => {
                    return <Option id={item.id} value={item.id} key={item.id}
                                   style={{textAlign: "left"}}>{item.descripts}</Option>
                  })}
                </Select>
              </Col>
            </Card>
          </Card>

          <Card title={<p style={{textAlign: "center", width: "100%", margin: 0, fontWeight: 1000}}>标记为未处理</p>}
                size="small"
                style={{marginTop: 5}}
                bodyStyle={{
                  borderLeftColor: "rgb(255, 61, 0)",
                  borderLeftStyle: "solid",
                  borderWidth: 2,
                  padding: 0
                }}
          >
            <Card title={<div><Radio value={2}>{`修改预约时间(当前预约时间：${appointDate} ${appointInterDesc})`}</Radio></div>}
                  size="small" type="inner">
              <Col span={3} style={{height: 32}}>
                <p style={{textAlign: "right", height: 32, marginTop: 5}}>请选择预约时间：</p>
              </Col>
              <Col span={21}>
                <DatePicker
                  value={dateSelect}
                  disabled={radioValue !== 2}
                  dropdownClassName="yyyyyy"
                  onChange={this.dateOnChange}
                  placeholder="请选择日期"
                  style={{width: "55%"}}
                  showToday={false}
                  dateRender={current => {
                    const today = moment().format('YYYY-MM-DD')
                    const currentDay = moment(current).format('YYYY-MM-DD')
                    const count = this.checkAppointmentTotal(currentDay)
                    return (
                      <div className="ant-calendar-date">
                        {current.date()}
                        {
                          count > 0 && currentDay >= today &&
                          <div style={{
                            color: "rgba(250,140,23,1)",
                            fontSize: 5,
                            fontWeight: "normal",
                            marginTop: -10
                          }}>{`${count}人`}</div>
                        }
                      </div>
                    );

                  }}
                />
              </Col>
            </Card>

            <Card title={<div><Radio value={4}>暂不处理</Radio></div>} size="small" type="inner">
              <Col span={3} style={{height: 32}}>
                <p style={{textAlign: "right", height: 32, marginTop: 5}}>备注：</p>
              </Col>
              <Col span={21}>
                <Input disabled={radioValue !== 4} value={noProcessingRemark} onChange={this.noProcessingRemarkChange}
                       placeholder="请输入"/>
              </Col>
            </Card>
          </Card>


          <Card size="small" bodyStyle={{padding: 5}}>
            <div style={{textAlign: "center"}}>
              <Button style={{width: 80}} onClick={() => {
                this.props.handleThis.handleCancel()
              }}>取消</Button>
              <Button type="primary" style={{marginLeft: 40, width: 80}}
                      onClick={this.appointmentCheckProcessing}
              >
                确定
              </Button>
            </div>
          </Card>
        </Radio.Group>
      </div>
    );
  }
}

export default AppointmentRecordHandle;