import { Button, Col, InputNumber, Row, Select } from "antd";
import React, { useState } from "react";
import { ReportTableValues } from "./types";

interface IProps {
  superRole: boolean
  tableValues: ReportTableValues[]
  onTableValuesChange: (tableValues: ReportTableValues[]) => void
}

const tableColumns = [
  {
    title: '标题',
    key: 'title',
    type: 'text',
    width: 100,
    options: []
  },
  {
    title: '打印',
    key: 'printType',
    type: 'select',
    width: 40,
    options: [
      { label: '是', value: 'all' },
      { label: '否', value: 'none' },
    ]
  },
  {
    title: '宽度(mm)',
    key: 'width',
    type: 'input',
    width: 60,
    options: []
  },
  // {
  //   title: '分组',
  //   key: 'grouping',
  //   type: 'select',
  //   width: 80,
  //   options: [
  //     { label: '否', value: 'none' },
  //     { label: '是', value: 'group' },
  //     { label: '分组并起栏', value: 'column' },
  //     { label: '分组并起页', value: 'page' }
  //   ]
  // },
  {
    title: '排序',
    key: 'sort',
    type: 'select',
    width: 40,
    options: [
      { label: '否', value: 'none' },
      { label: '升序', value: 'asc' },
      { label: '降序', value: 'desc' }
    ]
  },
  {
    title: '统计',
    key: 'statistic',
    type: 'select',
    width: 45,
    options: [
      { label: '否', value: 'none' },
      { label: '是', value: 'Sum' }
    ]
  }
]

const TableSetting: React.FC<IProps> = ({ superRole, tableValues, onTableValuesChange }) => {

  const [selectedRowKey, setSelectedRowKey] = useState(0)

  const groupName = tableValues[selectedRowKey].groupName

  const handleConfigTableChange = (rowKey: number, columnKey: string, value: any) => {
    onTableValuesChange(tableValues.map((row, index) => {
      if (index == rowKey) {
        const tempRow = row

        tempRow[columnKey] = value
        return tempRow
      }
      return row
    }))
  }

  const handleMove = (moveUp: boolean) => {
    const swap = (rows: ReportTableValues[], currentIndex: number, targetIndex: number) => {
      const currentRow = rows[currentIndex]
      rows[currentIndex] = rows[targetIndex]
      rows[targetIndex] = currentRow
    }
    const tempRows = tableValues.slice()
    const currentGroup = tempRows[selectedRowKey].group
    const currentLength = tempRows.filter(row => row.group == currentGroup).length

    const targetGroup = tempRows[selectedRowKey + (moveUp ? -1 : 1)].group
    const targetLength = tempRows.filter(row => row.group == targetGroup).length
    let targetRowKey
    if (currentGroup == targetGroup) {
      targetRowKey = selectedRowKey + (moveUp ? -1 : 1)
      swap(tempRows, selectedRowKey, targetRowKey)
    } else {
      targetRowKey = selectedRowKey + (moveUp ? (-targetLength) : targetLength)
      const currentStart = tempRows.findIndex(row => row.group == currentGroup)
      const currentEnd = tempRows.filter(row => row.group == currentGroup).length + currentStart - 1
      const targetStart = tempRows.findIndex(row => row.group == targetGroup)
      const targetEnd = tempRows.filter(row => row.group == targetGroup).length + targetStart - 1
      const start = moveUp ? currentStart : targetStart
      const end = moveUp ? currentEnd : targetEnd
      const length = moveUp ? targetLength : currentLength
      for (let i = start; i <= end; i++) {
        for (let j = i; i < j + length; j--) {
          swap(tempRows, j, j - 1)
        }
      }
    }
    onTableValuesChange(tempRows)
    setSelectedRowKey(targetRowKey)
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Row style={{ height: 30 }}>
        <Col><Button onClick={() => handleMove(true)} disabled={selectedRowKey == 0 || !superRole} type="link">上移</Button></Col>
        <Col><Button onClick={() => handleMove(false)} disabled={selectedRowKey == tableValues.length - 1 || !superRole} type="link">下移</Button></Col>
      </Row>
      <div style={{ flex: 1, marginTop: 8, overflow: 'auto' }}>
        <table id="report-print-column-config-table" className="column-config-table" width={342} cellSpacing={0} >
          <thead>
            <tr>
              {tableColumns.map(column => (
                <th key={column.key} style={{ width: column.width }} >{column.title}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {tableValues.map((row, index) => (
              <tr key={index}>
                {tableColumns.map(column => {
                  const value = row[column.key]
                  const isSelectedCell = column.key == 'title' && index == selectedRowKey
                  const isGroupCell = column.key == 'title' && (groupName ? groupName === row.groupName : index == selectedRowKey)
                  return (
                    <td
                      key={column.key}
                      title={column.key == 'title' ? value : undefined}
                      onClick={column.key == 'title' ? () => setSelectedRowKey(index) : undefined}
                      style={{ backgroundColor: isGroupCell ? '#3574ee' : isSelectedCell ? 'black' : undefined, color: isSelectedCell ? 'white' : undefined }}
                    >
                      {column.type == 'text' && <>{value}</>}
                      {column.type == 'select' &&
                        <Select
                          disabled={!superRole}
                          size='small'
                          showArrow={false}
                          value={value}
                          getPopupContainer={() => document.getElementById('report-print-column-config-table')!}
                          dropdownClassName='column-config-table-select-dropdown'
                          onChange={value => handleConfigTableChange(index, column.key, value)}
                        >
                          {column.options!.map((option, index) => (
                            <Select.Option key={index} value={option.value}>
                              {option.label}
                            </Select.Option>
                          ))}
                        </Select>
                      }
                      {column.type == 'input' &&
                        <InputNumber
                          style={{ width: '100%', border: 'none' }}
                          disabled={!superRole}
                          size="small"
                          controls={false}
                          value={value}
                          min={0}
                          max={200}
                          onChange={value => handleConfigTableChange(index, column.key, value)}
                        />
                      }
                    </td>
                  )
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

export default TableSetting