<template>
  <div class="container">
    <save-form inline :model="search" @submit="FetchList" @reset="reset" saveKey="/main/main/abnormal">
      <el-form-item prop="organId">
        <el-select
          clearable
          filterable
          v-model="search.organId"
          placeholder="请选择分部"
        >
          <el-option v-for="(item,index) in selects.branchs"
            :key="index"
            :label="item.name"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-button native-type="submit" type="primary">搜索</el-button>
      <el-button native-type="reset" type="danger">重置</el-button>
    </save-form>
    <div class="tags">
      <el-badge
        :hidden="!keyNames[item].num"
        is-dot
        v-for="(item, index) in permissionTags"
        :key="index"
      >
        <el-tag
          :effect="activeKey === item ? 'dark' : 'plain'"
          @click="changeTag(item)"
        >{{keyNames[item].name}}</el-tag>
      </el-badge>
    </div>
    <empty desc="暂无需要处理异常" v-if="!activeList.length"/>
    <el-button @click="handle(item)"
      style="width: 100%;color: #303133;margin-left: 0;"
      v-else
      v-for="(item, index) in activeList"
      :key="index"
      :disabled="(item[0].result && !item[0].result.length) || (!item[0].num)" type="text"
    >
      <title-item
        :type="item[0].isError ? 'error' : 'warning'"
        :data="item.map(title => ({name: title.desc, num: title.num, num2: title.num2, errorType:title.errorType}))"
      >
        <span style="color: #14928A;" v-if='item[0].errorType == "NO_CLASS_MUSIC_GROUP_STUDENT_INFO"'>
          <template v-if="permission('/notClassStudent')">
            立即处理<i class="el-icon-d-arrow-right"/>
          </template>
        </span>
        <span style="color: #14928A;" v-else>
          立即处理<i class="el-icon-d-arrow-right"/>
        </span>
      </title-item>
    </el-button>
    <!-- <title-item
      v-else
      :type="item[0].isError ? 'error' : 'warning'"
      v-for="(item, index) in activeList"
      :key="index"
      :data="item.map(title => ({name: title.desc, num: title.num}))"
    >
      <el-button
        type="text"
        v-if="item[0].url && item[0].result || item[0].always"
        @click="$router.push({
          path: item[0].url,
          query: {
            ...item[0].query,
            tag: $route.query.tag,
            filter_type: item[0].errorType,
            [item[0].resultKey]: item[0].resultKey ? (item[0].result || []).join(',') : undefined
          }
        })" :disabled="!item[0].result.length && !item[0].always"
      >立即处理<i class="el-icon-d-arrow-right"/></el-button>
    </title-item> -->
  </div>
</template>
<script>
import { Searchs } from '@/helpers'
import { getIndexError } from '@/views/main/api'
import { createNotification } from '@/helpers/notification'
import { errorType } from '@/views/main/constant'
import { permission } from '@/utils/directivePage'
import title from './title'
const initSearch = {
  organId: null
}
export default {
  components: {
    'title-item': title
  },
  data() {
    return {
      search: {
        ...initSearch
      },
      listByType: {},
      infoByType: {},
      list: [],
    }
  },
  computed: {
    keyNames() {
      const { status } = this.$store.state.app
      return {
        MUSIC_PATROL: {
          name: '乐团巡查',
          num: status.musicPatrol || false,
        },
        STUDENT_INFO: {
          name: '学员处理',
          num: status.studentInfo || false,
        },
        TEACHER_INFO: {
          name: '日常行政',
          num: status.teacherInfo || false,
        },
        ATTENDANCE_SERVE:{
          name:'考勤及服务',
          num: status.attendanceServe || false,
        }
      }
    },
    permissionTags() {
      const url = 'getIndexErrData?errorType='
      const permissions = ['MUSIC_PATROL', 'STUDENT_INFO', 'TEACHER_INFO','ATTENDANCE_SERVE']
      return permissions.filter(item => {
        return this.permission(url + item)
      })
    },
    activeKey() {
      let key = ''
      const { tag } = this.$route.query
      if (tag) {
        key = tag
      } else if (this.permissionTags[0]) {
        key = this.permissionTags[0]
      }
      return key
    },
    tags() {
      const tags = this.list.map(item => ({name: item.desc, type: item.errorType, num: item.num}))
      return tags
    },
    activeList() {

      const list = this.listByType[this.activeKey] || []
      return list
    },
  },
  mounted() {
    this.FetchList()
    this.$store.dispatch('setBranchs')
  },
  methods: {
    permission,
    handle(item) {
      if(item[0].errorType == "NO_CLASS_MUSIC_GROUP_STUDENT_INFO" && !this.permission('/notClassStudent')) {
        return
      }

      // 单独对未缴费学员数
      if(item[0].errorType == 'STUDENT_NOT_PAYMENT') {
        item[0].query['result'] = item[0].result ? (item[0].result || []).join(',') : undefined
      }
      new Searchs().removeByKey(item[0].url)
      this.$router.push({
        path: item[0].url,
        query: {
          ...item[0].query,
          tag: this.$route.query.tag,
          filter_type: item[0].errorType,
          organId: this.search.organId || undefined,
          [item[0].resultKey]: item[0].resultKey ? (item[0].result || []).join(',') : undefined
        }
      })
    },
    changeTag(type) {
      this.$router.replace({
        query: {
          ...this.$route.query,
          tag: type
        }
      })
      this.FetchList()
    },
    formatData(data) {
      const list = {}
      for (const item of data) {
        const row = errorType[item.errorType] || {}
        const key = row.parent || item.errorType
        if (!list[key]) {
          list[key] = []
        }
        list[key].push(
          {
            ...item,
            ...row,
          }
        )

      }
      return Object.values(list)
    },
    async FetchList() {
      try {
        const res = await getIndexError({
          errorType: this.activeKey,
          ...this.search,
        })
        this.list = res.data.data
        const data = {}
        const info = {}
        for (const item of this.list) {
          info[item.errorType] = item
          data[item.errorType] = this.formatData(item?.result || [])
        }
        this.infoByType = info
        this.listByType = data
      } catch (error) {}
    },
    reset() {
      this.search = {...initSearch}
      this.FetchList()
    },
    send() {
      createNotification({
        title: '测试发送通知',
        body: '您有一条待处理通知，请及时处理',
        onClick: () => {
          this.$router.replace('/main/main')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .tags{
    margin-bottom: 20px;
    >div{
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .container{
    /deep/ .is-disabled {
      .title{
        >span{
          color: #C0C4CC!important;
        }
      }
    }
  }
</style>
