/*
 * <<
 * 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,
  Popconfirm,
  message
} 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 { IDataSubject } from 'containers/DataGovernanceMarkRule/types'
import { IDictData } from 'containers/DataManagerDictionary/types'
import { isNumber } from 'lodash'
import Box from 'components/Box'
import { IMetaParam } from 'containers/DataGovernanceQualityAudit/types'

interface ISubjectModalProps extends RouteComponentWithParams {
  visible: boolean
  formView: IMetaParam
  onCancel: () => void
  onSave: (e: IDataSubject) => void
}

const SubjectModal = (props: ISubjectModalProps) => {
  const { visible, onCancel, onSave, match } = props

  const [tableLoading, setTableLoading] = useState(false)
  const [dataSubject, setDataSubject] = useState<IDataSubject[]>([])

  const [selectedSubjectsKey, setSelectedSubjectsKey] = useState<number>()

  const [tableRowSelection, setTableRowSelection] = useState<number>()

  const [treeLoading, setTreeLoading] = useState(false)
  const [subjects, setSubject] = useState<IDictData[]>([
    { dictLabel: '全部主题', dictCode: -1 }
  ])

  const tableColumns: Array<ColumnProps<IDataSubject>> = [
    {
      title: '标准主题',
      dataIndex: 'standardTheme'
    },
    {
      title: '标准编码',
      dataIndex: 'standardCode'
    },
    {
      title: '标准名称',
      dataIndex: 'standardName'
    },
    {
      title: '别名',
      dataIndex: 'standardAlias'
    },
    {
      title: '英文名称',
      dataIndex: 'englishName'
    },
    {
      title: '管理部门',
      dataIndex: 'deptName'
    },
    {
      title: '管理人员',
      dataIndex: 'management'
    }
  ]

  const querySubjects = async () => {
    try {
      setTreeLoading(true)
      const data = await request(`${api.getSubjects}data_standard`, {
        method: 'GET'
      })
      const defaultSubject = [{ dictLabel: '全部主题', dictCode: -1 }]
      setSubject(
        // @ts-ignore
        data?.payload ? [...defaultSubject, ...data?.payload] : defaultSubject
      )
      setSelectedSubjectsKey(-1)
    } finally {
      setTreeLoading(false)
    }
  }

  const queryDataBySelectedSubject = async () => {
    try {
      setTableLoading(true)
      const data = await request(
        `${api.getDataSubject}?pId=${
          selectedSubjectsKey === -1 ? '' : selectedSubjectsKey
        }`,
        { method: 'GET' }
      )
      // @ts-ignore
      setDataSubject(data?.payload ?? [])
    } finally {
      setTableLoading(false)
    }
  }

  const renderTree = (catalogues: IDictData[]) => (
    <>
      {catalogues.map((c, idx) => (
        <div
          key={c.dictCode ?? idx}
          className={classnames(styles.treeNode, {
            [styles.treeNodeSelected]: selectedSubjectsKey === c.dictCode
          })}
        >
          <span
            className={styles.treeNodeLeft}
            onClick={() => {
              setSelectedSubjectsKey(c.dictCode)
            }}
          >
            <Icon type="folder-open" />
            {c.dictLabel}
          </span>
        </div>
      ))}
    </>
  )

  useEffect(() => {
    async function query() {
      await querySubjects()
      // await queryDataBySelectedSubject()
    }

    query()
  }, [])

  useEffect(() => {
    if (isNumber(selectedSubjectsKey)) {
      queryDataBySelectedSubject()
    }
  }, [selectedSubjectsKey])

  const handleSave = () => {
    const s = dataSubject?.find((d) => d.id === tableRowSelection)
    console.log(s, dataSubject, tableRowSelection, '+++')
    onSave(s)
  }

  return (
    <Modal
      title="关联标准"
      visible={visible}
      onCancel={onCancel}
      onOk={handleSave}
      destroyOnClose
      width="80%"
    >
      <Box>
        <Box.Body>
          <div className={styles.treeTableContainer}>
            <div className={styles.treeContainer}>
              <div className={styles.treeTitle}>
                <h6>主题</h6>
              </div>
              <div className={styles.treeContent}>
                <Spin spinning={treeLoading}>{renderTree(subjects)}</Spin>
              </div>
            </div>

            <div style={{ flex: 1 }}>
              <Table
                rowSelection={{
                  type: 'radio',
                  selectedRowKeys: [tableRowSelection],
                  onChange: (selectedRowKeys) => {
                    // @ts-ignore
                    setTableRowSelection((c) => selectedRowKeys[0])
                  }
                }}
                style={{ flex: 1 }}
                bordered
                rowKey="id"
                loading={tableLoading}
                dataSource={dataSubject}
                columns={tableColumns}
                pagination={false}
                // onChange={this.tableChange}
              />
            </div>
          </div>
          <br />
        </Box.Body>
      </Box>
    </Modal>
  )
}

export default withRouter(SubjectModal)
