import React, { useEffect, useState } from 'react'
import Container, { ContainerBody } from 'components/Container'
import Helmet from 'react-helmet'
import Box from 'components/Box'
import styles from 'containers/DataManagerView/index.less'
import {
  Button,
  Divider,
  Dropdown,
  Icon,
  Menu,
  message,
  Popconfirm,
  Spin,
  Table
} from 'antd'
import classnames from 'classnames'
import request from 'utils/request'
import api from 'utils/api'
import { ColumnProps } from 'antd/lib/table'
import {
  IClassification,
  IQualityTask
} from 'containers/DataGovernanceQualityAudit/types'
import ClassificationsFormModal from 'containers/DataGovernanceQualityAudit/components/ClassificationsFormModal'
import QualityTaskFormModal from 'containers/DataGovernanceQualityAudit/components/QualityTaskFormModal'
import ScheduleFormModal from 'containers/DataGovernanceQualityAudit/components/ScheduleFormModal'
import header from 'containers/Display/Editor/Header'

export default function DataGovernanceQualityAudit() {
  const [tableLoading, setTableLoading] = useState(false)

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

  const [qualityTasks, setQualityTasks] = useState<IQualityTask[]>([])
  const [qtVisible, setQtVisible] = useState(false)
  const [qtLoading, setQtLoading] = useState(false)
  // eslint-disable-next-line no-undef
  const [qtForm, setQtForm] = useState<Partial<IQualityTask>>({})

  const [classifications, setClassifications] = useState<IClassification[]>([])
  const [cfVisible, setCfVisible] = useState(false)
  const [cfLoading, setCfLoading] = useState(false)
  const [cfForm, setCfForm] = useState<IClassification>({})

  const [scVisible, setScVisible] = useState(false)
  const [scLoading, setSCLoading] = useState(false)
  const [scForm, setSCForm] = useState<IClassification>({})

  const tableColumns: Array<ColumnProps<IQualityTask>> = [
    {
      title: '任务名称',
      dataIndex: 'taskName'
    },
    {
      title: '元数据名称',
      dataIndex: 'metadataName'
    },
    {
      title: '稽核字段个数',
      dataIndex: 'standardName'
    },
    {
      title: '操作',
      render: (_, data) => (
        <>
          <a
            onClick={() => {
              setQtVisible(true)
              setQtForm(data)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="0" onClick={() => setScVisible(true)}>
                  设置调度
                </Menu.Item>
                <Menu.Item key="1">
                  <Popconfirm
                    title="确定立即稽查吗？"
                    placement="bottom"
                    onConfirm={() => handleSetDispatchRightNow(data)}
                  >
                    <a>立即稽查</a>
                  </Popconfirm>
                </Menu.Item>
                <Menu.Item key="2">修改</Menu.Item>
                <Menu.Item key="3">
                  <Popconfirm
                    title="确定删除？"
                    placement="bottom"
                    // onConfirm
                  >
                    <a>删除</a>
                  </Popconfirm>
                </Menu.Item>
              </Menu>
            }
          >
            <a>
              {' '}
              更多 <Icon type="down" />
            </a>
          </Dropdown>
        </>
      )
    }
  ]

  const handleEditTreeItem = (form: IClassification) => {
    setCfForm(form)
    setCfVisible(true)
  }

  const handleDeleteTreeItem = async (c: IClassification) => {
    try {
      setTreeLoading(true)
      const data = await request(`${api.deleteAuditClassification}${c.id}`, {
        method: 'DELETE'
      })
      // @ts-ignore
      if (data?.header?.code === 200) {
        message.success({ content: '删除成功' })
        await queryClassifications()
      } else {
        // @ts-ignore
        // tslint:disable-next-line:no-unused-expression
        data?.header?.msg && message.error({ content: data?.header?.msg })
      }
    } finally {
      setTreeLoading(false)
    }
  }

  const renderTree = (catalogues: IClassification[]) => (
    <>
      {catalogues.map((c, idx) => (
        <div
          key={c.id ?? idx}
          className={classnames(styles.treeNode, {
            [styles.treeNodeSelected]: selectedKey === c.id
          })}
        >
          <span
            className={styles.treeNodeLeft}
            onClick={() => {
              setSelectedKey(c.id)
            }}
          >
            <Icon type="file" />
            {c.name}
          </span>
          <Dropdown
            overlay={() => (
              <Menu>
                <Menu.Item key="0" onClick={() => handleEditTreeItem(c)}>
                  编辑
                </Menu.Item>
                <Menu.Item key="1">
                  <Popconfirm
                    title="确定删除？"
                    placement="bottom"
                    onConfirm={() => handleDeleteTreeItem(c)}
                  >
                    <a>删除</a>
                  </Popconfirm>
                </Menu.Item>
              </Menu>
            )}
            trigger={['click']}
          >
            <Icon type="more" />
          </Dropdown>
        </div>
      ))}
    </>
  )

  const handleSetDispatchRightNow = async (data: IQualityTask) => {
    try {
      setTableLoading(true)
      const result = await request(
        `${api.setDispatchRightNow}${data.cronJobId}`,
        {
          method: 'PUT'
        }
      )
      // @ts-ignore
      if (result.header.code === 200) {
        message.success({ content: '立即稽核完成' })
      } else {
        // @ts-ignore
        // tslint:disable-next-line:no-unused-expression
        result?.header?.msg && message.success({ content: result.header.msg })
      }
    } finally {
      setTableLoading(false)
    }
  }

  const queryClassifications = async () => {
    try {
      setTreeLoading(true)
      const data = await request(api.getAuditClassification, { method: 'GET' })
      // @ts-ignore
      setClassifications(data?.payload ?? [])
      // @ts-ignore
      setSelectedKey(data?.payload?.[0]?.id)
    } finally {
      setTreeLoading(false)
    }
  }

  const queryQualityTasks = async () => {
    try {
      setTableLoading(true)
      const data = await request(`${api.getQualityTask}?pId=${selectedKey}`, {
        method: 'GET'
      })
      // @ts-ignore
      setQualityTasks(data?.payload ?? [])
    } finally {
      setTableLoading(false)
    }
  }

  const handleSaveCfForm = async (form: IClassification) => {
    try {
      setCfLoading(true)
      const url = cfForm.id
        ? api.updateAuditClassification + cfForm.id
        : api.createAuditClassification
      const result = await request(url, {
        method: cfForm.id ? 'PUT' : 'POST',
        data: { ...cfForm, ...form }
      })
      // @ts-ignore
      if (result?.header?.code === 200) {
        setCfVisible(false)
        await queryClassifications()
      }
    } finally {
      setCfLoading(false)
    }
  }

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

  useEffect(() => {
    if (selectedKey) {
      queryQualityTasks()
    }
  }, [selectedKey])

  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
                    className={styles.treePlusNode}
                    onClick={() => {
                      setCfForm({})
                      setCfVisible(true)
                    }}
                  >
                    <Icon type="plus" />
                  </div>
                </div>
                <div className={styles.treeContent}>
                  <Spin spinning={treeLoading}>
                    {renderTree(classifications)}
                  </Spin>
                </div>
              </div>

              <div style={{ flex: 1 }}>
                <div style={{ padding: '0 0 20px' }}>
                  <Button
                    type="primary"
                    icon="plus"
                    onClick={() => {
                      setQtVisible(true)
                      setQtForm(null)
                    }}
                  >
                    新增
                  </Button>
                </div>
                <Table
                  style={{ flex: 1 }}
                  bordered
                  rowKey="id"
                  loading={tableLoading}
                  dataSource={qualityTasks}
                  columns={tableColumns}
                  pagination={false}
                  // onChange={this.tableChange}
                />
              </div>
            </div>
            <br />
          </Box.Body>
        </Box>
      </ContainerBody>
      <ClassificationsFormModal
        visible={cfVisible}
        formView={cfForm}
        onSave={handleSaveCfForm}
        loading={cfLoading}
        onCancel={() => setCfVisible(false)}
      />
      <QualityTaskFormModal
        visible={qtVisible}
        formView={qtForm}
        onSave={handleSaveCfForm}
        loading={qtLoading}
        onCancel={() => setQtVisible(false)}
      />
      <ScheduleFormModal
        visible={scVisible}
        loading={scLoading}
        formView={scForm}
        onSave={undefined}
        onCancel={() => setScVisible(false)}
      />
    </Container>
  )
}
