<template>
  <div class="flex direction-column full personnel-statistics-view">
    <div class="p-l-base p-r-base p-t-medium-base fill-blank filter-form" style="padding-bottom: 10px">
      <base-form size="small" :label-width="'88px'" :disabled="loading" :model="model" :items="items">
        <template #form-item-button-group>
          <el-button :loading="loading" type="primary" @click="onSearch">查询</el-button>
          <el-button
            v-permBtn="'analysis-personnel_statistics_export'"
            :loading="exporting"
            type="primary"
            custom-1
            @click="onExport"
            >导出</el-button
          >
        </template>
        <template #form-item-columns-setting>
          <div class="setting-box">
            <el-tooltip effect="dark" content="表头配置" placement="bottom">
              <el-icon color="#333" :size="24" class="setting-icon" @click="showColumnsSetting = true">
                <setting />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
      </base-form>
    </div>
    <div v-loading="loading" class="flex-1 p-small">
      <component
        :is="fetchModel.expand ? StatisticsPersonnel : StatisticsGroup"
        :data="data"
        :params="fetchModel"
        :filter-columns="filterColumns"
        :result="result"
      ></component>
    </div>
    <base-dialog
      v-model="showColumnsSetting"
      class="columns-setting-dialog"
      title="表格列展示配置"
      center
      width="780px"
      @open="dialogOpen"
      @close="dialogClose"
    >
      <el-checkbox-group v-model="checkedList">
        <div v-for="item in checkboxList" :key="item.value" class="check-item">
          <el-checkbox :label="item.value">{{ item.content }}</el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <confirm-button right @confirm="sure" @cancel="cancel"></confirm-button>
      </template>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="AnalysisPersonnelStatistics">
/** 人员数据统计 */
import { computed, onMounted, ref, watch, watchEffect, onBeforeUnmount, onDeactivated } from 'vue'
import { omit } from 'lodash-es'
import { ElButton, ElIcon, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import useFetch from '@/hooks/useFetch'
import useVW from '@/hooks/useVW'
import useStatisticsFilter from './hooks/useStatisticsFilter'
import useMainStore from '@/store/main'
import StatisticsGroup from './components/StatisticsGroup.vue'
import StatisticsPersonnel from './components/StatisticsPersonnel.vue'
import { Setting } from '@element-plus/icons-vue'
import BaseDialog from '@/components/element/BaseDialog.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import { cloneDeep } from 'lodash-es'
import { useIntervalFn } from '@vueuse/core'
import { getTodayByDay } from '@/utils/common'
import { useRoute } from 'vue-router'
import { getUserConfigByType, setUserConfigByType } from '@/utils/common'
import type { ExtractApiResponse } from '@/api/api'
const route = useRoute()
console.log('route', route)
const { model, fetchModel, items, onOptionInit, groupListWithAll, changeModelValue } = useStatisticsFilter()
const showColumnsSetting = ref(false)
function cancel() {
  showColumnsSetting.value = false
}

let searchMarkerId = ref<any>('')
let searchOnline = ref<any>('')

const columnMap: any = {
  markingGroupNumber: '小组',
  markerName: '评卷员',
  markingPaperCount: '评卷份数',
  avg: '平均分',
  xyRelate: '相关系数',
  std: '标准差',
  integration: '综合系数',
  markDayCount: '当日可阅',
  todoMarkDayCount: '剩余可阅',
  objectiveZero: '客观题0分量',
  objectiveAvg: '客观平均分',
  objectiveStd: '客观标准差',
  reMarkUnConfirmCount: '重评/待确认',
  checkCount: '抽查量',
  checkCorrectCount: '抽查改正量',
  scoreTop: '近5分钟最高分',
  scoreLow: '近5分钟最低分',
  objSubRate: '近5分钟客主比',
  objSubAvgRate: '平均客主比',
  online: '在线',
  markingStatus: '状态',
  markingRate: '速度',
}
const labelList = Object.keys(columnMap)
let columnsByLocal = getUserConfigByType('personnelStatisticsColumns')
const checkedList = columnsByLocal ? ref(columnsByLocal) : ref(JSON.parse(JSON.stringify(labelList)))
const checkboxList = ref(labelList.map((item: any) => ({ value: item, content: columnMap[item] })))
const filterColumns = ref(JSON.parse(JSON.stringify(checkedList.value)))
let initCheckedList: any = []
function dialogOpen() {
  initCheckedList = checkedList.value
}
function dialogClose() {
  checkedList.value = initCheckedList
}
function sure() {
  filterColumns.value = checkedList.value
  initCheckedList = checkedList.value
  showColumnsSetting.value = false
  setUserConfigByType('personnelStatisticsColumns', checkedList.value)
}
const mainStore = useMainStore()
const deputyHasInit = ref(false)
watch(groupListWithAll, () => {
  if (mainStore.myUserInfo && mainStore.myUserInfo.role === 'DEPUTY') {
    setTimeout(() => {
      deputyHasInit.value = true
      changeModelValue('group')([mainStore.myUserInfo?.markingGroupNumber])
      onSearch()
    }, 0)
  }
})

onMounted(() => {
  if (
    (mainStore.myUserInfo && mainStore.myUserInfo.role === 'DEPUTY') ||
    getUserConfigByType('expandByPerson') == '1'
  ) {
    model.expand = ['按人员展开']
  }
  if (getUserConfigByType('includeLeaderScore') == '1') {
    model.hasGroupLeaderScore = ['true']
  }
})

const { fetch, result: allResult, loading } = useFetch('getStatisticsByGroup')
const result = computed(() => {
  return (allResult?.value || []).filter((item) => {
    if (
      !fetchModel.value.markingGroupNumber ||
      fetchModel.value.markingGroupNumber?.length === 0 ||
      item.markingGroupNumber == 0 ||
      (Array.isArray(fetchModel.value.markingGroupNumber) && fetchModel.value.markingGroupNumber.includes(undefined))
    ) {
      return item
    } else {
      return fetchModel.value.markingGroupNumber.includes(item.markingGroupNumber)
    }
  })
})

const data = computed<ExtractApiResponse<'getStatisticsByGroup'>>(() => {
  let arr = cloneDeep(result?.value || [])
  // let groupList = result?.value?.slice(0) || []
  let groupList = arr
    .map((groupItem: any) => {
      if (groupItem.markingGroupNumber === 0) {
        return groupItem
      } else {
        if (groupItem.markerDetails && groupItem.markerDetails.length) {
          groupItem.markerDetails = groupItem.markerDetails.filter((marker: any) => {
            return (
              (searchMarkerId.value === '' || marker.markerId === searchMarkerId.value) &&
              (searchOnline.value === '' || marker.online === searchOnline.value)
            )
          })
        }
        // return groupItem.markerDetails && groupItem.markerDetails.length ? groupItem : null
        return groupItem
      }
    })
    .filter((v: any) => !!v)
  const totalIndex = groupList.findIndex((v) => v.markingGroupNumber === 0)
  // let expandData = groupList
  //   .filter((v) => v.markingGroupNumber !== 0)
  //   .reduce((total, cur) => {
  //     total.push(...(cur.markerDetails || []))
  //     return total
  //   }, [] as ExtractApiResponse<'getStatisticsByGroup'>)
  //   .sort((a: any, b: any) => a.markerId - b.markerId)
  //   .concat(totalIndex >= 0 ? groupList[totalIndex] : [])
  // let topGroupRow = groupList.find((v) => v.markingGroupNumber == model.markingGroupNumber)
  // if (model.markingGroupNumber && topGroupRow) {
  //   expandData.unshift({ ...topGroupRow, isGroupTotalRow: true })
  // }

  let expandData = groupList
    .filter((v) => v.markingGroupNumber !== 0)
    .reduce((total, cur) => {
      total.push({ ...cur, isGroupTotalRow: true })
      let details = cur.markerDetails || []
      details.sort((a: any, b: any) => a.markerId - b.markerId)
      total.push(...details)
      return total
    }, [] as ExtractApiResponse<'getStatisticsByGroup'>)
    .concat(totalIndex >= 0 ? groupList[totalIndex] : [])

  return fetchModel.value.expand
    ? expandData
    : groupList.sort((a: any, b: any) => (a.markingGroupNumber as number) - (b.markingGroupNumber as number))
})

/** 刷新按钮 */
function onSearch() {
  setTimeout(() => {
    if (mainStore.myUserInfo?.role !== 'DEPUTY') {
      deputyHasInit.value = true
    }
    searchMarkerId.value = model.markerId
    searchOnline.value = model.online
    if (deputyHasInit.value) {
      // let params: any = { ...omit(fetchModel.value, 'expand', 'markerId', 'online'), markingGroupNumber: '' }
      let params: any = {
        ...omit(fetchModel.value, 'expand', 'markerId', 'online', 'markingGroupNumber'),
        markingGroupNumbers: fetchModel.value.markingGroupNumber.filter(Boolean),
      }
      if (fetchModel.value.curDay == 'notIncludeCurDay') {
        params.curDay = ''
        params.includeCurDay = false
      }
      fetch(params)
    }
  }, 1)
}

onOptionInit(onSearch)
// watch([() => fetchModel.value.markingGroupNumber], () => {
//   onSearch()
// })
const { fetch: exportStatisticsByGroup, loading: exporting } = useFetch('exportStatisticsByGroup', 'get')
/**导出 */
function onExport() {
  let params: any = {
    ...omit(fetchModel.value, 'expand', 'markingGroupNumber'),
    markingGroupNumbers: fetchModel.value.markingGroupNumber.filter(Boolean),
    showMarker: fetchModel.value.expand,
  }
  if (fetchModel.value.curDay == 'notIncludeCurDay') {
    params.curDay = ''
    params.includeCurDay = false
  }
  exportStatisticsByGroup(params)
  //
  // exportStatisticsByGroup(omit(fetchModel.value, 'expand'))
}

const { pause, isActive, resume } = useIntervalFn(onSearch, 30000, { immediate: false })
watchEffect(() => {
  //如果是小组长登录，且时间选择为当天，则开启定时器，30秒刷一次，否则停掉定时器
  if (
    mainStore.myUserInfo &&
    mainStore.myUserInfo.role === 'DEPUTY' &&
    model.curDay == getTodayByDay() &&
    !isActive.value
  ) {
    if (route.path === '/analysis/personnel-statistics') {
      resume()
    }
  } else {
    pause()
  }
})
onBeforeUnmount(() => {
  pause()
})
onDeactivated(() => {
  pause()
})
</script>

<style scoped lang="scss">
.personnel-statistics-view {
  .check-item {
    width: 146px;
    float: left;
  }
  .filter-form {
    border-bottom: $OnePixelLine;
  }
  :deep(.el-table__header .el-table__cell > .cell) {
    padding: 0;
    .caret-wrapper {
      width: 16px;
      .sort-caret {
        left: 4px;
      }
    }
  }
  :deep(.el-table__body .el-table__cell > .cell) {
    padding: 0 5px;
  }
  :deep(.setting-box) {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 15px;
    .setting-icon {
      cursor: pointer;
      font-weight: bold;
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
  :deep(.el-form-item--small) {
    margin-bottom: 10px;
  }
}
</style>
