/*
 * Create:      柿子
 * CreateDate:  2022/11/01
 * Describe：   文字医嘱弹窗
 * */
import React, { Component } from 'react';
import { Modal, Radio, Switch, Popconfirm, Divider, Input, Checkbox, Button, message } from 'antd';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import './style/index.less';

class WrittenOrdersModal extends Component {
  constructor(props) {
    super(props);
    let patientData = React.$getSessionData('patientData');
    this.state = {
      patientData,
      visible: false,
      inputDesc: undefined,
      selfFlag: 'N',
      queryType: 'last',
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      rowID: '',
      saveFlag: false, // 是否保存到个人常用
    };
    this.staticColumns = [{
      key: 1,
      title: '内容',
      dataIndex: 'content',
      align: 'center',
      width: 300
    }, {
      key: 2,
      title: '级别',
      dataIndex: 'levelDesc',
      align: 'center',
      width: 100
    }, {
      key: 3,
      title: '创建人',
      dataIndex: 'creatUserDesc',
      align: 'center',
      width: 100
    }, {
      key: 4,
      title: '使用次数',
      dataIndex: 'useCount',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '上次使用时间',
      dataIndex: 'lastUseDateTime',
      align: 'center',
      width: 150
    }]
  }

  componentDidMount() {
    let saveFlag = React.$getSessionData('writtenOrdersModalSaveFlag', false);
    this.setState({ saveFlag: saveFlag === 'Y' ? true : false });
    this.props.onRef && this.props.onRef(this);
  }

  // 修改弹窗状态
  modifyVisible = (visible, desc) => {
    const { columns, inputDesc } = this.state;
    if (!(columns && columns.length > 0) && visible) {
      this.getTableColumns();
    }
    if (desc !== inputDesc && visible) {
      this.setState({ inputDesc: desc }, () => {
        this.handleQuery();
      })
    }
    this.setState({ visible }, () => {
      if (!this.state.visible) {
        this.props.onCancel && this.props.onCancel();
      }
    });
  }

  // 仅显示本人
  handleSelfFlagChange = e => {
    this.setState({ selfFlag: e ? 'Y' : 'N' }, () => {
      this.handleQuery();
    });
  }

  // 使用次数最多 / 最近使用
  handleQueryTypeChange = e => {
    this.setState({ queryType: e.target.value }, () => {
      this.handleQuery();
    });
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          type: 'C',
          compontName: 'WrittenOrdersModal',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        });
      }
    } catch (error) {
      console.log(error);
    }
  }

  handleQuery = Util.debounce((desc) => {
    if (desc !== undefined) {
      this.setState({ inputDesc: desc });
    }
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  })

  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      let { selfFlag, queryType, inputDesc, pageSize, page } = this.state;
      this.setState({ loading: true })
      let data = {
        params: [{
          selfFlag,
          queryType,
          inputDesc
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '03020070', data);
      let tableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []));
      let rowID = '';
      if (tableData && tableData.length > 0) {
        rowID = tableData[0].writtenOrderID;
      }
      this.setState({ tableData, total: res.result?.total || tableData.length, loading: false, rowID });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false });
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.writtenOrderID))) {
          this.setState({ rowID: record.writtenOrderID });
        } else {
          this.setState({ rowID: '' });
        }
      },
      onDoubleClick: () => {
        this.handleOK(record)
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.writtenOrderID === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 删除
  handleDelete = async (record) => {
    try {
      let data = {
        params: [{
          writtenOrderID: record?.writtenOrderID
        }]
      }
      let res = await React.$asyncPost(this, '03020073', data);
      message.success(res?.errorMessage || '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 保存到个人
  handleSaveToPerson = async (record) => {
    try {
      let data = {
        params: [{
          content: record?.content
        }]
      }
      let res = await React.$asyncPost(this, '03020071', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 确认
  handleOK = async (record) => {
    try {
      const { ordPriorityID } = this.props;
      const { patientData, rowID, saveFlag, customContent } = this.state;
      let recordID = record && 'writtenOrderID' in record && record.writtenOrderID ? record.writtenOrderID : '';
      let data = {
        params: [{
          admID: patientData?.admID || '',
          customContent: recordID ? '' : customContent,
          saveFlag: saveFlag ? 'Y' : 'N', // Y 保存到个人，配合customContent字段使用
          writtenOrderID: recordID || rowID,
          ordPriorityID: ordPriorityID,
        }]
      }
      let res = await React.$asyncPost(this, '03020072', data);
      this.setState({ customContent: undefined });
      this.props.confirmSelection && this.props.confirmSelection(res);
      this.modifyVisible(false);
    } catch (error) {
      console.log(error);
    }
  }

  // 个人常用设置
  handleSaveFlagChange = e => {
    this.setState({ saveFlag: e.target.checked }, () => {
      React.$setSessionData('writtenOrdersModalSaveFlag', this.state.saveFlag ? 'Y' : 'N', false);
    });
  }

  // 上下移动
  handleWrittenOrderMove = (keyCode) => {
    const { tableData } = this.state;
    let rowID = '';
    for (let i = 0; i < tableData.length; i++) {
      let index = i;
      if (tableData[index].writtenOrderID === this.state.rowID) {
        if (keyCode === 38) { // 上移
          if (index > 0) {
            rowID = tableData[index - 1].writtenOrderID;
          } else {
            message.warning('已经到顶了，不能再向上移了哦');
          }
          break;
        } else if (keyCode === 40) {
          if (index < (tableData.length - 1)) {
            rowID = tableData[index + 1].writtenOrderID;
          } else {
            message.warning('已经到底了，不能再向下移了哦');
          }
          break;
        }
      }
    }
    rowID && this.setState({ rowID });
  }

  render() {
    const { visible, selfFlag, queryType, page, total, saveFlag, loading, tableData, totalWidth, columns, customContent } = this.state;
    const { param } = this.props;

    // 列表操作
    const operationObj = {
      width: 130,
      title: '操作',
      align: 'center',
      key: 'operation',
      // fixed: 'right',
      render: (text, record) => (
        <span>
          {record.deleteFlag === 'Y' ? (
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
              <span className="span common-record-delete-span">删除</span>
            </Popconfirm>
          ) : (
            <span style={{ color: '#999', cursor: 'no-drop', fontWeight: 'normal' }}>删除</span>
          )}
          <Divider type="vertical" />
          {record.levelDesc !== '个人' ? (
            <span className="span" onClick={() => this.handleSaveToPerson(record)}>保存到个人</span>
          ) : (
            <span style={{ color: '#999', cursor: 'no-drop', fontWeight: 'normal' }}>保存到个人</span>
          )}
        </span>
      ),
    };
    return (
      <Modal
        title=""
        width="1000px"
        footer={null}
        mask={false}
        closable={false}
        visible={visible}
        onCancel={() => this.modifyVisible(false)}
        style={{ position: 'absolute', top: param.top ? (parseInt(param.top) - 90 + 'px') : '40%', left: param.left ? param.left : '40%', paddingBottom: 0 }}
        className="written-orders-modal"
        wrapClassName="dasp-common-table-modal"
      >
        <div className="table-body-height">
          <div className="flex-between-center" style={{ marginBottom: '10px' }}>
            <Radio.Group value={queryType} onChange={this.handleQueryTypeChange} >
              <Radio.Button value="count">使用次数最多</Radio.Button>
              <Radio.Button value="last">最近使用</Radio.Button>
            </Radio.Group>
            <div className="flex-align-items">
              <Switch
                style={{ marginRight: '4px' }}
                checked={selfFlag == 'Y' ? true : false}
                onChange={this.handleSelfFlagChange}
              />
              仅显示本人
            </div>
          </div>
          <PubilcTablePagination
            param={{
              page,
              total,
              loading,
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: 220,
              height: '270px',
              componentName: 'WrittenOrdersModal',
              columns: columns && columns.length > 0 ? [...columns, operationObj] : [...this.staticColumns, operationObj], // 表头配置
            }}
            compilePage={this.compilePage}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
          <Divider dashed orientation="left" className="wom-footer-divider">推荐/自定义内容</Divider>
          <div className="flex-between-center" style={{ paddingRight: '12px' }}>
            <div className="flex-align-items" style={{ width: '80%' }}>
              <Input
                allowClear
                style={{ width: '70%', marginRight: '12px' }}
                placeholder="录入自定义文字医嘱内容确定"
                value={customContent}
                onChange={e => this.setState({ customContent: e.target.value })}
              />
              <Checkbox checked={saveFlag} onChange={this.handleSaveFlagChange}>个人常用</Checkbox>
            </div>
            <Button type="primary" onClick={this.handleOK}>确定</Button>
          </div>
        </div>
      </Modal>
    )
  }
};

export default WrittenOrdersModal;