<template>
  <div class="flex direction-column full analysis-monitor-view">
    <div class="p-l-base p-t-medium-base fill-blank">
      <base-form :disabled="loading" size="small" :label-width="useVW(60)" :model="model" :items="formItems">
        <template #form-item-operation>
          <el-button :loading="loading" type="primary" @click="onRefresh">刷新</el-button>
        </template>
      </base-form>
    </div>
    <div class="flex-1 p-base scroll-y-auto">
      <div class="flex justify-around data-card-view">
        <div
          v-for="card in cards"
          :key="card.dataField"
          class="flex direction-column radius-base full fill-blank data-card"
        >
          <div class="p-base card-title">{{ card.title }}</div>
          <div class="p-l-extra-base p-r-mini p-b-extra-small flex-1 overflow-hidden">
            <base-table
              size="small"
              height="100%"
              :columns="getColumns(card.valueLabel)"
              :data="sortableResult[card.dataField]"
            >
              <template #empty>
                <empty :image-size="100"></empty>
              </template>
            </base-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="Statistics">
/** 决策分析-统计 */
import { computed, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton } from 'element-plus'
import { omit } from 'lodash-es'
import BaseTable from '@/components/element/BaseTable.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import Empty from '@/components/common/Empty.vue'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import useVW from '@/hooks/useVW'

import type { EpTableColumn, EpFormItem } from 'global-type'
import type { ExtractApiParams, ExtractApiResponse } from '@/api/api'

const { push } = useRouter()

const { subjectList, mainQuestionList, groupListWithAll, dataModel, changeModelValue, onOptionInit } = useOptions([
  'subject',
  'question',
  'group',
])

const model = reactive<
  Omit<ExtractApiParams<'getStatistics'>, 'markingGroupNumbers'> & {
    time: string[] | null
    markingGroupNumbers?: number
  }
>({
  subjectCode: dataModel.subject || '',
  questionMainNumber: dataModel.question,
  markingGroupNumbers: dataModel.group,
  time: null,
})

const fetchModel = computed<ExtractApiParams<'getStatistics'>>(() => {
  return Object.assign(omit(model, 'time'), {
    startTime: model.time?.[0],
    endTime: model.time?.[1],
    markingGroupNumbers:
      typeof model.markingGroupNumbers === 'number' ? [model.markingGroupNumbers] : model.markingGroupNumbers,
  })
})

const { defineColumn, _ } = useForm()

watch(dataModel, () => {
  model.subjectCode = dataModel.subject
  model.questionMainNumber = dataModel.question
  model.markingGroupNumbers = dataModel.group
})

const OneRowSpan4 = defineColumn(_, 'row-1', { span: 4 })
const OneRowSpan6 = defineColumn(_, 'row-1', { span: 6 })

const formItems = computed<EpFormItem[]>(() => [
  OneRowSpan4({
    label: '科目',
    slotType: 'select',
    prop: 'subjectCode',
    labelWidth: useVW(52),
    slot: {
      options: subjectList.value,
      onChange: changeModelValue('subject'),
      disabled: true,
    },
  }),
  OneRowSpan4({
    label: '大题',
    slotType: 'select',
    prop: 'questionMainNumber',
    slot: {
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: true,
    },
  }),
  OneRowSpan4({
    label: '小组',
    slotType: 'select',
    prop: 'markingGroupNumbers',
    slot: {
      options: groupListWithAll.value,
      onChange: changeModelValue('group'),
    },
  }),
  OneRowSpan6({
    label: '时间',
    slotType: 'dateTime',
    prop: 'time',
    slot: {
      clearable: true,
      type: 'datetimerange',
      valueFormat: 'YYYYMMDDHHmmss',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
    },
  }),
  OneRowSpan4({
    labelWidth: useVW(20),
    slotName: 'operation',
  }),
])

interface Card {
  dataField: string
  title: string
  valueLabel: string
  hasAll: boolean
}

const cards: Card[] = [
  {
    dataField: 'totalPaperList',
    title: '评卷份数',
    valueLabel: '份数',
    hasAll: true,
  },
  {
    dataField: 'xyRelateList',
    title: '相关系数',
    valueLabel: '相关系数',
    hasAll: true,
  },
  {
    dataField: 'avgList',
    title: '平均分',
    valueLabel: '平均分',
    hasAll: true,
  },
  {
    dataField: 'stdList',
    title: '标准差',
    valueLabel: '标准差',
    hasAll: true,
  },
  {
    dataField: 'scoreTopLowList',
    title: '近5分钟最高最低分',
    valueLabel: '分数',
    hasAll: false,
  },
  {
    dataField: 'objSubRateList',
    title: '近5分钟客主比',
    valueLabel: '最高',
    hasAll: false,
  },
  {
    dataField: 'objSubAvgRateList',
    title: '平均客主比',
    valueLabel: '平均最高',
    hasAll: false,
  },
  {
    dataField: 'integrationList',
    title: '综合',
    valueLabel: '综合指数',
    hasAll: false,
  },
]

/** 跳转抽查详情 */
const viewMarkDetail = (row: ExtractArrayValue<ExtractRecordValue<ExtractApiResponse<'getStatistics'>>>) => {
  push({
    name: 'AnalysisViewMarked',
    params: {
      markerId: row.markerId,
    },
    query: {
      markerName: row.markerName,
    },
  })
}

const getColumns = (
  valueLabel: string
): EpTableColumn<ExtractArrayValue<ExtractRecordValue<ExtractApiResponse<'getStatistics'>>>>[] => {
  return [
    {
      label: '老师ID',
      formatter(row) {
        return row.markerId === 0 ? (
          '全体'
        ) : (
          <ElButton type="primary" link onClick={() => viewMarkDetail(row)}>
            {row.markerName}
          </ElButton>
        )
      },
    },
    { label: valueLabel, prop: 'value', align: 'right' },
  ]
}

const { fetch, result, loading } = useFetch('getStatistics')

const sortableResult = computed<typeof result.value>(() => {
  if (!result.value) return {}
  return cards.reduce((final, { dataField, hasAll }) => {
    let resultData = result.value[dataField]?.filter((v) => hasAll || v.markerId) || []
    if (dataField === 'scoreTopLowList') {
      const scoreTopList = result.value?.['scoreTopList']?.filter((v) => hasAll || v.markerId) || []
      const scoreLowList = result.value?.['scoreLowList']?.filter((v) => hasAll || v.markerId) || []
      resultData = scoreTopList
        .concat(scoreLowList)
        ?.filter((d, i, arr) => d && i === arr.findIndex((v) => v.markerId === d.markerId))
    }
    const arr = [...resultData]
    const totalIndex = arr.findIndex((v) => v.markerId === 0)
    if (totalIndex >= 0) {
      const [total] = arr.splice(totalIndex, 1)
      total && arr.unshift(total)
    }
    final[dataField] = arr
    return final
  }, {} as typeof result.value)
})

const onRefresh = () => {
  fetch(fetchModel.value)
}

onOptionInit(onRefresh)
</script>

<style scoped lang="scss">
.analysis-monitor-view {
  .data-card-view {
    flex-wrap: wrap;
    align-content: flex-start;
    .data-card {
      width: 347px;
      height: 337px;
      padding-top: 2px;
      margin-bottom: $ExtraSmallGapSpace;
    }
  }

  .card-title {
    color: $BlockTitleColor;
    font-size: $BaseFont;
    line-height: 1;
  }

  ::v-deep(.el-table) {
    .el-table__body-wrapper {
      .el-table__body {
        .el-table__cell {
          padding: 4px 0;
        }
      }
    }
  }
}
</style>
