/*
 * Creator:     WRX
 * CreatDate:   2022-09-01
 * descripts：  视光预约群发记录
 * */

import React, {Component} from 'react';
import {Button, Card, Select, message} 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 GetPatientInformation from "./component/GetPatientInformation";

const Option = Select.Option;

class AppointmentMassRecord extends Component {
  constructor(props) {
    super(props);
    this.userData = React.$getSessionData();
    this.patData = React.$getSessionData('titleData');
    this.state = {
      readMode: 'R',
      noTitleKey: '1',
      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: {},
      totalN: 0,
      totalY: 0,
      totalA: 0,
      rowId: '',
      sendStatus: '',
      glassAppointStatusIDs: []
    }
  }

  componentDidMount() {
    this.getDefaultData();
    this.getTableColumns();
    this.massRecordListQuery();
  }

  handleQuery = () => {
    this.setState({page: 1}, () => {
      this.massRecordListQuery()
    })
  }

  // 状态下拉框
  selectStatus = (option) => {
    this.setState({sendStatus: option.props.status}, () => {
      this.massRecordListQuery()
    })
  }

  // +---------------------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)
    }
  }

  // 获取列表头数据 -- 01040073
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'AppointmentMassRecordList',
          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 === 'sendStatus') {
              const statusColumns = {
                title: '状态',
                dataIndex: 'sendStatus',
                key: 'sendStatus',
                align: 'center',
                render: (text, record) => (
                  <span style={{color: text === 'Y' ? 'rgb(153, 153, 153)' : 'red'}}>{record.sendStatusDesc}</span>
                ),
              }
              columns.push(statusColumns)
            } else {
              columns.push(item)
            }
          })
        }
        columns = columns && columns.length > 0 ? [...columns] : []
        this.setState({
          columns: columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

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

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

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

  // +-----------------时间切换相关-------------------+
  // 开始时间更换
  startDateChange = (e) => {
    this.setState({startDate: moment(e)}, () => {
      this.massRecordListQuery()
    })
  }

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

  // +-----------------相关接口---------------------+
  // 群发记录分页列表 -- 17030011
  massRecordListQuery = () => {
    let patID = this.patientRef && this.patientRef.getPatientID();
    let data = {
      params: [
        {
          startDate: this.state.startDate.format('YYYY-MM-DD'),  //查询开始日期
          endDate: this.state.endDate.format('YYYY-MM-DD'),    //查询结束日期
          keywords: patID,   //关键词
          sendStatus: this.state.sendStatus, //Y 发送成功  N  发送失败
          patNo: patID,
        }
      ],
      pagination: [
        {
          pageSize: this.state.pageSize,   //页面大小
          currentPage: this.state.page, //当前页
        }
      ]
    };
    $http.post('urlS', this, {
      code: '17030011',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({tableData: res.result.rows, total: res.result.total})
        }
      }
    })
  };

  // 重新发送短信 -- 17030012
  resendMassRecord = () => {
    let data = {
      params: [
        {
          glassAppointStatusIDs: this.state.glassAppointStatusIDs
        }
      ]
    };
    $http.post('urlS', this, {
      code: '17030012',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            detailSelectedRowKeys: [],
            glassAppointStatusIDs: []
          })
          this.massRecordListQuery()
          message.success(res.errorMessage)
        }
      }
    })
  }


  render() {
    const {total, tableData, columns, totalWidth, page, loading, detailSelectedRowKeys, cardType, cardSelectData, startDate, endDate} = this.state;
    const detailRowSelection = {
      selectedRowKeys: detailSelectedRowKeys,
      onChange: this.handleDetailSelectedRowKeysChange
    };

    return (
      <div style={{background: 'rgb(245,247,254)'}} className="glasses-mass-record">
        <Card bordered={false}>
          <div className="gmaf-header flex-wrap-align-items">
            <div style={{marginRight: 15}}>
              <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 cardType={cardType} cardSelectData={cardSelectData}
                                   onRef={ref => this.patientRef = ref} handleQuery={this.handleQuery}/>
            <div style={{marginRight: 15}}>
              状态：
              <Select
                allowClear
                showSearch
                placeholder='请选择'
                className="common-query-input"
                optionFilterProp="search"
                onChange={(value, option) => this.selectStatus(option)}
              >
                <Option key="1" status="" id="1">全部</Option>
                <Option key="2" status="Y" id="2">发送成功</Option>
                <Option key="3" status="N" id="3">发送失败</Option>
              </Select>
            </div>
            <div style={{marginRight: 15}}>
              <Button type='primary' onClick={() => {
                this.massRecordListQuery()
              }}>查询</Button>
            </div>
            <div style={{marginRight: 15}}>
              <Button type='primary' style={{backgroundColor: 'rgb(250, 140, 22)', borderColor: 'rgb(250, 140, 22)'}}
                      onClick={() => {
                        this.resendMassRecord()
                      }}>重新发送</Button>
            </div>
          </div>
        </Card>
        <Card bordered={false} style={{width: '100%', marginTop: 10}} bodyStyle={{paddingBottom: 10}}>
          <PubilcTablePagination
            param={{
              page,
              total,
              loading,
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: store.getState().tableHeight.y + 30,
              componentName: 'AppointmentMassRecordList',
              height: store.getState().tableHeight.y + 80,
              columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
            }}
            compilePage={this.compilePage}
            getColumns={this.getTableColumns}
            onRef={ref => this.commonTableRef = ref}
            onClickRowPublic={this.onClickRowPublic}
            rowSelectionPublic={detailRowSelection}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </Card>
      </div>
    );
  }
}

export default AppointmentMassRecord;