<template>
  <div class="radius-base">
    <div class="fill-blank radius-base p-t-base">
      <base-form :items="items" :model="model" :label-width="'80px'" size="small">
        <template #form-item-button>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </template>
      </base-form>
    </div>
    <div class="fill-blank radius-base m-t-base p-base chart-info">
      <vue-e-charts v-loading="loading" class="full" :option="totalChartsOption" autoresize></vue-e-charts>
    </div>
    <div class="m-t-base fill-blank radius-base p-base">
      <base-table
        v-loading="loading"
        border
        stripe
        size="small"
        :data="subjectProgressEndList"
        :columns="columns"
        :span-method="tableSpanMethod"
      ></base-table>
    </div>
  </div>
</template>

<script setup lang="ts" name="SubjectProgress">
/** 科目进度 */
import { reactive, ref, computed, watch } from 'vue'
import { minus } from '@/utils/common'
import useFetch from '@/hooks/useFetch'
import useMainStore from '@/store/main'
import VueECharts from 'vue-echarts'
import BaseTable from '@/components/element/BaseTable.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import { ElButton } from 'element-plus'

import type { EChartsOption } from 'echarts'
import type { ExtractApiResponse } from '@/api/api'
import type { EpTableColumn, InstanceTable } from 'global-type'

type SubjectProgress = ExtractArrayValue<ExtractApiResponse<'subjectProgressEnd'>>
const subjectView = ref<any>({
  code: '',
  name: '',
})
const {
  subjectList,
  mainQuestionList,
  groupListWithAll,
  onOptionInit,
  dataModel,
  changeModelValue,
  isExpert,
  isLeader,
} = useOptions(['subject', 'question', 'group'])
const model = reactive<any>({
  // markingGroupNumber: dataModel.group,
  // questionMainNumber: dataModel.question,
  subjectCode: dataModel.subject || '',
})
watch(dataModel, () => {
  model.subjectCode = dataModel.subject || ''
  // model.questionMainNumber = dataModel.question
  // model.markingGroupNumber = dataModel.group
})

const { defineColumn, _ } = useForm()

const OneRow = defineColumn(_, 'row-1', { span: 5 })
const btnRow = defineColumn(_, 'row-1', { span: 2 })

const items = computed<any>(() => [
  OneRow({
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    labelWidth: '46px',
    slot: { options: subjectList.value, onChange: changeModelValue('subject'), disabled: !isExpert.value },
  }),
  // OneRow({
  //   label: '大题',
  //   prop: 'questionMainNumber',
  //   slotType: 'select',
  //   labelWidth: '60px',
  //   slot: {
  //     options: mainQuestionList.value,
  //     onChange: changeModelValue('question'),
  //     disabled: !isExpert.value && !isLeader.value,
  //   },
  // }),

  btnRow({
    slotName: 'button',
    labelWidth: '20px',
  }),
])

const mainStore = useMainStore()

const { fetch: subjectProgressEnd, result: subjectProgressEndList, loading } = useFetch('subjectProgressEnd')

watch(subjectList, () => {
  writeSubjectName()
})

const writeSubjectName = () => {
  let sName = (subjectList.value || []).find((item: any) => item.code == model.subjectCode)?.name
  subjectView.value = {
    code: model.subjectCode,
    name: sName || '',
  }
}

// subjectProgressEnd({ subjectCode: mainStore.myUserInfo?.subjectCode || '' })
const onSearch = () => {
  subjectProgressEnd({ subjectCode: model.subjectCode }).then(() => {
    writeSubjectName()
  })
}
onOptionInit(onSearch)
const getMainName = (row?: SubjectProgress) => {
  const { questionMainName: name, questionMainNumber: number } = row || {}
  return [number, name].filter(Boolean).join('-')
}

const getYAxisData = (field: keyof SubjectProgress | 'name', data?: SubjectProgress[]) => {
  if (!data) {
    return []
  }
  return data.map((v) => {
    if (field === 'name') {
      return getMainName(v)
    }
    return v[field]
  })
}

const totalChartsOption = computed<EChartsOption>(() => {
  return {
    grid: {
      top: 20,
      bottom: -20,
      left: 20,
      right: 30,
      containLabel: true,
    },
    legend: {
      right: 0,
      itemWidth: 14,
      data: ['试卷总量', '已完成', '完成比'],
    },
    yAxis: {
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      inverse: true,
      axisLabel: {
        align: 'right',
        verticalAlign: 'bottom',
      },
      data: getYAxisData('name', subjectProgressEndList?.value),
    },
    xAxis: [
      {
        position: 'top',
        type: 'value',
        splitLine: { show: true },
      },
      {
        position: 'bottom',
        type: 'value',
        show: false,
        axisLabel: {
          formatter: `{value}%`,
        },
        splitLine: { show: false },
      },
    ],
    series: [
      {
        name: '试卷总量',
        type: 'bar',
        barWidth: 11,
        barGap: '-200%',
        itemStyle: {
          color: '#3AD500',
        },
        data: getYAxisData('totalPaper', subjectProgressEndList?.value),
      },
      {
        name: '已完成',
        type: 'bar',
        barWidth: 11,
        barGap: '-200%',
        itemStyle: {
          color: '#0064FF',
        },
        data: getYAxisData('finishCount', subjectProgressEndList?.value),
      },
      {
        name: '完成比',
        type: 'bar',
        barWidth: 44,
        barGap: '-200%',
        showBackground: true,
        xAxisIndex: 1,
        itemStyle: {
          color: 'rgba(0, 186, 151,0.3)',
        },
        label: {
          show: true,
          color: '#444',
          fontSize: 10,
          formatter({ value }) {
            return value > 0 ? `${value}%` : ''
          },
          position: 'insideTopRight',
        },
        data: getYAxisData('finishRate', subjectProgressEndList?.value),
      },
    ],
  }
})

const columns: EpTableColumn<SubjectProgress>[] = [
  {
    label: '科目',
    formatter() {
      // let sName = (subjectList.value || []).find((item: any) => item.code == model.subjectCode)?.name
      // return (
      //   (mainStore.myUserInfo?.subjectCode || model.subjectCode) + '-' + (mainStore.myUserInfo?.subjectName || sName)
      // )
      return subjectView.value.code + '-' + subjectView.value.name
    },
    minWidth: 100,
  },
  { label: '大题', prop: 'questionMainName', minWidth: 80 },
  { label: '试卷总量', prop: 'totalPaper', minWidth: 90 },
  { label: '已完成', prop: 'finishCount', minWidth: 70 },
  {
    label: '完成比',
    prop: 'finishRate',
    minWidth: 70,
    formatter(row) {
      return `${row.finishRate}%`
    },
  },
  {
    label: '待完成',
    minWidth: 90,
    formatter(row) {
      return `${minus(row.totalPaper, row.finishCount)}`
    },
  },
  {
    label: '待完成比',
    minWidth: 90,
    prop: 'totalPaper',
    formatter(row) {
      return `${minus(100, row.finishRate)}%`
    },
  },
  { label: '问题卷待处理', prop: 'todoProblemPaperCount', minWidth: 110 },
  { label: '雷同卷待处理', prop: 'todoSamePaperCount', minWidth: 110 },
  { label: '主观题校验待处理', prop: 'subjectiveUnVerifyPaperCount', minWidth: 140 },
  {
    label: '抽查比例',
    prop: 'checkPaperRate',
    minWidth: 90,
    formatter(row) {
      return `${row.checkPaperRate}%`
    },
  },
  { label: '仲裁卷待处理', prop: 'todoArbitrationPaperCount', minWidth: 110 },
  {
    label: '仲裁率',
    prop: 'arbitrationPaperRate',
    minWidth: 70,
    formatter(row) {
      return `${row.arbitrationPaperRate}%`
    },
  },
]

const tableSpanMethod: InstanceTable['spanMethod'] = (scope) => {
  if (scope.columnIndex === 0) {
    if (scope.rowIndex === 0) {
      return {
        rowspan: subjectProgressEndList.value?.length || 1,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
  return {
    rowspan: 1,
    colspan: 1,
  }
}
</script>

<style scoped lang="scss">
.chart-info {
  height: 260px;
}
</style>
