/*
 * <<
 * Davinci
 * ==
 * Copyright (C) 2016 - 2017 EDP
 * ==
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * >>
 */

import React, { useEffect, useState } from 'react'
import { Modal, Button, Table, Divider, Icon, Spin } from 'antd'
import { ColumnProps } from 'antd/lib/table'
import api from 'utils/api'
import request from 'utils/request'
import styles from 'containers/DataManagerView/index.less'
import classnames from 'classnames'
import { ICatalogue, IViewBase } from 'containers/DataManagerView/types'
import { RouteComponentWithParams } from 'utils/types'
import { withRouter } from 'react-router-dom'
import SubjectModal from 'containers/DataGovernanceQualityAudit/components/SubjectModal'
import { IMetaParam } from 'containers/DataGovernanceQualityAudit/types'

interface IMetadataModalProps extends RouteComponentWithParams {
  visible: boolean
  selection: IViewBase[]
  onCancel: () => void
  onSave: (e: IViewBase[]) => void
}

const MetadataModal = (props: IMetadataModalProps) => {
  const { visible, onCancel, onSave, match, selection } = props

  const [treeLoading, setTreeLoading] = useState(false)
  const [selectedKey, setSelectedKey] = useState<number[]>([])
  const [catalogues, setCatalogues] = useState<ICatalogue[]>([])

  const [tableMetadata, setTableMetadata] = useState<IViewBase[]>([])
  const [tableLoading, setTableLoading] = useState(false)
  const [tableRowSelection, setTableRowSelection] = useState<number>()

  const getCatalogues = async() => {
    try {
      const { projectId } = match.params

      setTreeLoading(true)
      // @ts-ignore
      const { payload } = await request(
        `${api.getCatalogues}?projectId=${projectId}`,
        { method: 'GET' }
      )
      setCatalogues(payload)
      setSelectedKey(payload?.[0]?.id ? [payload?.[0]?.id] : [])
    } finally {
      setTreeLoading(false)
    }
  }

  const loadViews = async() => {
    const { projectId } = match.params
    if (projectId && selectedKey.length > 0) {
      const parentId = Number(selectedKey[0])
      try {
        setTableLoading(true)
        const data = await request(
          `${api.getViewsByParentId}?projectId=${projectId}&parentId=${parentId}`,
          { method: 'get' }
        )
        // @ts-ignore
        setTableMetadata(data.payload ?? [])
      } finally {
        setTableLoading(false)
      }
    }
  }

  const tableColumns: Array<ColumnProps<IViewBase>> = [
    {
      title: '元数据名称',
      dataIndex: 'name'
    },
    {
      title: '元数据类型',
      dataIndex: ''
    },
    {
      title: '更新时间',
      dataIndex: ''
    },
    {
      title: '创建人',
      dataIndex: ''
    },
    {
      title: '是否关联质量',
      dataIndex: 'isDefault',
      render: (_, data, idx) => (
        <>
          {data?.relationQuality ? <span>是</span> : <span>否</span>}
        </>
      )
    }
  ]

  const renderTree = (catalogues: ICatalogue[]) => (
    <>
      {catalogues.map((c, idx) => (
        <>
          <div
            key={c.id ?? idx}
            className={classnames(styles.treeNode, {
              [styles.treeNodeSelected]: selectedKey.includes(c.id)
            })}
            onClick={() => {
              setSelectedKey([c.id])
            }}
          >
            <span className={styles.treeNodeLeft}>
              <Icon type='file' />
              {c.name}
            </span>
          </div>
          <div style={{ marginLeft: 20 }}>
            {c.children && renderTree(c.children)}
          </div>
        </>
      ))}
    </>
  )
  const handleSave = () => {
    const s = tableMetadata?.find((t) => t.id === tableRowSelection)
    onSave([s])
  }

  useEffect(() => {
    getCatalogues()
  }, [])

  useEffect(() => {
    setTableRowSelection(selection?.map((s) => s.id)?.[0])
  }, [selection])

  useEffect(() => {
    if (selectedKey.length > 0) {
      loadViews()
    }
  }, [selectedKey])

  return (
    <Modal
      title='选择元数据'
      visible={visible}
      onCancel={onCancel}
      onOk={handleSave}
      destroyOnClose
      width='80%'
    >
      <div className={styles.treeTableContainer}>
        <div className={styles.treeContainer}>
          <div className={styles.treeTitle}>
            <h6>选择元数据</h6>
          </div>
          <div className={styles.treeContent}>
            <Spin spinning={treeLoading}>{renderTree(catalogues)}</Spin>
          </div>
        </div>

        <div style={{ flex: 1 }}>
          <div style={{ padding: '0 0 20px' }}>
            <Button type='primary' icon='plus'>
              查询
            </Button>
          </div>
          <Table
            rowSelection={{
              type: 'radio',
              selectedRowKeys: [tableRowSelection],
              onChange: (selectedRowKeys) => {
                // @ts-ignore
                setTableRowSelection((c) => selectedRowKeys[0])
              }
            }}
            style={{ flex: 1 }}
            bordered
            rowKey='id'
            loading={tableLoading}
            dataSource={tableMetadata}
            columns={tableColumns}
            pagination={false}
          />
        </div>
      </div>
    </Modal>
  )
}

export default withRouter(MetadataModal)
