// 组件表列按钮维护 - 组件Form表单字段
import React, { Component } from 'react';
import { Button, message, Popconfirm, Input, Icon, Divider } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import ComponentDataSelectModal from './ComponentDataSelectModal';
import TableColumnAuthorization from './TableColumnAuthorization';
import 'pages/workstation/style/index.less';

class CDMComponentMaintenance extends Component {
  constructor() {
    super();
    this.state = {
      columns: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      tableWidth: 0,
      componentID: undefined, // 父组件行数据ID
      loading: false,
      btnType: '',
      formData: [],
      selectedRowKeys: [],
      selectedRows: [],
      activeKey: '',
      rowID: '',
      recordData: {},
      rowData: {}, // 新增编辑回显数据
    }
  }

  componentDidMount() {
    // this.getColumns();
    this.handleQuery();
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.activeKey !== prevState.activeKey) {
      return {
        activeKey: nextProps.activeKey
      }
    }
    if (nextProps.componentID !== prevState.componentID) {
      return {
        componentID: nextProps.componentID
      }
    }
    return null
  }

  componentDidUpdate(nextProps, prevState) {
    if (JSON.stringify(prevState.componentID) !== JSON.stringify(this.state.componentID)) {
      this.handleQuery();
    }
  }

  // 获取表头数据
  getColumns = async () => {
    try {
      let data = {
        params: [{
          componentID: this.props.componentID, // 主表ID
        }]
      }
      let res = await React.$asyncPost(this, '4002', data);
      this.setState({
        columns: res.result.Data,
        tableWidth: res.result.tableWidth
      })
    } catch (error) {
      this.setState({
        columns: this.props && this.props.columns && Array.isArray(this.props.columns) ? this.props.columns : [],
        tableWidth: this.props && this.props.tableWidth ? this.props.tableWidth : 0
      })
    }
  }

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

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, rowID: '', recordData: {} }, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      let { componentID, code, descripts } = this.state;
      if (!componentID) {
        this.setState({ tableData: [], total: 0 });
        return;
      }
      let data = {
        params: [{
          code,
          descripts,
          reactComID: componentID, // 主表ID
        }],
        // pagination: [{
        //   pageSize: pageSize,
        //   currentPage: page,
        // }]
      }
      let res = await React.$asyncPost(this, this.props.queryCode, data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || [], '', 0);
      this.setState({ tableData, total: res.result.total, selectedRowKeys: [], selectedRows: [], rowID: '', recordData: {}, rowData: {} });
    } catch (error) {
      this.setState({ tableData: [], total: 0 });
    }
  }

  // 保存
  handleSave = async (values) => {
    try {
      let { componentID, rowData } = this.state;
      if (!this.props.saveCode) {
        return;
      }
      let data = {
        params: [{
          reactComID: componentID, // 主表ID
          id: rowData?.id || '',
          ...values
        }]
      }
      let res = await React.$asyncPost(this, this.props.saveCode, data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.setState({ rowData: {} });
      this.modalFormRef.modifyVisible(false, 'Y');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 删除
  handleDelete = async (record) => {
    if (this.props.deleteCode) {
      let data = {
        params: [{
          id: record?.id || ''
        }]
      }
      let res = await React.$asyncPost(this, this.props.deleteCode, data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      this.getTableData();
    } else {
      message.info('删除异常，请稍后重试！');
    }
  }

  // 记录价格信息表单的值
  handleRecordFormInput = record => {
    this.setState({ rowData: { ...this.state.rowData, ...record } });
  }

  // 新增时重新获取formData
  getFormData = () => {
    let { formData, selectData } = this.props;
    for (var i = 0; i < formData.length; i++) {
      if (selectData && Object.prototype.toString.call(selectData) === '[object Object]') {
        for (var keys in selectData) {
          if (formData[i].dataIndex === keys) {
            formData[i].detailItem = selectData[keys]?.data || [];
            formData[i].defaultValue = selectData[keys]?.defID || undefined;
          }
        }
      }
    }
    this.setState({ formData }, () => {
      this.getJumpSelectData();
    })
  }

  // 获取跳转到下拉数据
  getJumpSelectData = async () => {
    try {
      let { formData, rowData, componentID } = this.state;
      let isGetData = false;
      for (var i = 0; i < formData.length; i++) { // 判断当前form是否需要获取跳转下拉数据
        if (formData[i].dataIndex === 'jumpID' || formData[i].dataIndex === 'linkValueID') {
          isGetData = true;
          break;
        }
      }
      if (isGetData) {
        let data = {
          params: [{
            componentID, // 主表ID
            fieldID: rowData?.id || '', // 当前列ID
          }],
        }
        let res = await React.$asyncPost(this, '01040288', data);
        for (var i = 0; i < formData.length; i++) {
          if (formData[i].dataIndex === 'jumpID') {
            formData[i].detailItem = res.result?.jumpID || [];
          }
          if (formData[i].dataIndex === 'linkValueID') {
            formData[i].detailItem = res.result?.linkValueID || [];;
          }
        }
        this.setState({});
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 点击input框时阻止事件冒泡
  handleStopPropagation = (e) => {
    e.stopPropagation();
  }

  handleAdd = () => {
    let { rowData } = this.state;
    if (rowData && rowData.id) {
      this.setState({ rowData: {} });
    }
    this.handleShowModal();
  }

  // 编辑
  handleCompile = (record, e) => {
    // this.handleStopPropagation(e);
    this.setState({ rowData: record }, () => {
      this.handleShowModal();
    })
  }

  // 打开表单弹窗
  handleShowModal = () => {
    this.getFormData();
    this.modalFormRef.modifyVisible(true);
  }

  // 复制数据
  handleCopyData = () => {
    const { componentID, selectedRows, activeKey } = this.state;
    let selectedRowIDs = [];
    for (let i = 0; i < selectedRows.length; i++) {
      selectedRowIDs.push(selectedRows[i].id)
    }
    this.componentSelectRef && this.componentSelectRef.modifyVisible(true, componentID, selectedRowIDs, activeKey);
  }

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

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

  // 上移
  handleUp = () => {
    let { selectedRowKeys, tableData } = this.state;
    if (!(selectedRowKeys && selectedRowKeys.length > 0)) return;
    let keys = selectedRowKeys;
    let data = tableData;
    let newKeys = [];
    keys = keys.sort(function (m, n) {
      if (m < n) return -1;
      else if (m > n) return 1;
      else return 0;
    });
    for (let i = 0; i < keys.length; i++) {
      if (keys[i] === 0) {
        newKeys.push(keys[i]);
        continue;
      }
      let curRowData = data[keys[i]];
      let curRowKey = curRowData.key;
      let upRowData = data[keys[i] - 1];
      let upRowKey = upRowData?.key || 0;
      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 = () => {
    let { selectedRowKeys, tableData } = this.state;
    if (!(selectedRowKeys && selectedRowKeys.length > 0)) return;
    let keys = selectedRowKeys;
    let data = tableData;
    let newKeys = [];
    keys = keys.sort(function (m, n) {
      if (m < n) return -1;
      else if (m > n) return 1;
      else return 0;
    });
    for (let i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length - 1) {
        newKeys.push(keys[i]);
        continue;
      }
      let curRowData = data[keys[i]];
      let upRowData = data[keys[i] + 1];
      let curRowKey = curRowData?.key || 0;
      let 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
    });
  }

  // 保存上下移序号
  handleSeqNoSave = async () => {
    try {
      let { componentID, tableData } = this.state;
      if (!this.props.className) {
        return;
      }
      let sortArr = [];
      for (let i = 0; i < tableData.length; i++) {
        sortArr.push({
          id: tableData[i].id,
          seqNo: Number(tableData[i]?.key || 0) + 1,
        })
      }
      let data = {
        params: [{
          reactComID: componentID, // 主表ID
          className: this.props.className,
          sortArr
        }]
      }
      let res = await React.$asyncPost(this, '01040292', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 多行删除
  handleMultilineDelete = async () => {
    const { selectedRowKeys } = this.state;
    if (!(selectedRowKeys && selectedRowKeys.length > 0)) return;
    if (this.props.multilineDeleteCode) {
      let data = {
        params: [{
          ids: selectedRowKeys
        }]
      }
      let res = await React.$asyncPost(this, this.props.multilineDeleteCode, data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      this.getTableData();
    } else {
      message.info('删除异常，请稍后重试！');
    }
  }

  // table列授权
  handleColumnAuthorization = () => {
    const { rowID, recordData } = this.state;
    this.authorizeRef && this.authorizeRef.modifyVisible(true, { id: rowID, descripts: recordData?.descripts || '' });
  }

  render() {
    let { tableData, loading, rowID, rowData, descripts, formData, selectedRowKeys, selectedRows } = this.state;
    let { columns, tableWidth, className, authorizeFlag } = this.props;
    // 列表操作
    const operationObj = {
      width: 130,
      title: '操作',
      align: 'center',
      fixed: 'right',
      key: 'operation',
      render: (text, record) => (
        <span>
          <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
          <span className="span" onClick={(e) => this.handleCompile(record, e)}>编辑</span>
          <Divider type="vertical" />
          <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
          <Popconfirm
            title="删除后不可恢复，确定要删除吗?"
            onClick={this.handleStopPropagation}
            onCancel={this.handleStopPropagation}
            onConfirm={(e) => this.handleDelete(record, e)}
          >
            <span className="span" style={{ color: 'rgba(240, 65, 52, 1)' }}>删除</span>
          </Popconfirm>
        </span>
      ),
    };
    // 组件所需参数
    let param = {
      // page, // 当前页数
      // total, // 数据总条数
      loading,
      // pageSize: '20',
      data: tableData, // 表格数据
      y: store.getState().tableHeight.y - 26,
      height: store.getState().tableHeight.y + 24 + 'px',
      x: columns && columns.length > 0 ? tableWidth : 1000, // 表格的宽度
      columns: columns && columns.length > 0 ? [...columns, operationObj] : [], // 表头配置
    };
    let rowSelection = {
      selectedRowKeys,
      selectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          selectedRows,
        })
      },
    };
    return (
      <div className="table-body-height">
        <div className="flex-between" style={{ paddingBottom: '12px' }}>
          <div className="flex-align-items">
            {className ? (
              <>
                <span
                  className={[!(selectedRowKeys && selectedRowKeys.length > 0) ? 'common-color999' : 'common-color333', 'flex-align-items'].join(' ')}
                  onClick={this.handleUp}
                >
                  <Icon className="doctor-up-splice" />
                  上移
                </span>
                <Divider type="vertical" />
                <span
                  className={[!(selectedRowKeys && selectedRowKeys.length > 0) ? 'common-color999' : 'common-color333', 'flex-align-items'].join(' ')}
                  onClick={this.handleDown}
                >
                  <Icon className="doctor-down-splice" />
                  下移
                </span>
                <Divider type="vertical" />
                <span
                  className={[!this.props.componentID ? 'common-color999' : 'common-color333', 'flex-align-items'].join(' ')}
                  style={{ marginRight: '24px' }}
                  onClick={this.handleSeqNoSave}
                >
                  <Icon className="doctor-save-splice" />
                  保存
                </span>
                {this.props.multilineDeleteCode ? (
                  <>
                    <Divider type="vertical" />
                    <Popconfirm
                      title="删除后不可恢复，确定要删除吗?"
                      onConfirm={this.handleMultilineDelete}
                    >
                      <span
                        className={!(selectedRowKeys && selectedRowKeys.length > 0) ? 'common-color999' : 'common-color333'}
                      >
                        <Icon className="doctor-delete-splice" />
                        删除
                      </span>
                    </Popconfirm>
                  </>
                ) : ''}
              </>
            ) : ''}
            <Input
              value={descripts}
              title="输入内容后可回车检索"
              placeholder="输入代码/描述回车查询"
              style={{ width: '200px', marginRight: '12px' }}
              onPressEnter={this.handleQuery}
              onChange={Util.commonInputChange.bind(this, 'descripts')}
            />
            <Button onClick={this.handleQuery}>查询</Button>
          </div>
          <div>
            {authorizeFlag ? (
              <Button
                ghost
                type="primary"
                disabled={!rowID}
                style={{ marginRight: 12 }}
                onClick={this.handleColumnAuthorization}
              >
                Table列授权
              </Button>
            ) : ''}
            {tableData && tableData.length > 0 ? (
              <Popconfirm title="code重复则跳过不覆盖，不存在则添加，确认复制吗?" onConfirm={this.handleCopyData}>
                <Button ghost type="primary">
                  复制数据到
                </Button>
              </Popconfirm>
            ) : (
              <Button disabled>
                复制数据到
              </Button>
            )}
            <Button
              style={{ marginLeft: 12 }}
              className={this.props.componentID ? 'add-btn add-btn-nohover' : ''}
              disabled={!this.props.componentID}
              onClick={this.handleAdd}
            >
              新增
            </Button>
          </div>
        </div>
        <PublicTablePagination
          param={param}
          // compilePage={this.compilePage}
          rowSelectionPublic={rowSelection}
          onClickRowPublic={this.onClickRowPublic}
          setRowClassNamePublic={this.setRowClassNamePublic}
        />

        <PublicModalFormHooks
          width={1200}
          onRef={ref => this.modalFormRef = ref}
          formData={formData}
          rowData={rowData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 12 }}
          recordFormInput={this.handleRecordFormInput}
          handleSave={this.handleSave}
        />

        <ComponentDataSelectModal onRef={ref => this.componentSelectRef = ref} />

        {/* table列权限 */}
        <TableColumnAuthorization onRef={ref => this.authorizeRef = ref} />
      </div>
    )
  }
};

export default CDMComponentMaintenance;