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'
import { RouteComponentProps } from 'react-router'

export default function DataGovernanceAuaitAnalysis(
  props: RouteComponentProps
) {
  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 [detailRange, setDetailRange] = useState<[string, string]>(['', ''])

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

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

    // 规范性
    const normativeCorrect = reports
      .map((item) => item.normativeCorrect ?? 0)
      .reduce((c, n) => c + n, 0)
    const normativeError = reports
      .map((item) => item.normativeError ?? 0)
      .reduce((c, n) => c + n, 0)
    const normativeTotal = normativeError + normativeCorrect

    // 准确性
    const accuracyCorrect = reports
      .map((item) => item.accuracyCorrect ?? 0)
      .reduce((c, n) => c + n, 0)
    const accuracyError = reports
      .map((item) => item.accuracyError ?? 0)
      .reduce((c, n) => c + n, 0)
    const accuracyTotal = accuracyError + accuracyCorrect

    const total =
      integrityTotal + uniformityTotal + normativeTotal + accuracyTotal

    const totalCorrect =
      integrityCorrect + uniformityCorrect + normativeCorrect + accuracyCorrect

    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'
        }
      ]
    }
  ]
  const cloumns = tableColumns.concat({
    title: '操作',
    fixed: 'right',
    width: 50,
    render: (_, data) => (
      <span onClick={() => handleClickDetail(data)}>详情</span>
    )
  })

  const handleClickDetail = (data: IReport) => {
    console.log(data, '~~~~~~')

    setDetailVisible(true)
    setDetailForm(data)
    setDetailRange([
      detailForm?.startTime || time[0].format('YYYY-MM-DD'),
      detailForm?.endTime || time[1].format('YYYY-MM-DD')
    ])
  }

  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 ?? [])

      if (qs.taskId) {
        // @ts-ignore
        const detail = (data?.payload ?? [])?.find(
          (o) => String(o.id) === qs.taskId
        )
        console.log(qs, detail, data?.payload, '-----')

        detail && handleClickDetail(detail)
      }
    } 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={cloumns}
              pagination={false}
            />
            <div style={{ padding: 20 }} />
            <AnalysisReportDetailModal
              visible={detailVisible}
              tableColumns={tableColumns}
              onClose={() => {
                setDetailVisible(false)
                if (qs.taskId) {
                  // @ts-ignore
                  props.history.replace(props.match.url)
                }
              }}
              formView={detailForm}
              dateRange={detailRange}
            />
          </Box.Body>
        </Box>
      </ContainerBody>
    </Container>
  )
}
