/*
 * Create:      柿子
 * CreateDate:  2024/01/10
 * Describe：   设置排序
 * */
import React, { Component } from 'react';
import { Modal, Button, message, Icon, Radio, Select, Input } from 'antd';
import PublicTablePagination from 'pages/common/PubilcTablePagination';

class CommonTableSetSorting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      rowData: {},
      totalWidth: 0,
      columns: [],
      tableData: [],
      loading: false,
    }
  };

  componentDidMount() {
    this.props && 'onRef' in this.props && this.props.onRef(this);
  };

  modifyVisible = (visible, rowData = {}) => {
    const { columns } = this.state;
    this.setState({ visible, rowData }, () => {
      if (visible) {
        !(columns && columns.length > 0) && this.getTableColumns();
        this.getTableData();
      }
    });
  };

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          type: 'C',
          compontName: 'CommonTableSetSorting',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          let dataIndex = item?.dataIndex || '';
          let linkService = item?.linkService || '';
          return {
            ...item,
            render: (text, record, index) => {
              if (item?.linkMethod === 'Input') {
                return (
                  <Input
                    allowClear
                    placeholder="请输入"
                    style={{ width: '96%' }}
                    value={record && dataIndex in record ? record[dataIndex] : undefined}
                    onChange={(e) => this.handleInputChange(index, e.target.value, item, record, e)}
                    onClick={(e) => React.$stopPropagation(e)}
                  />
                )
              } else if (item?.linkMethod === 'Select') {
                let selectAttr = { // 下拉框属性
                  allowClear: true,
                  showSearch: true,
                  style: { width: '96%' },
                  optionFilterProp: "search",
                  placeholder: '请选择',
                  value: record && dataIndex in record ? record[dataIndex] : undefined,
                  onChange: (e) => this.handleInputChange(index, e, item, record, e),
                  onClick: (e) => React.$stopPropagation(e)
                };
                let selectOption = linkService && rowData[linkService] && Array.isArray(rowData[linkService]) ? React.$SelectOptions(rowData[linkService]) : '';
                return (
                  <Select {...selectAttr}>
                    {selectOption}
                  </Select>
                )
              } else if (item?.linkMethod === 'radioButton') {
                return (
                  <Radio.Group size="small" value={record && dataIndex in record ? record[dataIndex] : undefined} onChange={(e) => this.handleInputChange(index, e.target.value, item, record, e)}>
                    <Radio.Button value="A">升序</Radio.Button>
                    <Radio.Button value="D">降序</Radio.Button>
                  </Radio.Group>
                )
              } else {
                return text;
              }
            },
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 修改入参
  handleInputChange = (index, val, item, record) => {
    let dataIndex = item?.dataIndex || '';
    // let inputType = item?.linkMethod || 'Input';
    record[dataIndex] = val;
    this.setState({}, () => {
      // inputType === 'Select' && this.handleOk('N');
    });
  }

  // 病区信息明细
  getTableData = async () => {
    try {
      this.setState({ loading: true });
      const { rowData } = this.state;
      let data = {
        params: [{
          compontName: rowData?.componentName || '',
        }]
      }
      let res = await React.$asyncPost(this, '01040317', data);
      let tableData = res?.result?.rows || [];
      for (let i = 0; i < tableData.length; i++) {
        tableData[i].key = i + 1;
        tableData[i].seqNo = i;
      }
      this.setState({ tableData, loading: false });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  getOperationObj = (dataIndex) => {
    // 列表操作
    const operationObj = {
      width: 100,
      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>
        <span
          style={{ marginLeft: '8px' }}
          className="span common-record-delete-span"
          onClick={(e) => this.handleRecordDelete(record, index, e)}
        >
          删除
        </span>
      </>
    )
  };

  // 上下移动
  handleMove = (record, direction, dataIndex, e) => {
    React.$stopPropagation(e);
    let tableData = this.state[dataIndex];
    const rowKey = record?.seqNo;
    const currentIndex = tableData.findIndex(item => item.seqNo === rowKey);
    if (direction === 'up' && currentIndex > 0) {
      [tableData[currentIndex - 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex - 1]];
      tableData[currentIndex].seqNo = currentIndex;
      tableData[currentIndex - 1].seqNo = currentIndex - 1;
    } else if (direction === 'down' && currentIndex < (tableData.length - 1)) {
      [tableData[currentIndex + 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex + 1]];
      tableData[currentIndex].seqNo = currentIndex;
      tableData[currentIndex + 1].seqNo = currentIndex + 1;
    }
    for (let i = 0; i < tableData.length; i++) {
      tableData[i].key = i + 1;
      tableData[i].priLevel = i + 1;
    }
    this.state[dataIndex] = tableData;
    this.setState({});
  };

  // 删除
  handleRecordDelete = (record, indexToRemove, e) => {
    React.$stopPropagation(e);
    let { tableData } = this.state;
    const newArray = tableData.filter((d, index) => index !== indexToRemove).map((item, index) => {
      return {
        ...item,
        priLevel: index + 1,
        seqNo: index,
        key: index + 1,
      }
    });
    this.setState({ tableData: newArray });
  };

  // 新增
  handleAdd = () => {
    let { tableData } = this.state;
    let key = tableData && tableData.length > 0 ? tableData.length + 1 : 1;
    tableData.push({
      seqNo: key - 1,
      key,
      priLevel: key,
      sortType: 'A', // A-顺序 D-倒序
    });
    this.setState({ tableData });
  };

  // 确认
  handleOk = async () => {
    try {
      const { rowData, tableData } = this.state;
      let codeRequireIndex = 0;
      for (let i = 0; i < tableData.length; i++) {
        if (!(tableData[i].code)) {
          codeRequireIndex = i + 1;
          break;
        }
      }
      if (codeRequireIndex) {
        message.error('排序内容不能为空！【第' + codeRequireIndex + '行】');
        return;
      }
      let data = {
        params: [{
          compontName: rowData?.componentName || '',
          sortData: tableData && tableData.map((item, index) => {
            return {
              ...item,
              priLevel: index + 1
            }
          })
        }]
      }
      let res = await React.$asyncPost(this, '01040318', data);
      message.success(res?.message || '保存成功');
      this.modifyVisible(false);
      this.props && this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    const { visible, tableData, totalWidth, columns, loading } = this.state;
    return (
      <Modal
        title="设置排序"
        width="46vw"
        visible={visible}
        bodyStyle={{ padding: '12px 24px' }}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="table-body-height">
          <div style={{ marginBottom: '12px' }}>
            <span className="span" onClick={this.handleAdd}>
              <Icon type="plus"></Icon>
              新增排序内容
            </span>
            <span style={{ fontWeight: 'normal', float: 'right', color: '#999', fontSize: '12px', marginTop: '6px' }}>注：系统最多支持三级排序</span>
          </div>
          <PublicTablePagination
            param={{
              y: 300,
              height: 350 + 'px',
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              loading: loading,
              componentName: 'CommonTableSetSorting',
              columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('tableData')] : [], // 表头配置
            }}
            getColumns={this.getTableColumns}
          />
        </div>
      </Modal>
    )
  }
};

export default CommonTableSetSorting;