import React, { useEffect, useState } from 'react'
import Helmet from 'react-helmet'
import Container, { ContainerBody } from 'components/Container'
import Box from 'components/Box'
import { Button, Divider, Icon, message, Popconfirm, Spin, Table } from 'antd'
import { ColumnProps } from 'antd/lib/table'
import { compose } from 'redux'
import request from 'utils/request'
import api from 'utils/api'
import { IDataSubject } from 'containers/DataGovernanceMarkRule/types'
import DataSubjectFormModal from 'containers/DataGovernanceMarkRule/components/DataSubjectFormModal'
import { AuditClassificationFormModal } from 'containers/DataGovernanceMarkRule/components/AuditClassificationFormModal'
import styles from 'containers/DataManagerView/index.less'
import classnames from 'classnames'
import { IDictData } from 'containers/DataManagerDictionary/types'
import { isNumber } from 'lodash'

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

  const [dataSubjectFormVisible, setDataSubjectFormVisible] = useState(false)
  const [dataSubjectFormLoading, setDataSubjectFormLoading] = useState(false)
  const [dataSubjectForm, setDataSubjectForm] = useState<IDataSubject>(null)

  const [auditLoading, setAuditLoadingLoading] = useState(false)

  const [selectedSubjectsKey, setSelectedSubjectsKey] = 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'
    },
    {
      title: '操作',
      render: (_, data) => (
        <>
          <a
            onClick={() => {
              setAuditLoadingLoading(true)
              setDataSubjectForm(data)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setDataSubjectFormVisible(true)
              setDataSubjectForm(data)
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定删除？"
            placement="bottom"
            onConfirm={() => handleDeleteDataSubject(data.id)}
          >
            <a>删除</a>
          </Popconfirm>
        </>
      )
    }
  ]

  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 handleDeleteDataSubject = async (id) => {
    try {
      setTableLoading(true)
      await request(`${api.deleteDataSubject}/${id}`, { method: 'delete' })
      await queryDataBySelectedSubject()
    } finally {
      setTableLoading(false)
    }
  }
  const handleSaveDataSubject = async (dt: IDataSubject) => {
    // // 0=正常,1=停用
    try {
      setDataSubjectFormLoading(true)
      const url = dataSubjectForm?.id
        ? `${api.updateDataSubject}/${dataSubjectForm.id}`
        : api.createDataSubject
      await request(url, {
        method: dataSubjectForm?.id ? 'PUT' : 'POST',
        data: { ...(dataSubjectForm ?? {}), ...dt }
      })
      message.success({ content: '成功' })
      setDataSubjectFormVisible(false)
      await queryDataBySelectedSubject()
    } finally {
      setDataSubjectFormLoading(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])

  return (
    <Container>
      <Helmet title="规则制定" />
      <ContainerBody>
        <Box>
          <Box.Header>
            <Box.Title>规则制定</Box.Title>
          </Box.Header>
          <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 }}>
                <div style={{ padding: '0 0 20px' }}>
                  <Button
                    type="primary"
                    icon="plus"
                    onClick={() => {
                      setDataSubjectFormVisible(true)
                      setDataSubjectForm(null)
                    }}
                  >
                    新增
                  </Button>
                </div>
                <Table
                  style={{ flex: 1 }}
                  bordered
                  rowKey="id"
                  loading={tableLoading}
                  dataSource={dataSubject}
                  columns={tableColumns}
                  pagination={false}
                  // onChange={this.tableChange}
                />
              </div>
            </div>
            <br />
          </Box.Body>
        </Box>
      </ContainerBody>
      <AuditClassificationFormModal
        visible={auditLoading}
        fromView={dataSubjectForm}
        onCancel={() => setAuditLoadingLoading(false)}
      />
      <DataSubjectFormModal
        visible={dataSubjectFormVisible}
        loading={dataSubjectFormLoading}
        fromView={dataSubjectForm}
        subject={selectedSubjectsKey}
        subjects={subjects}
        onSave={handleSaveDataSubject}
        onCancel={() => setDataSubjectFormVisible(false)}
      />
    </Container>
  )
}

export default compose()(DataDictionary)
