import { Button, DatePicker, Drawer, Modal, Spin, Table } from 'antd'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { IReport } from 'containers/DataGovernanceAuaitAnalysis/types'
import { init, EChartOption, ECharts } from 'echarts'
import request from 'utils/request'
import api from 'utils/api'
import moment, { Moment } from 'moment'
import { RangePickerValue } from 'antd/lib/date-picker/interface'
import { ColumnProps } from 'antd/lib/table'

// tslint:disable-next-line:interface-name
export interface AnalysisReportDetailModalProps {
  visible: boolean
  // eslint-disable-next-line no-undef
  formView: Partial<IReport>
  tableColumns: Array<ColumnProps<IReport>>
}

const DEFAULT_COLORS = ['#52c41a', '#fa8c16', '#1890ff', '#722ed1']

export const AnalysisReportDetailModal = ({
  visible,
  formView,
  tableColumns
}: AnalysisReportDetailModalProps) => {
  const lineChartRef = useRef<ECharts>()
  const lineChartElementRef = useRef<HTMLDivElement>()

  const [lineLoading, setLineLoading] = useState(false)
  const [lineReports, setLineReports] = useState<IReport[]>([])
  const [lineDateRange, setLineDateRange] = useState<RangePickerValue>([])

  const [tableReports, setTableReports] = useState<IReport[]>([])
  const [tableLoading, setTableLoading] = useState(false)
  const [tableDateRange, setTableDateRange] = useState<RangePickerValue>([])

  const lineDataSource = useMemo(
    () =>
      lineReports.map((l) => ({
        ...l,
        完整性正确率: Number(l.integrityCorrectProbability ?? '') * 100,
        一致性正确率: Number(l.uniformityCorrectProbability ?? '') * 100,
        规范性正确率: Number(l.normativeCorrectProbability ?? '') * 100,
        准确性正确率: Number(l.accuracyCorrectProbability ?? '') * 100
      })),
    [lineReports]
  )

  const lineOption = useMemo<EChartOption>(
    () => ({
      tooltip: {},
      legend: {
        data: ['完整性正确率', '一致性正确率', '规范性正确率', '准确性正确率']
      },
      xAxis: {
        type: 'category'
      },
      yAxis: {
        type: 'value'
      },
      series: [
        '完整性正确率',
        '一致性正确率',
        '规范性正确率',
        '准确性正确率'
      ].map((o, idx) => ({
        name: o,
        type: 'line',
        smooth: true,
        data: lineDataSource.map((s) => s[o]),
        itemStyle: {
          color: DEFAULT_COLORS[idx]
        }
      }))
    }),
    [lineDataSource]
  )
  const disableDate = (current: Moment) =>
    current &&
    (current < moment(formView?.startTime) ||
      current > moment(formView?.endTime))

  const queryLineReports = async (startTime: string, endTime: string) => {
    try {
      setLineLoading(true)

      const data = await request(
        `${
          api.qualityReportDetail + formView?.cronJobId
        }?startTime=${startTime}&endTime=${endTime}`,
        { method: 'GET' }
      )
      // @ts-ignore
      setLineReports(data.payload)
    } finally {
      setLineLoading(false)
    }
  }
  const queryTableReports = async (startTime: string, endTime: string) => {
    try {
      setTableLoading(true)

      const data = await request(
        `${
          api.qualityReportDetail + formView?.cronJobId
        }?startTime=${startTime}&endTime=${endTime}`,
        { method: 'GET' }
      )
      // @ts-ignore
      setTableReports(data.payload)
    } finally {
      setTableLoading(false)
    }
  }

  useEffect(() => {
    if (lineDateRange?.[0] && lineDateRange?.[1]) {
      // @ts-ignore
      queryLineReports(
        // @ts-ignore
        lineDateRange?.[0]?.format('YYYY-MM-DD'),
        // @ts-ignore
        lineDateRange?.[1]?.format('YYYY-MM-DD')
      )
    }
  }, [lineDateRange])

  useEffect(() => {
    if (tableDateRange?.[0] && tableDateRange?.[1]) {
      // @ts-ignore
      queryTableReports(
        // @ts-ignore
        tableDateRange?.[0]?.format('YYYY-MM-DD'),
        // @ts-ignore
        tableDateRange?.[1]?.format('YYYY-MM-DD')
      )
    }
  }, [tableDateRange])

  useEffect(() => {
    setLineDateRange([
      // @ts-ignore
      formView?.startTime ? moment(formView.startTime) : undefined,
      // @ts-ignore
      formView?.endTime ? moment(formView.endTime) : undefined
    ])
    setTableDateRange([
      // @ts-ignore
      formView?.startTime ? moment(formView.startTime) : undefined,
      // @ts-ignore
      formView?.endTime ? moment(formView.endTime) : undefined
    ])
  }, [formView?.startTime, formView?.endTime])

  useEffect(() => {
    if (formView?.startTime && formView?.endTime) {
      queryLineReports(formView.startTime, formView.endTime)
      queryTableReports(formView.startTime, formView.endTime)
    }
  }, [formView?.startTime, formView?.endTime])

  useEffect(() => {
    if (lineChartElementRef.current) {
      lineChartRef.current = init(lineChartElementRef.current)
      lineChartRef.current.setOption(lineOption)
    }
  }, [lineOption])

  return (
    <Drawer
      placement="bottom"
      visible={visible}
      height="100%"
      destroyOnClose
      title="质量任务结果"
    >
      <div>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            margin: '10px 0'
          }}
        >
          <h4 style={{ borderLeft: '2px solid #1890ff', paddingLeft: 14 }}>
            数据质量趋势
          </h4>
          <div>
            <DatePicker.RangePicker
              value={lineDateRange}
              disabledDate={disableDate}
              onChange={(range) => setLineDateRange(range)}
              format="YYYY-MM-DD"
            />
            <span style={{ padding: 4 }} />
            <Button>查询</Button>
          </div>
        </div>
        <Spin spinning={lineLoading}>
          <div style={{ height: 400 }} ref={lineChartElementRef} />
        </Spin>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            margin: '10px 0'
          }}
        >
          <h4 style={{ borderLeft: '2px solid #1890ff', paddingLeft: 14 }}>
            数据质量历史
          </h4>
          <div>
            <DatePicker.RangePicker
              value={tableDateRange}
              disabledDate={disableDate}
              onChange={(range) => setTableDateRange(range)}
              format="YYYY-MM-DD"
            />
            <span style={{ padding: 4 }} />
            <Button>查询</Button>
          </div>
        </div>
        <Table
          style={{ flex: 1 }}
          bordered
          rowKey="id"
          loading={tableLoading}
          dataSource={tableReports}
          columns={tableColumns}
          pagination={false}
          // onChange={this.tableChange}
        />
      </div>
    </Drawer>
  )
}
