/*
 * Creator:     WRX
 * CreatDate:   2022-08-25
 * descripts：  预约复诊记录管理
 * */
import React, { Component } from 'react';
import { Button, Card, Divider, Icon, Select, Tag, message, Modal, Radio } from 'antd';
import RangeDatePicker from 'components/rangePicker/index';
import PubilcTablePagination from "../common/PubilcTablePagination";
import store from 'store';
import { $http } from "../../containers/config/https";
import moment from "moment";
import AppointmentRecordHandle from './AppointmentRecordHandle.jsx'
import GetPatientInformation from "./component/GetPatientInformation";

const Option = Select.Option;

class AppointmentRecordManagement extends Component {
  constructor(props) {
    super(props);
    this.userData = React.$getSessionData();
    this.state = {
      readMode: 'R',
      noTitleKey: 'N',
      tableData: [],// 预约列表查询数据
      columns: [],// 预约列表查询表头信息
      loading: false,
      totalWidth: '100%', // 表头总宽度
      detailSelectedRowKeys: [],
      startDate: moment(),
      endDate: moment(),
      page: 1,
      pageSize: 20,
      total: 0,// 预约人数
      patID: '', // 病人Id
      defaultCardType: '', // 默认卡类型
      cardType: undefined, // 卡类型,
      cardNo: undefined, // 卡号,
      patNo: undefined, // 病人
      visible: false, // 表头编辑弹框控制属性
      visibleModal: false, // 其他弹框控制属性
      patInfo: {}, // table行数据存储
      modalKey: '',// 其他弹框的key用于控制弹窗销毁
      totalN: 0,   // 待处理统计
      totalY: 0,   // 已处理统计
      totalA: 0,    // 全部统计
      glassesAppointIDs: [], // table复选框数组
      optometryDoctor: [],// 验光师列表
      rowID: '',// 行ID
      totalWidthN: '100%'
    }
  }

  componentDidMount() {
    this.getDefaultData();
    this.basicDataInitial();
    this.getRecordListColumns();
    this.statusTotalCount();
  }

  // Tabs 切换回调
  onTabChange = (key, type) => {
    // console.log('key',key)
    if (key === 'N') {
      this.getRecordListColumns()
    } else if (key === 'Y') {
      this.getProcessingRecordColumns()
    } else if (key === '') {
      this.getProcessingRecordColumns()
    }

    this.setState({
      [type]: key,
      detailSelectedRowKeys: [],
      glassesAppointIDs: []
    }, () => {
      // 查数据
      this.appointmentListQuery(key)
      // 统计数量
    });
  };

  // +----------------接口相关---------------+

  // 获取列表头数据 -- 01040073 -- AppointmentRecordList
  getRecordListColumns = async () => {
    let operationObj = {
      width: 170,
      title: '操作',
      fixed: 'right',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <div>
          <a onClick={() => {
            this.showModal(record)
          }}>{record.statusID !== '1' ? '重新处理' : '处理预约'}</a>
          <Divider type="vertical" />
          <a onClick={() => {
          }}>就诊历史</a>
        </div>
      ),
    };
    try {
      let data = {
        params: [{
          compontName: 'AppointmentRecordList',
          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 = []
        if (filterArr && filterArr.length > 0) {
          filterArr.map(item => {
            if (item.dataIndex === 'statusDesc') {
              const statusColumns = {
                title: '状态',
                width: 100,
                dataIndex: 'statusDesc',
                key: 'statusDesc',
                align: 'center',
                render: (text, record) => (
                  <Tag color={this.choiceTagColor(record.statusID)}>{record.statusDesc}</Tag>
                ),
              }
              columns.push(statusColumns)
            } else {
              columns.push(item)
            }
          })
        }
        columns = columns && columns.length > 0 ? [...columns, operationObj] : []
        this.setState({
          columns: columns,
          totalWidthN: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取列表头数据 -- 01040073 -- AppointmentProcessingRecord
  getProcessingRecordColumns = async () => {
    let operationObj = {
      width: 170,
      title: '操作',
      fixed: 'right',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <div>
          <Button type="link" style={{ padding: 0, fontWeight: 'bold' }} onClick={() => { this.showModal(record) }}>{record.statusID !== '1' ? '重新处理' : '处理预约'}</Button>
          <Divider type="vertical" />
          <a onClick={() => {
          }}>就诊历史</a>
        </div>
      ),
    };
    try {
      let data = {
        params: [{
          compontName: 'AppointmentProcessingRecord',
          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 = []
        if (filterArr && filterArr.length > 0) {
          filterArr.map(item => {
            if (item.dataIndex === 'statusDesc') {
              const statusColumns = {
                title: '状态',
                width: 100,
                dataIndex: 'statusDesc',
                key: 'statusDesc',
                align: 'center',
                render: (text, record) => (
                  <Tag color={this.choiceTagColor(record.statusID)}>{record.statusDesc}</Tag>
                ),
              }
              columns.push(statusColumns)
            } else {
              columns.push(item)
            }
          })
        }
        columns = columns && columns.length > 0 ? [...columns, operationObj] : []
        this.setState({
          columns: columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 预约分页查询列表 -- 17030003
  appointmentListQuery = (processing, isTips) => {
    // console.log('processing',processing)
    const startDate = this.state.startDate
    const endDate = this.state.endDate
    //console.log('startDate2',startDate,'endDate2',endDate)
    const { optometryDoctorID } = this.state
    const userID = this.userData.userID
    let patID = this.patientRef && this.patientRef.getPatientID();
    let data = {
      params: [
        {
          startDate: startDate,  //查询开始日期
          endDate: endDate,    //查询结束日期
          keywords: patID,   //关键词
          doctorID: optometryDoctorID === '' ? userID : optometryDoctorID,   //预约医生ID
          //statusID: e === '5' ? '' : e,  //预约状态ID 1待处理  2已处理 3延后 4取消
          patNo: patID,
          processing
        }
      ],
      pagination: [
        {
          pageSize: this.state.pageSize,   //页面大小
          currentPage: this.state.page, //当前页
        }
      ]
    };
    $http.post('urlS', this, {
      code: '17030003',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result.rows;
          this.statusTotalCount()
          if (tableData && tableData.length > 0) {
            this.setState({ tableData: res.result.rows, total: res.result.total })
          } else {
            this.setState({
              tableData: [],
              total: 0
            })
            isTips === 'N' ? '' : message.error('未查询到数据');
          }
        }
      }
    })
  };

  // 预约状态统计 -- 17030003
  statusTotalCount = () => {
    const { optometryDoctorID } = this.state
    const userID = this.userData.userID
    let patID = this.patientRef && this.patientRef.getPatientID();
    let data = {
      params: [
        {
          startDate: this.state.startDate,  //查询开始日期
          endDate: this.state.endDate,    //查询结束日期
          keywords: patID,   //关键词
          doctorID: optometryDoctorID === '' ? userID : optometryDoctorID,   //预约医生ID
          statusID: '',  //预约状态ID 1待处理  2已处理 3延后 4取消
          patNo: patID
        }
      ],
      pagination: [
        {
          pageSize: this.state.pageSize,   //页面大小
          currentPage: this.state.page, //当前页
        }
      ]
    };
    $http.post('urlS', this, {
      code: '17030003',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let totalN = 0
          let totalY = 0
          let totalA = 0
          let tableData = []
          tableData = res.result.rows
          tableData.map(item => {
            totalA = totalA + 1
            if (item.statusID === '1' || item.statusID === '3') {
              totalN = totalN + 1
            } else {
              totalY = totalY + 1
            }
          })
          this.setState({ totalN, totalY, totalA })
        }
      }
    })

  };

  // 预约复诊界面初始化查询接口 -- 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,
            startDate: moment(res.result.params.startDate),
            endDate: moment(res.result.params.endDate)
          }, () => { this.appointmentListQuery('N', 'N') })
        }
      }
    })
  };

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

  // +---------------------Table 操作相关 ------------------------------+
  // 获取初始化数据
  getDefaultData = async () => {
    try {
      var data = {
        params: [{}]
      }
      let res = await React.$asyncPost(this, '17020002', data);
      let defaultValue = '';
      let cardSelectData = res.result?.cardType || [];
      for (var i = 0; i < cardSelectData.length; i++) {
        if (cardSelectData[i].defaultFlag === 'Y') {
          defaultValue = cardSelectData[i].id;
        }
      }
      this.setState({
        cardSelectData,
        cardType: defaultValue
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.appointmentListQuery(this.state.noTitleKey)
    })
  }

  // table复选项
  handleDetailSelectedRowKeysChange = (selectedRowKeys, selectedRows) => {
    let objArr = []
    let statusArr = []
    objArr = selectedRows
    objArr.map(item => {
      statusArr.push(item.glassesAppointID)
    })
    this.setState({
      detailSelectedRowKeys: selectedRowKeys,
      glassesAppointIDs: statusArr
    })
  }

  // 行类名
  setRowClassNamePublic = (record) => {
    let rowStyle = ''
    let rowIdArr = []
    rowIdArr = this.state.glassesAppointIDs
    rowIdArr.map(item => {
      if (item === record.glassesAppointID) {
        rowStyle = 'clickRowStyle'
      }
    })
    return rowStyle
  }

  // 开始时间更换
  startDateChange = (e) => {
    this.setState({ startDate: moment(e) }, () => {
      this.appointmentListQuery(this.state.noTitleKey)
    })
  }

  // 结束时间更换
  endDateChange = (e) => {
    this.setState({ endDate: moment(e) }, () => {
      this.appointmentListQuery(this.state.noTitleKey)
    })
  }

  //Tag组件颜色区分
  choiceTagColor = (e) => {
    // 根据预约处理状态的ID来返回颜色
    // 1待处理  2已处理 3延后 4取消
    if (e === '1' || e === '3') {
      return 'orange'
    } else {
      return 'green'
    }
  }

  // +--------------------处理预约弹窗相关--------------------+
  showModal = (patInfo) => {
    const modalKey = patInfo && 'glassesAppointID' in patInfo ? patInfo.glassesAppointID : ''
    const appointDate = patInfo && 'appointDate' in patInfo ? patInfo.appointDate : ''
    const today = moment().format('YYYY-MM-DD')
    if (appointDate !== '' && appointDate < today) {
      this.appointmentCheckProcessing(patInfo)
    } else {
      this.setState({
        visibleModal: true,
        patInfo,
        modalKey
      });
    }
  };

  handleOk = () => {
    this.appointmentListQuery(this.state.noTitleKey)
    this.statusTotalCount()
    this.setState({
      visibleModal: false,
    });
  };

  handleCancel = () => {
    this.setState({
      visibleModal: false,
    });
  };

  handleQuery = (isTips) => {
    this.setState({ page: 1 }, () => {
      this.appointmentListQuery(this.state.noTitleKey, isTips)
    })
  }

  // 批量处理
  batchProcessing = () => {
    this.showModal();
  }

  render() {
    const {
      total, tableData, columns, totalWidth, page, loading, detailSelectedRowKeys, cardType, totalWidthN,
      cardSelectData, glassesAppointIDs, patInfo, modalKey, startDate, endDate
    } = this.state;

    const tabListNoTitle = [
      {
        key: 'N',
        tab: `待处理(${this.state.totalN})`,
      },
      {
        key: 'Y',
        tab: `已处理(${this.state.totalY})`,
      },
      {
        key: '',
        tab: `全部(${this.state.totalA})`,
      },
    ];
    const detailRowSelection = {
      selectedRowKeys: detailSelectedRowKeys,
      onChange: this.handleDetailSelectedRowKeysChange
    };

    return (
      <div className="glasses-order-dom">
        <div
          style={{ lineHeight: 'inherit' }}
          className="gmaf-header common-query-header flex-align-items"
        >
          <div style={{ marginRight: 15, display: 'inline-block' }}>
            <RangeDatePicker
              width="300px"
              label="预约日期："
              isChange={true}
              format='YYYY-MM-DD'
              className='express-select-border'
              startDate={startDate}
              endDate={endDate}
              startChange={this.startDateChange}
              endChange={this.endDateChange}
            />
          </div>
          <GetPatientInformation
            parLabelClass="common-input-label"
            cardType={cardType}
            cardSelectData={cardSelectData}
            onRef={ref => this.patientRef = ref}
            handleQuery={this.handleQuery}
          />
          <span className="common-input-label">预约验配师：</span>
          <Select style={{ width: 180, marginRight: 15 }}
            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>
          <Button type='primary' onClick={() => {
            this.appointmentListQuery(this.state.noTitleKey)
          }}>查询</Button>
        </div>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <Card
          bordered={false}
          size="small"
          className="table-body-height"
          activeTabKey={this.state.noTitleKey}
          tabList={tabListNoTitle}
          onTabChange={key => {
            this.onTabChange(key, 'noTitleKey');
          }}
        >
          {
            this.state.noTitleKey === 'N' &&
            <div>
              <div style={{ marginBottom: 10, lineHeight: '32px' }}>
                <span className="span flex-align-items" style={{ color: '#333', fontWeight: 'normal' }} onClick={this.batchProcessing}>
                  <Icon type="reconciliation" style={{ color: "rgb(213, 0, 249)", marginRight: 4, fontSize: '18px' }} />
                  批量处理
                </span>
              </div>
              <PubilcTablePagination
                param={{
                  page,
                  total,
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidthN, // 表格的宽度
                  y: store.getState().tableHeight.y - 50,
                  componentName: 'AppointmentRecordList', // 待处理表头
                  height: store.getState().tableHeight.y,
                  columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                }}
                compilePage={this.compilePage}
                getColumns={this.getRecordListColumns}
                onRef={ref => this.commonTableRef = ref}
                rowSelectionPublic={detailRowSelection}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          }
          {
            this.state.noTitleKey === 'Y' &&
            <div>
              <div style={{ marginBottom: 10, lineHeight: '32px' }}>
                <span className="span flex-align-items" style={{ color: '#333', fontWeight: 'normal' }} onClick={this.batchProcessing}>
                  <Icon type="reconciliation" style={{ color: "rgb(213, 0, 249)", marginRight: 4, fontSize: '18px' }} />
                  批量处理
                </span>
              </div>
              <PubilcTablePagination
                param={{
                  page,
                  total,
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y - 50,
                  componentName: 'AppointmentProcessingRecord', // 已处理表头
                  height: store.getState().tableHeight.y,
                  columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                }}
                compilePage={this.compilePage}
                getColumns={this.getProcessingRecordColumns}
                onRef={ref => this.commonTableRef = ref}
                rowSelectionPublic={detailRowSelection}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          }
          {
            this.state.noTitleKey === '' &&
            <div>
              <div className="flex-between-center" style={{ marginBottom: 10 }}>
                <span className="span flex-align-items" style={{ color: '#333', fontWeight: 'normal' }} onClick={this.batchProcessing}>
                  <Icon type="reconciliation" style={{ color: "rgb(213, 0, 249)", marginRight: 4, fontSize: '18px' }} />
                  批量处理
                </span>
                <Radio.Group
                  defaultValue=""
                  buttonStyle="solid"
                  onChange={(e) => {
                    this.appointmentListQuery(e.target.value)
                  }}
                >
                  <Radio.Button key="1" value="N">待处理</Radio.Button>
                  <Radio.Button key="2" value="Y">已处理</Radio.Button>
                  <Radio.Button key="3" value="">全部</Radio.Button>
                </Radio.Group>
              </div>
              <PubilcTablePagination
                param={{
                  page,
                  total,
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y - 50,
                  componentName: 'AppointmentProcessingRecord',
                  height: store.getState().tableHeight.y,
                  columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                }}
                compilePage={this.compilePage}
                getColumns={this.getProcessingRecordColumns}
                onRef={ref => this.commonTableRef = ref}
                rowSelectionPublic={detailRowSelection}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          }
        </Card>
        <Modal
          key={modalKey}
          title="请选择处理方式"
          visible={this.state.visibleModal}
          onCancel={this.handleCancel}
          footer={false}
          width="60%"
          bodyStyle={{ padding: 0 }}
          destroyOnClose
        >
          <AppointmentRecordHandle
            appointArr={glassesAppointIDs}
            patInfo={patInfo}
            handleThis={this}
          />
        </Modal>
      </div>
    );
  }
};

export default AppointmentRecordManagement;