/*
 * Creater:     柿子
 * CreateDate:  2022/10/12
 * Describe：   表单数据维护
 * */
import React, { Component } from 'react';
import { Modal, Button, Input, Select, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import PublicTablePagination from 'pages/common/PubilcTablePagination';

class PublicFormDataMaintenance extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      columns: [],
      totalWidth: 600,
      tableData: [],
      loading: false,
      componentName: '',
      selectData: {},
      typeID: 'U',
      selectedRowKeys: []
    };
  }

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

  // 修改弹窗状态
  modifyVisible = (visible, componentName) => {
    const { selectData, columns } = this.state;
    if (visible && !(selectData && 'flag' in selectData && selectData.flag)) { // 获取下拉数据
      this.getSelectData();
    }
    if (visible && !(columns && columns.length > 0)) { // 获取下拉数据
      this.getColumnsData();
    }
    this.setState({ visible, componentName }, () => {
      this.state.visible ? this.getTableData() : '';
    })
  }

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '01040094');
      if (res.result && 'editFlag' in res.result && res.result.editFlag === 'Y') {
        this.setState({ selectData: { ...res.result, flag: true } });
      } else {
        this.setState({
          visible: false
        });
        message.warn('暂无编辑权限！');
      }
    } catch (error) {
      this.setState({ selectData: {} });
    }
  }

  // 获取表单数据
  getColumnsData = () => {
    let columns = [{
      key: 1,
      title: '代码',
      dataIndex: 'code',
      align: 'center',
      width: 100
    }, {
      key: 2,
      title: '描述',
      dataIndex: 'descripts',
      align: 'center',
      width: 100
    }, {
      key: 3,
      title: '占位',
      dataIndex: 'col',
      align: 'center',
      width: 100,
      render: (text, record, index) => {
        return (
          <Input
            type="number"
            className="input-number"
            style={{ width: '90%' }}
            value={record.col}
            onChange={(e) => this.handleTableInputChange(e.target.value, 'col', index)}
          />
        )
      }
    }, {
      key: 4,
      title: '跳转到',
      dataIndex: 'jumpID',
      align: 'center',
      width: 100,
      render: (text, record, index) => {
        let defaultSelectData = [];
        if (record && 'jumpID' in record && record.jumpID) {
          defaultSelectData.push({
            id: record?.jumpID,
            descripts: record?.jumpDesc,
          })
        }
        return (
          <Select
            showSearch
            placeholder="回车光定位到下一个"
            optionFilterProp="search"
            style={{ width: '90%' }}
            value={record.jumpID}
            onChange={(e) => this.handleTableInputChange(e, 'jumpID', index)}
            onFocus={() => this.getJumpSelectData(record, index)}
          >
            {React.$SelectOptions(record?.jumpSelectData || defaultSelectData)}
          </Select>
        )
      }
    }, {
      key: 5,
      title: 'labelCol',
      dataIndex: 'labelCol',
      align: 'center',
      width: 100,
      render: (text, record, index) => {
        return (
          <Input
            type="number"
            className="input-number"
            style={{ width: '90%' }}
            value={record.labelCol}
            onChange={(e) => this.handleTableInputChange(e.target.value, 'labelCol', index)}
          />
        )
      }
    }, {
      key: 6,
      title: 'wrapperCol',
      dataIndex: 'wrapperCol',
      align: 'center',
      width: 100,
      render: (text, record, index) => {
        return (
          <Input
            type="number"
            className="input-number"
            style={{ width: '90%' }}
            value={record.wrapperCol}
            onChange={(e) => this.handleTableInputChange(e.target.value, 'wrapperCol', index)}
          />
        )
      }
    }];
    this.setState({ columns });
  }

  // 获取跳转到下拉框数据
  getJumpSelectData = async (record, index) => {
    try {
      const { componentName } = this.state;
      if (!(record && 'jumpSelectData' in record && record.jumpSelectData.length > 1)) {
        let data = {
          params: [{
            fieldID: record?.id || '',
            componentName,
          }]
        }
        let res = await React.$asyncPost(this, '01040288', data);
        this.state.tableData[index]['jumpSelectData'] = res.result?.jumpID;
        this.setState({}, () => {
          this.getColumnsData();
        });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      const { componentName, typeID } = this.state;
      let data = {
        params: [{
          componentName,
          type: typeID
        }]
      }
      let res = await React.$asyncPost(this, '01040286', data);
      let tableData = res && res.result ? Util.addKeyValueToDataSource(res.result, '', 0) : [];
      this.setState({ tableData })
    } catch (error) {
      this.setState({ tableData: [] })
    }
  }

  // 更改table输入域数据
  handleTableInputChange = (value, dataIndex, index) => {
    this.state.tableData[index][dataIndex] = value;
    this.setState({});
  }

  //上移
  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 () => {
    try {
      const { componentName, typeID, tableData } = this.state;
      let data = {
        params: [{
          componentName,
          type: typeID,
          formData: tableData
        }]
      }
      let res = await React.$asyncPost(this, '01040284', data);
      message.success(res.errorMessage || '保存成功');
      this.modifyVisible(false);
      this.setState({ selectedRowKeys: [] });
      this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
    }
  }

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

  render() {
    const { visible, columns, totalWidth, tableData, loading, selectData, typeID, selectedRowKeys, componentName } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys })
      },
    };
    return (
      <Modal
        footer={null}
        destroyOnClose
        visible={visible}
        width="1000px"
        title={'表单数据维护（' + componentName + '）'}
        className="table-body-height"
        onCancel={() => this.modifyVisible(false)}
      >
        <div style={{ marginBottom: 12 }}>
          <Select
            showSearch
            value={typeID}
            placeholder="请选择"
            optionFilterProp="search"
            className="common-query-input"
            onChange={Util.handleSelectChange.bind(this, 'typeID')}
          >
            {React.$SelectOptions(selectData?.authList || [], 'value')}
          </Select>
          <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: 400,
            height: '450px',
            x: totalWidth, // 表格的宽度
            data: tableData, // 表格数据
          }}
          rowSelectionPublic={rowSelection}
        />
      </Modal>
    )
  }
};

export default PublicFormDataMaintenance;