/*
 * Create:      柿子
 * CreateDate:  2023/11/24
 * Describe：   查询条件设置
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, Checkbox, Switch, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import iconListVisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

class QueryConditionSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userData: React.$getSessionData(),
      queryParams: {
        alias: undefined, // 名称
        useFlag: true, // 仅显示生效
      },
      loading: false,
      columns: [],
      tableData: [],
      totalWidth: 0,
      rowID: '',
    };
  };

  componentDidMount() {
    this.getTableData();
    this.getTableColumns();
  };

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  };

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'NSQueryConditionSettings',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        for (let i = 0; i < columns.length; i++) {
          let colItem = columns[i];
          columns[i].render = (text, record, index) => this.handleRenderInput(text, record, index, colItem);
        }
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 请求列表数据
  getTableData = async (isClear) => {
    try {
      this.setState({ loading: true })
      let { queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag ? 'Y' : 'N',
          locID: this.props.locID || undefined, // 科室id
        }],
      }
      let res = await React.$asyncPost(this, this.props.locID ? '04011019' : '04011020', data);
      let tableData = Util.addKeyValueToDataSource(res?.result || [], '', 0);
      this.setState({ tableData, total: res.result?.total || tableData?.length || 0, loading: false }, () => {
        isClear !== 'N' && this.handleClear();
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'useFlag') {
        this.getTableData();
      }
    })
  };

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

  handleClear = () => {
    this.setState({ rowID: '' });
  };

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

  handleMove = (record, direction, dataIndex, e) => {
    React.$stopPropagation(e);
    let tableData = this.state[dataIndex];
    const rowKey = record?.key;
    const currentIndex = tableData.findIndex(item => item.key === rowKey);
    if (direction === 'up' && currentIndex > 0) {
      [tableData[currentIndex - 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex - 1]];
      // 更新key值
      tableData[currentIndex].key = currentIndex;
      tableData[currentIndex - 1].key = currentIndex - 1;
    } else if (direction === 'down' && currentIndex < (tableData.length - 1)) {
      [tableData[currentIndex + 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex + 1]];
      // 更新key值
      tableData[currentIndex].key = currentIndex;
      tableData[currentIndex + 1].key = currentIndex + 1;
    }
    this.state[dataIndex] = tableData;
    this.setState({}, () => {
      // dataIndex === 'tableData' && this.handleMoveSave();
    })
  };

  // 保存排序数据 - 去除，统一走保存
  handleMoveSave = async () => {
    try {
      const { tableData } = this.state;
      let sortArr = tableData && tableData.map(item => item.id);
      let data = {
        params: [{
          sortArr
        }]
      }
      let res = await React.$asyncPost(this, '04011021', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  };

  handleRenderInput = (text, record, index, colItem) => {
    let dataIndex = colItem?.dataIndex || '';
    if (colItem?.linkMethod === 'Switch') {
      return (
        <Switch
          checkedChildren="是"
          unCheckedChildren="否"
          checked={record[dataIndex] === 'Y' ? true : false}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e ? 'Y' : 'N')}
        />
      )
    } else if (colItem?.linkMethod === 'Checkbox') {
      return (
        <Checkbox
          checked={record[dataIndex] === 'Y' ? true : false}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e.target.checked ? 'Y' : 'N', e)}
        />
      )
    } if (colItem?.linkMethod === 'Input') {
      return (
        <Input
          allowClear
          style={{ width: '90%' }}
          placeholder="请输入"
          value={record[dataIndex] || undefined}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e.target.value, e)}
        />
      )
    } else {
      return text;
    }
  };

  handleInputChange = (index, dataIndex, val, e) => {
    React.$stopPropagation(e);
    this.state.tableData[index][dataIndex] = val;
    this.setState({});
  };

  getOperationObj = (dataIndex) => {
    // 列表操作
    const operationObj = {
      width: 80,
      key: 'operation',
      title: '操作',
      align: 'center',
      render: (text, record, index) => this.handleRenderMoveBtn(text, record, index, dataIndex)
    };
    return operationObj;
  };

  // 渲染移动按钮
  handleRenderMoveBtn = (text, record, index, dataIndex) => {
    let tableLen = this.state[dataIndex]?.length || 0;
    return (
      <>
        <Button
          type="link"
          size="small"
          disabled={index === 0}
          onClick={(e) => this.handleMove(record, 'up', dataIndex, e)}
        >
          上移
        </Button>
        <Button
          type="link"
          size="small"
          disabled={index >= tableLen - 1}
          onClick={(e) => this.handleMove(record, 'down', dataIndex, e)}
        >
          下移
        </Button>
      </>
    )
  };

  // 保存
  handleSave = async () => {
    try {
      const { tableData } = this.state;
      let data = {
        params: [{
          saveType: this.props.locID ? 'W' : 'C', // 保存类型【C:公共 W:病区】
          locID: this.props.locID || undefined, // 病区ID
          tableData,
        }]
      }
      let res = await React.$asyncPost(this, '04011022', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  };

  // 从本科移除
  handleDelete = async () => {
    try {
      let data = {
        params: [{
          locID: this.props.locID || undefined, // 病区ID
        }]
      }
      let res = await React.$asyncPost(this, '04011023', data);
      message.success(res?.errorMessage || '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  };

  render() {
    const { tabHeight } = this.props;
    const { queryParams, loading, columns, tableData, totalWidth } = this.state;

    return (
      <div className="ward-information-settings">
        <div
          style={{ paddingRight: '8px', position: 'relative', height: '100%' }}
        >
          <Card
            size="small"
            bordered={false}
            title={(
              <div className="card-title-left-img">
                <img src={iconListVisits} alt="" />
                查询条件设置
              </div>
            )}
            extra={(
              <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅显示生效</Checkbox>
            )}
          >
            <div className="table-body-height">
              <div style={{ marginBottom: 12 }}>
                <Row>
                  <Col span={18}>
                    <span className="common-input-label">描述：</span>
                    <Input
                      title="输入内容后可回车检索"
                      placeholder="输入描述/说明检索"
                      className="common-query-input"
                      style={{ width: '300px' }}
                      value={queryParams?.alias}
                      onChange={(e) => this.handleModifyInputValue(e.target.value, 'alias')}
                      onPressEnter={this.getTableData}
                    />
                    <Button type="primary" style={{ marginRight: 12 }} onClick={this.getTableData}>查询</Button>
                  </Col>
                  <Col span={6} style={{ textAlign: 'right' }}>
                    <Button style={{ marginRight: '12px' }} type="primary" onClick={this.handleSave}>保存</Button>
                    {this.props.locID && (
                      <Popconfirm
                        title="确认恢复默认设置吗?"
                        onConfirm={this.handleDelete}
                      >
                        <Button>恢复默认设置</Button>
                      </Popconfirm>
                    )}
                  </Col>
                </Row>
              </div>
              <PublicTablePagination
                param={{
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: tabHeight ? tabHeight : store.getState().tableHeight.y + 86,
                  height: tabHeight ? (tabHeight + 50 + 'px') : store.getState().tableHeight.y + 136 + 'px',
                  componentName: 'NSQueryConditionSettings',
                  columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('tableData')] : [], // 表头配置
                }}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          </Card>
        </div>
      </div>
    )
  }
};

export default QueryConditionSettings;