import React, { useEffect, useMemo, useState } from 'react'
import Helmet from 'react-helmet'
import Container, { ContainerBody } from 'components/Container'
import Box from 'components/Box'
import { Button, DatePicker, message, Progress, Select, Table } from 'antd'
import { ColumnProps } from 'antd/lib/table'
import { IReport } from 'containers/DataGovernanceAuaitAnalysis/types'
import api from 'utils/api'
import request from 'utils/request'
import styles from './index.less'
import { AnalysisReportDetailModal } from 'containers/DataGovernanceAuaitAnalysis/AnalysisReportDetailModal'
import { IClassification } from 'containers/DataGovernanceQualityAudit/types'
import moment, { Moment } from 'moment'
import * as querystring from 'querystring'

export default function DataGovernanceAuaitAnalysis(props: {
  location: Location
}) {
  const qs: any = querystring.decode(
    props?.location?.search?.replace('?', '') ?? ''
  )

  const [tableLoading, setTableLoading] = useState(false)
  const [detailVisible, setDetailVisible] = useState(false)
  const [detailForm, setDetailForm] = useState<IReport>()

  const [reports, setReports] = useState<IReport[]>([])

  const [classifications, setClassifications] = useState<IClassification[]>([])
  const [systemId, setSystemId] = useState<number>(
    qs.systemId ? Number(qs.systemId) : null
  )
  const [time, setTime] = useState<[Moment, Moment]>([
    qs.starTime ? moment(qs.starTime) : moment(),
    qs.endTime ? moment(qs.endTime) : moment()
  ])

  const workbench = useMemo(() => {
    const total = reports
      .map(
        (item) =>
          item.accuracyCorrect ??
          item.accuracyError ??
          item.integrityCorrect ??
          item.integrityError ??
          item.normativeCorrect ??
          item.normativeError ??
          item.uniformityCorrect ??
          item.uniformityError ??
          0
      )
      .reduce((c, n) => c + n, 0)

    const totalCorrect = reports
      .map(
        (item) =>
          item.accuracyCorrect ??
          item.integrityCorrect ??
          item.normativeCorrect ??
          item.uniformityCorrect ??
          0
      )
      .reduce((c, n) => c + n, 0)

    // 完整性
    const integrityCorrect = reports
      .map((item) => item.integrityCorrect ?? 0)
      .reduce((c, n) => c + n, 0)
    const integrityTotal = reports
      .map((item) => item.integrityCorrect ?? item.integrityError)
      .reduce((c, n) => c + n, 0)

    // 一致性
    const uniformityCorrect = reports
      .map((item) => item.uniformityCorrect ?? 0)
      .reduce((c, n) => c + n, 0)
    const uniformityTotal = reports
      .map((item) => item.uniformityCorrect ?? item.uniformityError)
      .reduce((c, n) => c + n, 0)

    // 规范性
    const normativeCorrect = reports
      .map((item) => item.normativeCorrect ?? 0)
      .reduce((c, n) => c + n, 0)
    const normativeTotal = reports
      .map((item) => item.normativeCorrect ?? item.normativeError)
      .reduce((c, n) => c + n, 0)
    // 准确性
    const accuracyCorrect = reports
      .map((item) => item.accuracyCorrect ?? 0)
      .reduce((c, n) => c + n, 0)
    const accuracyTotal = reports
      .map((item) => item.accuracyCorrect ?? item.accuracyError)
      .reduce((c, n) => c + n, 0)
    return [
      {
        title: '总概率',
        rateLabel: '正确率',
        rateValue: ((totalCorrect / total || 0) * 100).toFixed(2) ?? '',
        countLabel: '正确数量',
        countValue: totalCorrect ?? 0,
        totalLabel: '总数据量',
        totalValue: total ?? 0,
        color: '#1890ff'
      },
      {
        title: '完整性',
        rateLabel: '正确率',
        rateValue:
          ((integrityCorrect / integrityTotal || 0) * 100).toFixed(2) ?? '',
        countLabel: '正确数量',
        countValue: integrityCorrect,
        totalLabel: '总数据量',
        totalValue: integrityTotal,
        color: '#52c41a'
      },
      {
        title: '一致性',
        rateLabel: '正确率',
        rateValue:
          ((uniformityCorrect / uniformityTotal || 0) * 100).toFixed(2) ?? '',
        countLabel: '正确数量',
        countValue: uniformityCorrect,
        totalLabel: '总数据量',
        totalValue: uniformityTotal,
        color: '#fa8c16'
      },
      {
        title: '规范性',
        rateLabel: '正确率',
        rateValue:
          ((normativeCorrect / normativeTotal || 0) * 100).toFixed(2) ?? '',
        countLabel: '正确数量',
        countValue: normativeCorrect,
        totalLabel: '总数据量',
        totalValue: normativeTotal,
        color: '#1890ff'
      },
      {
        title: '准确性',
        rateLabel: '正确率',
        rateValue:
          ((accuracyCorrect / accuracyTotal || 0) * 100).toFixed(2) ?? '',
        countLabel: '正确数量',
        countValue: accuracyCorrect,
        totalLabel: '总数据量',
        totalValue: accuracyTotal,
        color: '#722ed1'
      }
    ]
  }, [reports])
  const tableColumns: Array<ColumnProps<IReport>> = [
    {
      title: '任务名称',
      dataIndex: 'taskName'
    },
    {
      title: '稽查时间',
      dataIndex: 'auditorTime'
    },
    {
      title: '系统名称',
      dataIndex: 'typeName'
    },
    {
      title: '元数据名称',
      dataIndex: 'metadataName'
    },
    {
      title: '完整性',
      children: [
        {
          title: '正确数量',
          dataIndex: 'integrityCorrect'
        },
        {
          title: '错误数量',
          dataIndex: 'integrityError'
        },
        {
          title: '正确率',
          dataIndex: 'integrityCorrectProbability'
        },
        {
          title: '错误率',
          dataIndex: 'integrityErrorProbability'
        }
      ]
    },
    {
      title: '一致性',
      children: [
        {
          title: '正确数量',
          dataIndex: 'uniformityCorrect'
        },
        {
          title: '错误数量',
          dataIndex: 'uniformityError'
        },
        {
          title: '正确率',
          dataIndex: 'uniformityCorrectProbability'
        },
        {
          title: '错误率',
          dataIndex: 'uniformityErrorProbability'
        }
      ]
    },
    {
      title: '规范性',
      children: [
        {
          title: '正确数量',
          dataIndex: 'normativeCorrect'
        },
        {
          title: '错误数量',
          dataIndex: 'normativeError'
        },
        {
          title: '正确率',
          dataIndex: 'normativeCorrectProbability'
        },
        {
          title: '错误率',
          dataIndex: 'normativeErrorProbability'
        }
      ]
    },
    {
      title: '准确性',
      children: [
        {
          title: '正确数量',
          dataIndex: 'accuracyCorrect'
        },
        {
          title: '错误数量',
          dataIndex: 'accuracyError'
        },
        {
          title: '正确率',
          dataIndex: 'accuracyCorrectProbability'
        },
        {
          title: '错误率',
          dataIndex: 'accuracyErrorProbability'
        }
      ]
    },
    {
      title: '操作',
      fixed: 'right',
      width: 50,
      render: (_, data) => (
        <span
          onClick={() => {
            setDetailVisible(true)
            setDetailForm(data)
          }}
        >
          详情
        </span>
      )
    }
  ]

  const queryReports = async function(id?: number) {
    const sysId = id || systemId
    if (!sysId || !time) {
      return
    }
    try {
      setTableLoading(true)
      const selfTime = time.map((t) => t.format('YYYY-MM-DD'))
      const data = await request(
        `${api.qualityReport}?systemId=${sysId}&starTime=${selfTime[0]}&endTime=${selfTime[1]}`,
        {
          method: 'GET'
        }
      )
      // @ts-ignore
      setReports(data?.payload ?? [])
    } finally {
      setTableLoading(false)
    }
  }

  const querySystem = async() => {
    try {
      setTableLoading(true)
      const data = await request(`${api.getAuditClassification}`, {
        method: 'GET'
      })
      // @ts-ignore
      setClassifications(data?.payload ?? [])
      // @ts-ignore
      if (!systemId) {
        setSystemId(data?.payload?.[0].id)
      }
      // @ts-ignore
      queryReports(systemId || data?.payload?.[0].id)
    } finally {
      setTableLoading(false)
    }
  }

  const handleQuery = () => {
    if (!systemId || !time) {
      message.info({ content: '请输入主题或时间' })
      return
    }
    queryReports()
  }
  useEffect(() => {
    querySystem()
  }, [])

  return (
    <Container>
      <Helmet title="稽核分析" />
      <ContainerBody>
        <Box>
          <Box.Header>
            <Box.Title>稽核分析</Box.Title>
          </Box.Header>
          <div style={{ padding: 20 }} />
          <Box.Body>
            <div className={styles['audit-analysiss-search-content']}>
              <div>
                <span>系统选择：</span>
                <Select
                  value={systemId}
                  style={{ width: 200 }}
                  onChange={(e) => setSystemId(e)}
                >
                  {classifications.map((c) => (
                    <Select.Option key={c.id} value={c.id}>
                      {c.name}
                    </Select.Option>
                  ))}
                </Select>
              </div>
              <div>
                <span>时间选择：</span>
                <DatePicker.RangePicker
                  value={time}
                  onChange={(e) => setTime(e)}
                  format="YYYY-MM-DD"
                />
              </div>
              <Button onClick={handleQuery}>查询</Button>
            </div>

            <div className={styles['audit-analysiss-card-content']}>
              {workbench?.map((item, idx) => (
                <div
                  key={item.title}
                  className={styles['audit-analysiss-card-item']}
                >
                  <div className={styles['audit-analysiss-card-item-title']}>
                    {item.title}
                  </div>
                  <div className={styles['audit-analysiss-card-item-rate']}>
                    <div
                      className={styles['audit-analysiss-card-item-rate-label']}
                    >
                      <span>正确率</span>
                      <span>{item.rateValue ?? '-'}%</span>
                    </div>
                    <Progress
                      showInfo={false}
                      strokeColor={item.color}
                      percent={Number(item.rateValue ?? 0)}
                    />
                  </div>
                  <div className={styles['audit-analysiss-card-item-number']}>
                    <div
                      className={
                        styles['audit-analysiss-card-item-number-count']
                      }
                    >
                      <span>正确数量</span>
                      <span>{item.countValue ?? '-'}</span>
                    </div>

                    <div
                      className={
                        styles['audit-analysiss-card-item-number-total']
                      }
                    >
                      <span>总数据量</span>
                      <span>{item.totalValue ?? '-'}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <Table
              style={{ flex: 1 }}
              bordered
              rowKey="id"
              loading={tableLoading}
              dataSource={reports}
              columns={tableColumns}
              pagination={false}
            />
            <div style={{ padding: 20 }} />
            <AnalysisReportDetailModal
              visible={detailVisible}
              tableColumns={tableColumns}
              formView={detailForm}
            />
          </Box.Body>
        </Box>
      </ContainerBody>
    </Container>
  )
}
