import React, { useEffect, useMemo, useState } from 'react'
import {
  Drawer,
  Form,
  Button,
  Input,
  Switch,
  Select,
  Tag,
  Table,
  Divider,
  Dropdown,
  Menu,
  Popconfirm,
  Icon,
  Modal, Spin
} from 'antd'
import { IClassification, IMetaParam, IQualityTask } from '../types'
import { ColumnProps } from 'antd/lib/table'
import MetadataModal from 'containers/DataGovernanceQualityAudit/components/MetadataModal'
import { IViewBase } from 'containers/View/types'
import SubjectModal from 'containers/DataGovernanceQualityAudit/components/SubjectModal'
import { IDataSubject } from 'containers/DataGovernanceMarkRule/types'
import request from 'utils/request'
import api from 'utils/api'

interface IQualityTaskFormModalProps {
  pId: number
  visible: boolean
  loading: boolean
  // eslint-disable-next-line no-undef
  formView: Partial<IQualityTask>
  onSave: (view) => void
  onCancel: () => void
}

const QualityTaskFormModal = ({
                                formView,
                                visible,
                                loading,
                                onCancel,
                                pId,
                                onSave
                              }: IQualityTaskFormModalProps) => {
  const [metaVisible, setMetaVisible] = useState(false)
  const [viewLoading, setViewLoading] = useState(false)

  const [taskName, setTaskName] = useState<IQualityTask['taskName']>()
  // @ts-ignore
  const [selection, setSelection] = useState<IViewBase[]>([])

  const [tableData, setTableData] = useState<IMetaParam[]>([])
  const [metaDataConfig, setMateDataConfig] = useState<IMetaParam[]>([])

  const [smVisible, setSmVisible] = useState(false)
  const [smFormView, setSmFormView] = useState<IMetaParam>()

  const paramsColumns: Array<ColumnProps<IMetaParam>> = [
    {
      title: '名称',
      dataIndex: 'fieldName'
    },
    {
      title: '数据类型',
      dataIndex: 'fieldType'
    },
    {
      title: '别名',
      dataIndex: ''
    },
    {
      title: '标准名称',
      dataIndex: 'subjectName'
    },
    {
      title: '操作',
      render: (_, data) => (
        <>
          <a
            onClick={() => {
              setSmVisible(true)
              setSmFormView(data)
            }}
          >
            关联标准
          </a>
          {metaDataConfig.find((m) => m.fieldName === data.fieldName) && (
            <>
              <Divider type='vertical' />
              <Popconfirm
                title='确定删除？'
                placement='bottom'
                onConfirm={() => handleResetSmForm(data)}
              >
                <a>取消关联</a>
              </Popconfirm>
            </>
          )}
        </>
      )
    }
  ]

  const handleSave = () => {
    onSave({
      taskName,
      viewId: selection?.[0]?.id,
      metadataName: selection?.[0]?.name,
      metadataConfig: JSON.stringify(metaDataConfig),
      pId
    })
  }

  const handleSaveSmForm = (data: IDataSubject) => {
    setMateDataConfig((meta) => {
      return [
        ...meta.filter((s) => s.fieldName !== smFormView.fieldName),
        {
          ...smFormView
        }
      ]
    })

    setSmVisible(false)
  }
  const handleResetSmForm = (data: IMetaParam) => {
    // selection
    setMateDataConfig((meta) => {
      return [
        ...meta.filter((s) => s.fieldName !== smFormView.fieldName)
      ]
    })
  }

  const queryViewByID = async() => {
    try {
      setTaskName(formView?.taskName)

      setViewLoading(true)
      if (formView?.viewId) {
        const data = await request(api.view + '/' + formView.viewId)
        setSelection(
          // @ts-ignore
          [{
            name: formView?.metadataName,
            metadataConfig: formView?.metadataConfig,
            // @ts-ignore
            model: data.payload.model
          }]
        )
      } else {
        setSelection([])
      }
    } finally {
      setViewLoading(false)
    }
  }

  useEffect(() => {
    queryViewByID()
  }, [formView])

  useEffect(() => {
    const d = selection?.map((s) => s?.model)?.[0] || '{}'
    let next = {}
    try {
      next = JSON.parse(d)
    } catch (e) {
      console.log(e)
    }
    const model = Object.keys(next)?.map((k) => ({
      fieldName: k,
      fieldType: next?.[k]?.visualType
    })) as IMetaParam[] || []
    setTableData(model)

  }, [selection])

  useEffect(() => {
    const d = selection
      ?.map((s) => s?.metadataConfig)
      .reduce((c, n) => {
        let next = []
        try {
          next = JSON.parse(n || '[]')
        } catch (e) {
          console.log(e)
        }
        return [...c, ...next]
      }, [] as IMetaParam[])
    setMateDataConfig(d)
  }, [selection])

  return (
    <Modal
      title={null}
      visible={visible}
      onCancel={onCancel}
      destroyOnClose
      width='80%'
      footer={
        <>
          <Button onClick={onCancel} style={{ marginRight: 6 }}>
            取 消
          </Button>
          <Button disabled={loading} type='primary' onClick={handleSave}>
            保 存
          </Button>
        </>
      }
      // placement={'bottom'}
    >
      <Spin spinning={viewLoading}>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
          }}
        >
          <h3>质量任务</h3>
        </div>
        <div style={{ margin: '10px 0', display: 'flex', alignItems: 'center' }}>
          <label>质量任务名称：</label>
          <Input
            value={taskName}
            onChange={(e) => setTaskName(e.target.value)}
            style={{ width: 300 }}
          />
        </div>
        <div style={{ margin: '10px 0', display: 'flex', alignItems: 'center' }}>
          <label>元数据：</label>
          <Button onClick={() => setMetaVisible(true)}>选择元数据</Button>
          <div
            style={{
              margin: '0 10px',
              display: 'flex',
              alignItems: 'center',
              flexWrap: 'wrap',
              flex: 1
            }}
          >
            {selection.map((c, idx) => (
              <Tag key={c.id || idx} closable onClose={() => setSelection([])}>
                {c.name}
              </Tag>
            ))}
          </div>
        </div>
        <div>
          <p style={{ margin: '10px 0' }}>字段映射</p>
          <Table
            columns={paramsColumns}
            rowKey='fieldName'
            dataSource={tableData}
          />
        </div>
      </Spin>
      <MetadataModal
        selection={selection}
        onSave={(e) => {
          setSelection(e)
          setMetaVisible(false)
        }}
        visible={metaVisible}
        onCancel={() => setMetaVisible(false)}
      />
      <SubjectModal
        visible={smVisible}
        formView={smFormView}
        onSave={handleSaveSmForm}
        onCancel={() => setSmVisible(false)}
      />
    </Modal>
  )
}

export default QualityTaskFormModal
