/*
 * Create:      柿子
 * CreateDate:  2023/09/19
 * Describe：   列表数据排序/列表数据顺序调整
 * */
import React, { Component } from 'react';
import { Modal, Button, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination';

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

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

  // 修改弹窗状态 - params包含 -> title, tableData, columns, totalWidth, saveCode, deleteCode, idIndex, recordIdIndex, interfaceParams
  modifyVisible = (visible, params) => {
    if (visible) { // 打开弹窗时
      this.setState({ ...params, tableData: Util.addKeyValueToDataSource(params?.tableData || [], '', 0) });
    }
    this.setState({ visible, selectedRowKeys: [] });
  }

  //上移
  handleUp = () => {
    var keys = this.state.selectedRowKeys;
    var data = this.state.tableData;
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1;
      else if (m > n) return 1;
      else return 0;
    });
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] === 0) {
        newKeys.push(keys[i]);
        continue;
      }
      var curRowData = data[keys[i]];
      var curRowKey = curRowData.key;
      var upRowData = data[keys[i] - 1];
      var upRowKey = upRowData.key;
      upRowData.key = curRowKey;
      curRowData.key = upRowKey;
      data[keys[i]] = upRowData;
      data[keys[i] - 1] = curRowData;
      newKeys.push(keys[i] - 1);
    }
    this.setState({
      tableData: data,
      selectedRowKeys: newKeys
    })
  }

  //下移
  handleDown = () => {
    var keys = this.state.selectedRowKeys;
    var data = this.state.tableData;
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1;
      else if (m > n) return 1;
      else return 0;
    });
    for (var i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length - 1) {
        newKeys.push(keys[i])
        continue;
      }
      var curRowData = data[keys[i]];
      var upRowData = data[keys[i] + 1];
      var curRowKey = curRowData.key;
      var upRowKey = upRowData.key;
      upRowData.key = curRowKey;
      curRowData.key = upRowKey;
      data[keys[i]] = upRowData;
      data[keys[i] + 1] = curRowData;
      newKeys.push(keys[i] + 1);
    }
    this.setState({
      tableData: data,
      selectedRowKeys: newKeys
    })
  }

  // 保存
  handleSave = async (saveType) => {
    try {
      const { saveCode, interfaceParams, idIndex, recordIdIndex, tableData } = this.state;
      let listData = tableData && tableData.map((item, index) => {
        return {
          [idIndex || 'id']: item[recordIdIndex || 'id'],
          seqNo: saveType === 'delete' ? '' : (item?.key || index) + 1, // 删除时不传序号
        }
      })
      let data = {
        params: [{
          ...interfaceParams, // 保存其他入参，界面自己定义
          listData,
        }]
      }
      let res = await React.$asyncPost(this, saveCode, data);
      message.success(res?.errorMessage || (saveType === 'delete' ? '删除成功' : '保存成功'));
      this.modifyVisible(false);
      this.setState({ selectedRowKeys: [] });
      this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
    }
  }

  // 删除当前配置
  handleDelete = async () => {
    try {
      const { deleteCode, interfaceParams } = this.state;
      if (deleteCode) {
        let data = {
          params: [{
            ...interfaceParams
          }]
        }
        let res = await React.$asyncPost(this, deleteCode, data);
        message.success(res.errorMessage || '删除成功');
        this.props.handleQuery && this.props.handleQuery();
      } else {
        this.handleSave('delete');
      }
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    const { visible, columns, totalWidth, tableData, loading, selectedRowKeys, modalTitle, modalWidth } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys })
      },
    };
    return (
      <Modal
        footer={null}
        destroyOnClose
        visible={visible}
        width={modalWidth || '1000px'}
        title={modalTitle || '列表数据排序'}
        className="table-body-height"
        onCancel={() => this.modifyVisible(false)}
      >
        <div style={{ marginBottom: 12 }}>
          <Button style={{ marginRight: '15px' }} ghost type="primary" onClick={this.handleUp}>向上移动</Button>
          <Button ghost type="primary" onClick={this.handleDown}>向下移动</Button>
          <Button style={{ margin: '0 15px' }} type="primary" onClick={this.handleSave}>保存</Button>
          <Popconfirm title="删除后不可恢复，确定要删除吗?" onConfirm={this.handleDelete}>
            <Button type="danger">删除当前配置</Button>
          </Popconfirm>
        </div>
        <PublicTablePagination
          param={{
            loading,
            columns, // 表头配置
            y: store.getState().tableHeight.y - 200,
            height: store.getState().tableHeight.y - 150 + 'px',
            x: totalWidth, // 表格的宽度
            data: tableData, // 表格数据
          }}
          rowSelectionPublic={rowSelection}
        />
      </Modal>
    )
  }
};

export default PublicDataOrderAdjustment;