import React, { useEffect, useState } from 'react'
import { Modal, message, Button, Tabs, Table, Divider, Popconfirm } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { IDataRule, IDataSubject, IRule } from '../types'
import { ColumnProps } from 'antd/lib/table'
import api from 'utils/api'
import request from 'utils/request'
import RuleFormModal from 'containers/DataGovernanceMarkRule/components/RuleFormModal'
import Messages from 'containers/Display/messages'

interface IAuditClassificationFormModalProps {
  visible: boolean
  fromView: IDataSubject
  onCancel: () => void
}

const { TabPane } = Tabs

// @ts-ignore
const enum InspectionType {
  integrity = 'integrity', // 完整性
  uniformity = 'uniformity', // 一致性
  normative = 'normative', // 规范性
  accuracy = 'accuracy' // 准确性
}

export const AuditClassificationFormModal = (
  props: IAuditClassificationFormModalProps
) => {
  const { visible, fromView, onCancel } = props

  const [activeKey, setActiveKey] =
    useState<IDataRule['inspectionType']>('integrity')
  const [tableLoading, setTableLoading] = useState(false)
  const [formVisible, setFormVisible] = useState(false)
  const [formLoading, setFormLoading] = useState(false)
  const [auditClassification, setAuditClassification] = useState<IRule[]>([])
  const [ruleFormView, setRuleFormView] = useState<IDataRule>({})

  const queryDataSubject = async () => {
    try {
      setTableLoading(true)
      const data = await request(
        api.getDataRules + `?subjectId=${fromView.id}`,
        { method: 'GET' }
      )
      // @ts-ignore
      setAuditClassification(data?.payload ?? [])
    } finally {
      setTableLoading(false)
    }
  }

  useEffect(() => {
    // tslint:disable-next-line:no-unused-expression
    visible && queryDataSubject()
  }, [visible])

  const tableColumns: Array<ColumnProps<IRule>> = [
    {
      title: '规则编号',
      dataIndex: 'ruleCode'
    },
    {
      title: '规则名称',
      dataIndex: 'ruleName'
    },
    {
      title: '检测类型',
      dataIndex: 'inspectionType'
    },
    {
      title: '规则描述',
      dataIndex: 'ruleDesc'
    },
    {
      title: '操作',
      render: (_, data) => (
        <>
          <a onClick={() => handleAddEditRule(data)}>编辑</a>
          <Divider type={'vertical'} />
          <Popconfirm
            title={'确定删除？'}
            placement={'bottom'}
            onConfirm={() => handleDeleteTheme(data)}
          >
            <a>删除</a>
          </Popconfirm>
        </>
      )
    }
  ]

  const handleTabChange = (e) => setActiveKey(e)
  const handleParse = (str: string): IDataRule['ruleConfig'] => {
    try {
      return JSON.parse(str)
    } catch (e) {
      console.log(e)
    }
    return {}
  }
  const handleSave = async (form: IDataRule) => {
    try {
      setFormLoading(true)
      const url = ruleFormView?.id
        ? api.updateDataRules + ruleFormView.id
        : api.createDataRules
      console.log(form, url, '===')
      const data = await request(url, {
        method: ruleFormView?.id ? 'PUT' : 'POST',
        data: {
          subjectId: fromView.id,
          inspectionType: activeKey,
          id: ruleFormView.id,
          ...form,
          ruleConfig: JSON.stringify(form.ruleConfig)
        }
      })
      console.log(data)
      // @ts-ignore
      if (data?.header?.code === 200) {
        setFormVisible(false)
        queryDataSubject()
      }
    } finally {
      setFormLoading(false)
    }
  }
  const handleAddEditRule = (data) => {
    setRuleFormView({ ...data, ruleConfig: handleParse(data.ruleConfig) })
    setFormVisible(true)
  }
  const handleDeleteTheme = async (data: IRule) => {
    try {
      setTableLoading(true)
      const result = await request(api.deleteDataSubject + data.id)
      // @ts-ignore
      if (result?.header?.code === 200) {
        message.success({ content: '删除成功' })
        queryDataSubject()
      }
    } finally {
      setTableLoading(false)
    }
  }
  const handleCancel = () => setFormVisible(false)

  return (
    <Modal
      title={'质量稽核规则'}
      visible={visible}
      footer={null}
      onCancel={onCancel}
      width={1000}
      destroyOnClose
    >
      <div style={{ padding: '20px 0 0' }}>
        <Button
          type="primary"
          icon="plus"
          onClick={() => {
            setFormVisible(true)
            // DataSubjectFormVisible(true)
            // DataSubjectForm(null)
          }}
        >
          新增
        </Button>
      </div>
      <Tabs activeKey={activeKey} onChange={handleTabChange}>
        <TabPane tab={'完整性'} key={'integrity'}>
          <Table
            bordered
            rowKey={'id'}
            loading={tableLoading}
            dataSource={auditClassification.filter(
              (o) => o.inspectionType === InspectionType.integrity
            )}
            columns={tableColumns}
            pagination={false}
          />
        </TabPane>
        <TabPane tab="一致性" key={'uniformity'}>
          <Table
            bordered
            rowKey={'id'}
            loading={tableLoading}
            dataSource={auditClassification.filter(
              (o) => o.inspectionType === InspectionType.uniformity
            )}
            columns={tableColumns}
            pagination={false}
          />
        </TabPane>
      </Tabs>
      <RuleFormModal
        visible={formVisible}
        inspectionType={activeKey}
        onCancel={handleCancel}
        loading={formLoading}
        fromView={ruleFormView}
        onSave={handleSave}
      />
    </Modal>
  )
}
