import React from 'react'
import { Button, Modal, Table, Form, Input } from 'antd'
import { generateUUID, showMessage } from '../../../../util'
import { DatatypeInput } from './ImportActionTable'

import { dispatch } from '../../../../model'
import Suggest from './suggest'

function hasDuplicates(array) {
  return (new Set(array)).size !== array.length;
}

const FC = (props) => {
  const { visible, value, onChange, modelerData } = props
  const basicRef = React.useRef()

  const close = (data = undefined) => {
    onChange?.(data)
  }

  const save = async () => {
    try {
      await basicRef.current.validate()

      const data = basicRef.current.data
      const names = (data??[]).map(item => item.name)
      const cnNames = (data??[]).map(item => item.cnName)

      if (hasDuplicates(names)) {
        showMessage('warn', '英文名称重复')
        return 
      }

      if (hasDuplicates(cnNames)) {
        showMessage('warn', '中文名称重复')
        return 
      }

      close(data)
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  const footer = React.useMemo(() => {
    return [
      <Button key={'cancel'}
        onClick={() => close()}
      >取消</Button>,
      <Button key={'save'} type='primary'
        onClick={() => save()}
      >保存</Button>
    ]
  }, [close, save])

  return (
    <Modal
      visible={visible}
      footer={footer}
      width='80%'
      bodyStyle={{ padding: '15px 15px 0px 15px', overflowX: 'auto', maxHeight: '80vh', height: 500 }}
      title='编辑分区字段'
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      <Basic ref={basicRef} modelerData={modelerData} value={value} />
    </Modal>
  )
}

export default FC

const Basic = React.forwardRef(function ({ modelerData, value }, ref) {
  const [form] = Form.useForm()
  const [data, setData] = React.useState()
  const [supportedDatatypes, setDatatypes] = React.useState()
  const [suggestParams, setSuggestParams] = React.useState({
    visible: false,
    name: undefined,
    cnName: undefined,
    triggerType: undefined,
  })
  const [triggerSuggestItem, setTriggerSuggestItem] = React.useState()

  React.useImperativeHandle(ref, () => ({
    validate: async () => {
      return await form?.validateFields()
    },
    data
  }), [form, data])

  React.useEffect(() => {
    getSupportedDatatypes()
  }, [])

  React.useEffect(() => {
    setData(value)
  }, [value])

  const columns = [
    {
      title: '中文名称',
      dataIndex: 'cnName',
      width: 200,
      render: (_, record) => {
        form?.setFieldsValue({ [`cnName${record.iid}`]: record.cnName })
        return (
          <Form.Item name={`cnName${record.iid}`}
            rules={[{ required: true, message: '请输入中文名称' }]}
            style={{ marginBottom: 0 }}
          >
            <Input placeholder='请输入中文名称' onChange={(e) => {
              const newData = [...data??[]]
              const index = newData.findIndex(item => item.iid === record.iid)
              if (index !== -1) {
                newData[index].cnName = e.target.value
                setData(newData)
              }
            }} onPressEnter={() => {
              setTriggerSuggestItem(record)
              onColumnPressEnter('cnName', record)
            }} />
          </Form.Item>
        )
      }
    },
    {
      title: '英文名称',
      dataIndex: 'name',
      width: 200,
      render: (_, record) => {
        form?.setFieldsValue({ [`name${record.iid}`]: record.name })
        return (
          <Form.Item name={`name${record.iid}`}
            rules={[{ required: true, message: '请输入英文名称' }]}
            style={{ marginBottom: 0 }}
          >
            <Input placeholder='请输入英文名称' onChange={(e) => {
              const newData = [...data??[]]
              const index = newData.findIndex(item => item.iid === record.iid)
              if (index !== -1) {
                newData[index].name = e.target.value
                setData(newData)
              }
            }} onPressEnter={() => {
              setTriggerSuggestItem(record)
              onColumnPressEnter('name', record)
            }} />
          </Form.Item>
        )
      }
    },
    {
      title: '类型',
      dataIndex: 'datatype',
      width: 200,
      render: (_, record) => {
        form?.setFieldsValue({ [`datatype${record.iid}`]: record.datatype })
        return (
          <Form.Item name={`datatype${record.iid}`}
            rules={[{ required: true, message: '请输入类型' }]}
            style={{ marginBottom: 0 }}
          >
            <DatatypeInput 
              datatypes={(supportedDatatypes??[]).filter(item => item.supportedDBTypes.indexOf(modelerData?.dbType) !== -1)}
              onChange={(val) => {
                const newData = [...data??[]]
                const index = newData.findIndex(item => item.iid === record.iid)
                if (index !== -1) {
                  newData[index].datatype = val
                  setData(newData)
                }
              }} />
          </Form.Item>
        )
      }
    },
    {
      title: '业务含义',
      dataIndex: 'remark',
      width: 200,
      render: (_, record) => {
        form?.setFieldsValue({ [`remark${record.iid}`]: record.remark })
        return (
          <Form.Item name={`remark${record.iid}`}
            rules={[{ required: true, message: '请输入业务含义' }]}
            style={{ marginBottom: 0 }}
          >
            <Input placeholder='请输入业务含义' onChange={(e) => {
              const newData = [...data??[]]
              const index = newData.findIndex(item => item.iid === record.iid)
              if (index !== -1) {
                newData[index].remark = e.target.value
                setData(newData)
              }
            }} />
          </Form.Item>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 80,
      render: (_, record) => {
        return <a onClick={() => {
          const newData = [...data??[]]
          const index = newData.findIndex(item => item.iid === record.iid)

          if (index !== -1) {
            newData.splice(index, 1)
            setData(newData)
          }
        }}>删除</a>
      }
    }
  ]

  const getSupportedDatatypes = () => {
    dispatch({
      type: 'datamodel.getSupportedDatatypes',
      callback: data => {
        setDatatypes(data)
      }
    });
  }

  const onColumnPressEnter = (dataIndex, record) => {
    setSuggestParams({
      visible: true,
      name: record.name,
      cnName: record.cnName,
      triggerType: dataIndex,
    })
  }

  const onSuggestChange = (record) => {
    const newData = [...data??[]]
    const index = newData.findIndex(item => item.iid === triggerSuggestItem?.iid)

    if (index !== -1) {
      newData.splice(index, 1, record)
      setData(newData)
    }
  }

  return (
    <>
      <div className='mb-3 flex' style={{ justifyContent: 'flex-end' }}>
        <Button onClick={() => {
          const iid = generateUUID()
          const newData = [...data??[], { iid }]
          setData(newData)
        }}>新建</Button>
      </div>
      <Form form={form}>
        <Table 
          columns={columns}
          dataSource={data}
          pagination={false}
        />
      </Form>
      <Suggest 
        {...suggestParams}
        onCancel={() => {
          setSuggestParams({
            visible: false,
            name: undefined,
            cnName: undefined,
            triggerType: undefined,
          })
        }}
        onOk={onSuggestChange}
      />
    </>
  )
})

export const Detail = ({ value }) => {
  const columns = [
    {
      title: '中文名称',
      dataIndex: 'cnName',
    },
    {
      title: '英文名称',
      dataIndex: 'name',
    },
    {
      title: '类型',
      dataIndex: 'datatype',
      render: (_, record, __) => {
        if (record?.datatype) {

          if ((record?.datatype?.name==='Char'||record?.datatype?.name==='Varchar') && record?.datatype?.parameterValues?.length>0) {

            return `${record?.datatype?.name||''}(${(record?.datatype?.parameterValues[0]?record.datatype.parameterValues[0]:0)})`;
          
          } else if ((record?.datatype?.name==='Decimal'||record?.datatype?.name==='Numeric') && record?.datatype?.parameterValues?.length>1) {
            return `${record?.datatype?.name||''}(${(record?.datatype?.parameterValues[0]?record.datatype.parameterValues[0]:0)},${(record?.datatype?.parameterValues[1]?record.datatype.parameterValues[1]:0)})`;
          }

          return record.datatype.name||'';
        }

        return '';
      }
    },
    {
      title: '业务含义',
      dataIndex: 'remark',
    },
  ]

  return (
    <div style={{ width: 500, maxHeight: 300, overflow: 'auto' }}>
      <Table 
        columns={columns}
        dataSource={value??[]}
        pagination={false}
      />
    </div>
  )
}