/*
 * Creator:     WRX
 * CreatDate:   2022-08-22
 * descripts：  角膜塑形站预约复诊
 * */
import React from 'react';
import {
  Row,
  Col,
  Select,
  Button,
  DatePicker,
  Icon,
  message,
  Calendar,
  Card,
  Popconfirm
} from 'antd';
import moment from 'moment';
import { $http } from "../../containers/config/https";
import './style/AppointmentVisit.less'
import PubilcTablePagination from "../common/PubilcTablePagination";

const Option = Select.Option;
const { MonthPicker } = DatePicker;

const AppointmentVisit = (
  class ViewTextReport extends React.Component {
    constructor(props) {
      super(props)
      this.userData = React.$getSessionData();
      this.patData = React.$getSessionData('titleData');
      this.state = {
        nowDateTime: moment(), // 控制日历组件的日期显示
        selectedValue: moment(),// 控制日历的选中日期，用于控制入参
        appointType: [],// 预约类型下拉
        appointTime: [],// 预约时间下拉
        appointStatics: [],// 已约人数显示
        appointTimeSelect: {}, // 选择预约时段
        appointTypeSelect: '',// 预约类型选择
        pageSize: 20,
        page: 1,
        optometryDoctor: [],// 验光师列表
        optometryDoctorID: '', // 选择验配师ID
        styleName: ''// 样式修改
      }
    }

    componentDidMount() {
      const nowDate = moment().format('YYYY-MM-DD')
      const nowDateFormat = moment(nowDate)
      this.setState({ nowDateTime: nowDateFormat })
      this.todayNumColor()
      // 初始化设置table的高度以及表体的高度
      //document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y　+ 51 + 'px';
      this.getTableColumns();
      this.basicDataInitial();
      this.appointmentListQuery();

      // 设置日历日期格式为星期几的格式
      moment.updateLocale('zh-cn', {
        weekdaysMin: ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      })
    }

    componentWillUnmount() {
      // 设置日历日期格式为星期几的格式
      moment.updateLocale('zh-cn', {
        weekdaysMin: ['日', '一', '二', '三', '四', '五', '六']
      })
    }

    onColumnRef = (ref) => {
      this.columnRef = ref;
    }

    // 获取列表头数据 -- 01040073
    getTableColumns = async () => {
      let operationObj = {
        width: 80,
        title: '操作',
        align: 'center',
        key: 'operation',
        render: (text, record) => (
          <Popconfirm title="取消后不可恢复，确定要取消吗?" onClick={(e) => React.$stopPropagation(e)} onConfirm={(e) => this.appointmentCheckProcessing(record)} >
            <Button
              type="link"
              style={{ color: record.statusID === '4' ? "grey" : "red" }}
              size="small"
              disabled={record.statusID === '4'}
            >
              取消
            </Button>
          </Popconfirm>

        ),
      };
      try {
        let data = {
          params: [{
            compontName: 'AppointmentVisitList',
            type: 'C',
          }]
        }
        let res = await React.$asyncPost(this, '01040073', data);
        let filterArr = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
        if (filterArr && filterArr.length > 0) {
          let columns = []
          columns = filterArr && filterArr.length > 0 ? [...filterArr, operationObj] : []
          this.setState({
            columns: columns,
            totalWidth: res.totalWidth
          })
        }
      } catch (error) {
        console.log(error)
      }
    }

    // 预约复诊 -- 17030001
    appointmentVisitAdd = () => {
      const { appointTimeSelect, selectedValue, appointTypeSelect } = this.state
      let data = {
        params: [
          {
            glassesAppointID: '',      //主键ID
            patientID: this.patData.patID,  //病人ID
            admID: this.patData.admID,      //就诊ID
            appointTypeID: appointTypeSelect,//预约类型
            appointDate: selectedValue.format('YYYY-MM-DD'),//预约日期
            appointInterID: appointTimeSelect.id,      //预约时段
            statusID: '1',            //预约状态
            handleMethod: '',         //非必传，处理方式 Mobile ,SMS,Other 首字母
            remark: ''            //备注
          }
        ]
      }
      if (appointTypeSelect === '') {
        message.error('请选择预约类型')
      } else if (appointTimeSelect.id === undefined || appointTimeSelect.id === '') {
        message.error('请选择预约时段')
      } else {
        $http.post('urlS', this, {
          code: '17030001',
          data,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success('预约成功')
              this.appointmentListQuery()
              this.basicDataInitial()
            }
          }
        })
      }
    };

    // 预约复诊界面初始化查询接口 -- 17030002
    basicDataInitial = () => {
      let data = {
        params: [
          {
            appointType: 'Y',  //预约类型下拉列表  Y
            appointTime: 'Y',  //预约时间段下拉列表  Y
            appointStatics: '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
            })
          }
        }
      })
    };

    // 预约分页查询列表 -- 17030003
    appointmentListQuery = () => {
      const { optometryDoctorID } = this.state
      const userID = this.userData.userID
      let data = {
        params: [
          {
            startDate: this.state.selectedValue.format('YYYY-MM-DD'),  //查询开始日期
            endDate: this.state.selectedValue.format('YYYY-MM-DD'),    //查询结束日期
            keywords: '',   //关键词
            doctorID: optometryDoctorID === '' ? userID : optometryDoctorID,   //预约医生ID
            statusID: ''  //预约状态ID 1待处理  2已处理 3延后 4取消
          }
        ],
        pagination: [
          {
            pageSize: this.state.pageSize,   //页面大小
            currentPage: this.state.page, //当前页
          }
        ]
      };
      $http.post('urlS', this, {
        code: '17030003',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({ tableData: res.result.rows, total: res.result.total })
          }
        }
      })
    };

    // 处理检查预约（通用）-- 17030004
    appointmentCheckProcessing = (record) => {
      const cancel = {
        enable: 'Y',
        reason: "取消预约" //修改后的预约日期
      }
      let data = {
        params: [
          {
            glassesAppointIDs: [record.glassesAppointID],
            cancel: cancel,
          }
        ]
      };
      $http.post('urlS', this, {
        code: '17030004',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success('取消成功')
            this.appointmentListQuery();
            this.basicDataInitial()
          }
        }
      })
    };

    // 预约类型选择
    selectAppointmentType = (value) => {
      this.setState({ appointTypeSelect: value.props.id })
    }

    // 单击选择时段
    selectAppointmentTime = (item) => {
      this.setState({ appointTimeSelect: item })
    }

    // 双击选择时段并预约
    selectAndAppointment = (item) => {
      this.setState({ appointTimeSelect: item }, () => {
        this.appointmentVisitAdd();

      })
    }

    // +---------------------Table 操作相关 ------------------------------+
    // 分页操作
    compilePage = (page, pageSize) => {
      this.setState({ page, pageSize }, () => {
        this.appointmentListQuery();
      })
    }

    // +-----------------------日历组件相关--------------------------------+
    onSelect = (value) => {
      const selectDate = moment(value).format('YYYY-MM-DD') // 选择的日期
      const nowDate = moment().format('YYYY-MM-DD') // 今天的日期
      if (nowDate <= selectDate) {
        this.setState({
          nowDateTime: value,
          selectedValue: value,
        }, () => {
          this.appointmentListQuery()
          this.todayNumColor()
        });
      } else {
        message.error("不能预约过去时间！")
      }
    };

    // 上一月
    preMonth = (value) => {
      const selectDate = moment(value).add(-1, 'month') // 选择的日期
      const selectMouthFormat = moment(value).add(-1, 'month').format('YYYY-MM') // 选择的月份
      const nowDate = moment().format('YYYY-MM') // 今天的日期
      const selectDateFormat = moment(value).add(-1, 'month').format('YYYY-MM-DD') // 选择的日期
      if (nowDate <= selectMouthFormat) {
        this.setState({
          nowDateTime: selectDate,
        }, () => {
          this.todayNumColor('pre', selectDateFormat)
        }
        );
      } else {
        message.error("不能预约过去时间！")
      }
    }

    // 下一月
    lastMonth = (value) => {
      const selectDate = moment(value).add(1, 'month') // 选择的日期
      const selectDateFormat = moment(value).add(1, 'month').format('YYYY-MM-DD') // 选择的日期
      const nowDate = moment().format('YYYY-MM-DD') // 今天的日期
      if (nowDate <= selectDateFormat) {
        this.setState({
          nowDateTime: selectDate
        }, () => {
          this.todayNumColor('last', selectDateFormat)
        }
        );
      }
    }

    // 颜色选择
    colorSelect = (e) => {
      if (e === '1') {
        return 'blue'
      }
      if (e === '2') {
        return 'red'
      }
      if (e === '3') {
        return 'green'
      }
    }

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

    cardColorCase = (item) => {
      if (item.id === this.state.appointTimeSelect.id) {
        return true
      }
    }

    optometryDoctorChange = (option) => {
      this.setState({
        optometryDoctorID: option.props.doctorid
      })
    }

    // 日历颜色样式逻辑
    todayNumColor = (style, changeMouth) => {
      const selectedValueFormat = this.state.selectedValue.format('YYYY-MM-DD')
      const nowDateTimeFormat = moment().format('YYYY-MM-DD')

      if (style === 'last' && changeMouth !== selectedValueFormat) { // 如果是由月份组件控制翻页，则不显示蓝色
        this.setState({ styleName: 'reportDom-Calendar-Select-Default' })
      } else if (style === 'last' && changeMouth === selectedValueFormat) { // 如果使用下一月控件，则当控制翻页的日期 = 选择的日期时 显示蓝色
        this.setState({ styleName: '' })
      } else if (style === 'pre' && changeMouth !== selectedValueFormat) { // 如果使用上一月控件，则当控制翻页的日期 = 选择的日期时 显示蓝色
        this.setState({ styleName: 'reportDom-Calendar-Select-Default' })
      } else if (selectedValueFormat === nowDateTimeFormat) {// 如果选择的时间 = 今天的时间，则显示粉红色字体样式
        this.setState({ styleName: 'reportDom-Calendar' })
      } else { // 否则使用默认预设全局样式
        this.setState({ styleName: '' })
      }
    }

    render() {
      const monthFormat = "YYYY年MM月";
      const { nowDateTime, total, tableData, columns, totalWidth, page, loading, styleName } = this.state;
      return (
        <div style={{ padding: '4px 2px', backgroundColor: 'rgb(245,247,254)' }} className="reportDom">
          <Row>
            <Col span={11}>

              <Card bodyStyle={{ padding: "6px 12px" }} bordered={true} size='small'
                title={<div><Icon type="minus-square" theme="twoTone" style={{ marginRight: 5 }} />请选择预约时间</div>}
              >
                <Row gutter={8}>
                  <Col span={12}>
                    <span>预约验光师:</span>
                    <Select style={{ width: "60%", marginLeft: 5 }}
                      defaultValue={this.userData.userName}
                      onChange={(value, option) => this.optometryDoctorChange(option)}
                    >
                      {
                        this.state.optometryDoctor.map(item => {
                          return <Option key={item.id} doctorid={item.id}>{item.descripts}</Option>
                        })
                      }
                    </Select>
                  </Col>

                  <Col span={12}>
                    <span><span style={{ color: "red" }}>*</span>预约类型:</span>
                    <Select style={{ width: "60%", marginLeft: 5 }} placeholder="请选择"
                      onChange={(value, option) => this.selectAppointmentType(option)}>
                      {this.state.appointType.map(item => {
                        return <Option key={item.id} code={item.code} id={item.id}>{item.descripts}</Option>
                      })}
                    </Select>
                  </Col>
                </Row>
              </Card>

              <Card bordered={true} size="small" style={{ marginTop: 4, marginBottom: 4 }} bodyStyle={{ padding: '6px 12px' }}>
                <Calendar
                  className={styleName}
                  value={nowDateTime}
                  fullscreen={false}
                  onSelect={this.onSelect}
                  headerRender={({ value }) => {
                    return <div className="flex-between-center" style={{ paddingBottom: '6px' }}>
                      <span style={{ color: "#1890ff" }}>预约日期</span>
                      <div className="flex-align-items">
                        <Button
                          type="primary"
                          ghost
                          size="small"
                          style={{ marginRight: 10 }}
                          onClick={() => {
                            this.setState({
                              nowDateTime: moment(),
                              selectedValue: moment(),
                            }, () => {
                              this.todayNumColor()
                            })
                          }}
                        >
                          本月
                        </Button>

                        <div className="flex-align-items" style={{ marginLeft: '12px' }}>
                          <Button style={{
                            borderRight: 0,
                            borderBottomRightRadius: 0,
                            borderTopRightRadius: 0,
                            width: 20
                          }}
                            onClick={() => {
                              this.preMonth(nowDateTime)
                            }}
                          >
                            <Icon type="left" style={{ marginLeft: -7 }} />
                          </Button>
                          <MonthPicker
                            allowClear={false}
                            value={moment(value, monthFormat)}
                            format={monthFormat}
                            style={{ width: 120 }}
                            onChange={(value) => {
                              this.onSelect(value)
                            }}
                          />
                          <Button style={{
                            borderLeft: 0,
                            borderBottomLeftRadius: 0,
                            borderTopLeftRadius: 0,
                            width: 20
                          }}
                            onClick={() => {
                              this.lastMonth(nowDateTime)
                            }}
                          >
                            <Icon type="right" style={{ marginLeft: -7 }} />
                          </Button>
                        </div>
                      </div>
                    </div>
                  }}
                  dateCellRender={
                    value => {
                      const eachDate = moment(value).format('YYYY-MM-DD')
                      const nowFlag = moment().format('YYYY-MM-DD')
                      const selectDate = moment(nowDateTime).format('YYYY-MM-DD')
                      const count = this.checkAppointmentTotal(eachDate)
                      if (eachDate === nowFlag && nowFlag !== selectDate) {
                        // 显示规则：今日
                        return <div className="aaa">
                          <div className="bbb">
                            <span>今日</span>
                          </div>
                          <p style={{
                            color: eachDate === selectDate ? "white" : "rgba(250,140,23,1)",
                            marginTop: 24,
                            fontSize: "8px",
                            whiteSpace: "nowrap",
                            display: count > 0 ? "" : "none"
                          }}>{`已约${count}人`}</p>
                        </div>
                      } else if (count > 0) {
                        // 显示规则：预约人数大于0
                        return <p style={{
                          color: eachDate === selectDate ? "white" : "rgba(250,140,23,1)",
                          marginBottom: 16,
                          fontSize: "8px"
                        }}>
                          {eachDate >= nowFlag && `已约${count}人`}
                        </p> // 日历大于等于今日才显示预约人数
                      }
                    }
                  }
                />
              </Card>
              <Card bordered={true} size='small'
                title={<p style={{ color: "#1890ff", margin: 0, fontWeight: "bold" }}>预约时段</p>}
                extra={<Button size='small' type="primary" ghost onClick={this.appointmentVisitAdd}>确定预约</Button>}
                bodyStyle={{ padding: "3.5px 12px" }}
              >
                <Row>
                  {/*预约时段*/}
                  {
                    this.state.appointTime.map(item => {
                      return <Col span={6} key={item.id}>
                        <div key={item.id}
                          style={{ width: 140 }}
                          onClick={() => {
                            this.selectAppointmentTime(item)
                          }}
                          onDoubleClick={() => {
                            this.selectAndAppointment(item)
                          }}
                        >
                          <div className="eeeeee"
                            style={{
                              borderColor: this.cardColorCase(item) && '#40a9ff',
                              boxShadow: this.cardColorCase(item) && "0px 2px 6px 0px rgb(99, 172, 245)",
                            }}
                          >
                            <div className="cccccc"
                              style={{ borderColor: this.colorSelect(item.id) }}>{item.descripts}</div>
                            <div className="dddddd">{item.startTime + '-' + item.endTime}</div>
                          </div>
                        </div>
                      </Col>
                    })
                  }
                </Row>
              </Card>

            </Col>
            <Col span={13}>
              <Card
                title={(
                  <div>
                    <Icon type="minus-square" theme="twoTone" style={{ marginRight: 5 }} />
                    预约列表
                  </div>
                )}
                bordered={true}
                size='small'
                bodyStyle={{ height: 553, padding: "10px 12px" }}
                className="table-body-height"
              >
                <PubilcTablePagination
                  param={{
                    page,
                    total,
                    loading,
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    y: 454,
                    componentName: 'AppointmentVisitList',
                    height: '504px',
                    columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                  }}
                  compilePage={this.compilePage}
                  getColumns={this.getTableColumns}
                  onRef={ref => this.commonTableRef = ref}
                />
              </Card>
            </Col>
          </Row>
        </div>
      )
    }
  })
export default AppointmentVisit
