<template>
  <div class="main-container">
    <el-card class="box-card !border-none" shadow="never">
      <div class="flex justify-between items-center">
        <span class="text-lg">{{ pageName }}</span>
        <el-button type="primary" @click="addEvent">
          {{ t('addCourseSchedule') }}
        </el-button>
      </div>

      <el-card
        class="box-card !border-none my-[10px] table-search-wrap"
        shadow="never"
      >
        <el-form
          :inline="true"
          :model="courseScheduleTable.searchParam"
          ref="searchFormRef"
        >
          <el-form-item :label="t('campusId')" prop="campus_id">
            <el-select
              v-model="courseScheduleTable.searchParam.campus_id"
              :placeholder="t('campusIdPlaceholder')"
              clearable
            >
              <el-option
                v-for="item in campusList"
                :key="item.id"
                :label="item.campus_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('venueId')" prop="venue_id">
            <el-select
              v-model="courseScheduleTable.searchParam.venue_id"
              :placeholder="t('venueIdPlaceholder')"
              clearable
            >
              <el-option
                v-for="item in venueFilterList"
                :key="item.id"
                :label="item.venue_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('courseDate')" prop="course_date">
            <el-date-picker
              v-model="courseScheduleTable.searchParam.course_date"
              type="date"
              :placeholder="t('courseDatePlaceholder')"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item :label="t('coachId')" prop="coach_id">
            <el-input
              v-model="courseScheduleTable.searchParam.coach_id"
              :placeholder="t('coachIdPlaceholder')"
            />
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="loadCourseScheduleList()">{{
              t('search')
            }}</el-button>
            <el-button @click="resetForm(searchFormRef)">{{
              t('reset')
            }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <div class="mt-[10px]">
        <el-table
          :data="courseScheduleTable.data"
          size="large"
          v-loading="courseScheduleTable.loading"
        >
          <template #empty>
            <span>{{
              !courseScheduleTable.loading ? t('emptyData') : ''
            }}</span>
          </template>
          <el-table-column
            prop="campus_id"
            :label="t('campusId')"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ getCampusName(row.campus_id) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="venue_id"
            :label="t('venueId')"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.venue ? row.venue.venue_name : '' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="course_date"
            :label="t('courseDate')"
            min-width="120"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            prop="time_slot"
            :label="t('timeSlot')"
            min-width="120"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            prop="course_id"
            :label="t('courseId')"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.course ? row.course.course_name : '' }}
            </template>
          </el-table-column>


          <el-table-column
            prop="coach_id"
            :label="t('coachId')"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.coach ? row.coach.name : '' }}
            </template>
          </el-table-column>

<!-- 
          <el-table-column
            prop="participants"
            :label="t('participants')"
            min-width="120"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            prop="student_ids"
            :label="t('studentIds')"
            min-width="120"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            prop="available_capacity"
            :label="t('availableCapacity')"
            min-width="120"
            :show-overflow-tooltip="true"
          /> -->

          <el-table-column
            prop="status"
            :label="t('status')"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <span v-if="row.status === 'pending'">{{ t('pending') }}</span>
              <span v-if="row.status === 'upcoming'">{{ t('upcoming') }}</span>
              <span v-if="row.status === 'ongoing'">{{ t('ongoing') }}</span>
              <span v-if="row.status === 'completed'">{{ t('completed') }}</span>
            </template>
          </el-table-column>

          <el-table-column
            :label="t('operation')"
            fixed="right"
            min-width="120"
          >
            <template #default="{ row }">
              <el-button type="primary" link @click="editEvent(row)">{{
                t('edit')
              }}</el-button>
              <el-button type="primary" link @click="deleteEvent(row.id)">{{
                t('delete')
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="mt-[16px] flex justify-end">
          <el-pagination
            v-model:current-page="courseScheduleTable.page"
            v-model:page-size="courseScheduleTable.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="courseScheduleTable.total"
            @size-change="loadCourseScheduleList()"
            @current-change="loadCourseScheduleList"
          />
        </div>
      </div>

      <edit ref="editCourseScheduleDialog" @complete="loadCourseScheduleList" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { t } from '@/lang'
import { useDictionary } from '@/app/api/dict'
import {
  getCourseScheduleList,
  deleteCourseSchedule,
} from '@/app/api/course_schedule'
import { getAllClassroomList } from '@/app/api/classroom'
import { getWithCampusList, getAllVenueList } from '@/app/api/venue'
import { img } from '@/utils/common'
import { ElMessageBox, FormInstance } from 'element-plus'
import Edit from '@/app/views/course_schedule/components/course-schedule-edit.vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const pageName = route.meta.title

let courseScheduleTable = reactive({
  page: 1,
  limit: 10,
  total: 0,
  loading: true,
  data: [],
  searchParam: {
    campus_id: '',
    venue_id: '',
    course_date: ''
  },
})

const searchFormRef = ref<FormInstance>()

// 选中数据
const selectData = ref<any[]>([])

// 校区列表
const campusList = ref<any[]>([])
// 场地列表 - 所有场地，用于显示名称
const venueList = ref<any[]>([])
// 场地筛选列表 - 特定校区下的场地，用于筛选
const venueFilterList = ref<any[]>([])

// 根据ID获取校区名称
const getCampusName = (id: string | number) => {
  const campus = campusList.value.find(item => item.id === id)
  return campus ? campus.campus_name : id
}

// 获取校区列表
const loadCampusList = () => {
  getWithCampusList({})
    .then((res) => {
      campusList.value = res.data || []
    })
    .catch(() => {})
}

// 获取所有场地列表 - 用于显示名称
const loadVenueList = () => {
  getAllVenueList({})
    .then((res) => {
      venueList.value = res.data || []
    })
    .catch(() => {})
}

// 获取校区下的场地列表 - 用于筛选条件
const loadVenuesByCampus = (campus_id?: string | number) => {
  getAllVenueList({ campus_id })
    .then((res) => {
      venueFilterList.value = res.data || []
    })
    .catch(() => {})
}

// 监听校区变化
watch(
  () => courseScheduleTable.searchParam.campus_id,
  (newValue) => {
    courseScheduleTable.searchParam.venue_id = ''
    if (newValue) {
      loadVenuesByCampus(newValue)
    } else {
      venueFilterList.value = []
    }
  }
)

/**
 * 获取课程安排列表
 */
const loadCourseScheduleList = (page: number = 1) => {
  courseScheduleTable.loading = true
  courseScheduleTable.page = page

  getCourseScheduleList({
    page: courseScheduleTable.page,
    limit: courseScheduleTable.limit,
    ...courseScheduleTable.searchParam,
  })
    .then((res) => {
      courseScheduleTable.loading = false
      courseScheduleTable.data = res.data.data
      courseScheduleTable.total = res.data.total
    })
    .catch(() => {
      courseScheduleTable.loading = false
    })
}

// 初始化加载数据
onMounted(() => {
  loadCampusList()
  loadVenueList()
  loadCourseScheduleList()
})

const editCourseScheduleDialog: Record<string, any> | null = ref(null)

/**
 * 添加课程安排
 */
const addEvent = () => {
  editCourseScheduleDialog.value.setFormData()
  editCourseScheduleDialog.value.showDialog = true
}

/**
 * 编辑课程安排
 * @param data
 */
const editEvent = (data: any) => {
  editCourseScheduleDialog.value.setFormData(data)
  editCourseScheduleDialog.value.showDialog = true
}

/**
 * 删除课程安排
 */
const deleteEvent = (id: number) => {
  ElMessageBox.confirm(t('courseScheduleDeleteTips'), t('warning'), {
    confirmButtonText: t('confirm'),
    cancelButtonText: t('cancel'),
    type: 'warning',
  }).then(() => {
    deleteCourseSchedule(id)
      .then(() => {
        loadCourseScheduleList()
      })
      .catch(() => {})
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  loadCourseScheduleList()
}
</script>

<style lang="scss" scoped>
/* 多行超出隐藏 */
.multi-hidden {
  word-break: break-all;
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
