/* eslint-disable space-before-function-paren */
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'
import { RouteComponentProps, withRouter } from 'react-router-dom'

function DataGovernanceQualityAudit(
  props: RouteComponentProps<{ projectId: string }>
) {
  const { history, match } = props

  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] = useState<IClassification>({})

  const tableColumns: Array<ColumnProps<IQualityTask>> = [
    {
      title: '任务名称',
      dataIndex: 'taskName'
    },
    {
      title: '元数据名称',
      dataIndex: 'metadataName'
    },
    {
      title: '稽核字段个数',
      dataIndex: 'auditorCount'
    },
    {
      title: '操作',
      render: (_, data) => (
        <>
          <a
            onClick={() => {
              setQtVisible(true)
              setQtForm(data)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item
                  key="00"
                  onClick={() => {
                    // eslint-disable-next-line react/prop-types
                    history.push(
                      // eslint-disable-next-line react/prop-types
                      `/project/${match.params.projectId}/dataGovernance/auditAnalysiss?systemId=${data.pId}&starTime=${data.startTime}&endTime=${data.endTime}&taskId=${data.id}`
                    )
                  }}
                >
                  稽查历史
                </Menu.Item>
                <Menu.Item
                  key="0"
                  onClick={() => {
                    setQtForm(data)
                    setScVisible(true)
                  }}
                >
                  设置调度
                </Menu.Item>
                <Menu.Item key="1">
                  <Popconfirm
                    title="确定立即稽查吗？"
                    placement="bottom"
                    onConfirm={() => handleSetDispatchRightNow(data)}
                  >
                    <a>立即稽查</a>
                  </Popconfirm>
                </Menu.Item>
                <Menu.Item key="3">
                  <Popconfirm
                    title="确定删除？"
                    placement="bottom"
                    onConfirm={() => handleDeleteTask(data.id)}
                  >
                    <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.id}`, {
        method: 'GET'
      }).catch((err) => {
        if (err?.response?.data?.header?.msg) {
          message.error({ content: err?.response?.data?.header?.msg })
        }
      })
      // @ts-ignore
      if (result?.header?.code === 200) {
        message.success({ content: '立即稽核完成' })
      }
    } finally {
      setTableLoading(false)
    }
  }

  const handleDispatch = async (form) => {
    try {
      setSCLoading(true)
      const result = await request(`${api.setDispatch}${qtForm.id}`, {
        method: 'PUT',
        data: {
          // @ts-ignore
          projectId: match.params?.projectId,
          name: qtForm.taskName,
          // taskName: qtForm.taskName,
          cronExpression: form.cronExpression,
          startDate: form.startDate[0].format('YYYY-MM-DD hh:mm:ss'),
          endDate: form.startDate[1].format('YYYY-MM-DD hh:mm:ss'),
          periodUnit: form.periodUnit,
          jobStatus: form.jobStatus ? 'started' : 'new',
          jobType: 'auditor'
        }
      })
      // @ts-ignore
      if (result.header.code === 200) {
        setScVisible(false)
        message.success({ content: '设置调度成功' })
        queryQualityTasks()
      }
    } catch (err) {
      if (err?.response?.data?.header?.msg) {
        message.error({ content: err?.response?.data?.header?.msg })
      }
      console.log(err)
    } finally {
      setSCLoading(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.getQualityTaskByPid}?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)
    }
  }

  const handleSaveQtForm = async (view) => {
    try {
      setQtLoading(true)
      const url = qtForm?.id
        ? api.updateQualityTask + qtForm?.id
        : api.createQualityTask
      const result = await request(url, {
        method: qtForm?.id ? 'PUT' : 'POST',
        data: { ...qtForm, ...view }
      })
      // @ts-ignore
      if (result?.header?.code === 200) {
        setQtVisible(false)
        await queryQualityTasks()
      }
    } finally {
      setQtLoading(false)
    }
  }

  const handleDeleteTask = async (id: number) => {
    try {
      setTableLoading(true)
      const data = await request(`${api.deleteQualityTask}${id}`, {
        method: 'DELETE'
      })
      // @ts-ignore
      if (data.header.code === 200) {
        message.success({ content: '删除成功' })
        queryQualityTasks()
      }
    } finally {
      setTableLoading(false)
    }
  }

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

  useEffect(() => {
    if (selectedKey) {
      queryQualityTasks()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [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
        pId={selectedKey}
        visible={qtVisible}
        formView={qtForm}
        onSave={handleSaveQtForm}
        loading={qtLoading}
        onCancel={() => {
          setQtVisible(false)
          setQtForm(null)
        }}
      />
      <ScheduleFormModal
        visible={scVisible}
        loading={scLoading}
        formView={qtForm}
        onSave={handleDispatch}
        onCancel={() => setScVisible(false)}
      />
    </Container>
  )
}

export default withRouter(DataGovernanceQualityAudit)
