<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" @search="onRefresh" placeholder="请输入课程体系名称或段落搜索"></van-search>
    <van-tabs v-model:active="activeTab" @change="onRefresh">
      <van-tab v-for="tab in tabs" :name="tab.name" :title="tab.label"></van-tab>
    </van-tabs>
    <div class="list">
        <van-pull-refresh v-model="state.refreshing" @refresh="onRefresh">
          <van-list v-model:loading="state.loading" :finished="state.finished"
                    finished-text="没有更多数据了。" v-model:error="state.error"
                    error-text="请求失败，点击重新加载" @load="onPage"
          >
            <template v-for="item in dataset" :key="item.id">
              <van-swipe-cell>
                <van-cell center :label="item.section_name" :title="item.course_name" @click="() => onClick(item.id)" >
                  <template #label>
                    <div><strong>章节：</strong>{{item.section_name}}</div>
                    <div v-if="item.course_category_name"><strong>类型：</strong>{{item.course_category_name}}</div>
                    <div class="van-multi-ellipsis--l3" v-if="item.course_text">
                      <strong>说明：</strong>{{item.course_text}}
                    </div>
                    <div class="van-multi-ellipsis--l3" v-if="item.teachers?.vals?.length">
                      <strong>共享给老师：</strong>{{item.teachers.vals.map(x => x.teacher_name).join(", ")}}
                    </div>
                    <div>
                      <strong>创建时间：</strong>{{datetime(item.created_at)}}
                    </div>
                    <div>
                      <strong>更新时间：</strong>{{datetime(item.updated_at)}}
                    </div>
                    <div>
                      <strong>创建人：</strong>{{item.creator_name}}
                    </div>
                    <div>
                      <strong>更新人：</strong>{{item.updator_name}}
                    </div>
                  </template>
                  <template #right-icon>
                    <i v-if="item.resources?.some(r => r.resource_type === 'Video')" style="color: #00AA4F" class="fa-solid fa-film"></i>
                    <i v-if="item.resources?.some(r => r.resource_type === 'Audio')" style="color: #00AA4F; margin-left: 2px;" class="fa-solid fa-headphones"></i>
                  </template>
                </van-cell>
                <template #right>
                  <van-button class="swipe-btn" square type="primary" @click="$router.push('/course/section/edit?id=' + item.id)" text="编辑"></van-button>
                  <van-button class="swipe-btn" square type="danger" @click="onRemove(item.id)" text="删除"></van-button>
                  <van-button class="swipe-btn" square type="success" @click="onClone(item)" text="复制"></van-button>
                </template>
              </van-swipe-cell>
            </template>
          </van-list>
        </van-pull-refresh>
      </div>
    <van-icon v-if="!state.isPicking" name="add" class="btn-add" size="0.96rem" color="#2196f3" @click="$router.push('/course/section/add')" />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, onMounted, ref, watch } from 'vue';
import {Button, Cell, SwipeCell, List, PullRefresh, Search, Icon, showConfirmDialog, Tabs, Tab} from 'vant';
import useCourseSection from "~/store/qumu-section";
import {useRouter, useRoute} from "vue-router";
import {CourseQueryParam} from '~/types';
import {DateFormatter, formatDate} from '~/utils'

export interface CourseState {
  loading: boolean,
  finished: boolean,
  error: boolean,
  keyword: string,
  refreshing: boolean,
  page: number,
  page_size: number
}

export default defineComponent({
  name: "course-section",
  components: {
    [List.name]: List,
    [Cell.name]: Cell,
    [Search.name]: Search,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Icon.name]: Icon,
    [SwipeCell.name]: SwipeCell,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab
  },
  props: {params: {} as any},
  setup({params}) {
    const route = useRoute();

    const courseIdFromRoute = (): string | undefined => {
      const raw = route.query.course_id;
      if (typeof raw === "string") {
        return raw;
      }
      if (Array.isArray(raw) && raw.length > 0 && typeof raw[0] === "string") {
        return raw[0];
      }
      return undefined;
    };

    const state = reactive<CourseState>({
      loading: false,
      finished: false,
      error: false,
      keyword: '',
      refreshing: false,
      page: 1,
      page_size: 20
    });

    const router = useRouter();
    const timer = ref(0);
    const activeTab = ref("mine")

    const tabs = [
      {name: "mine", label: "我的课程"},
      {name: "assigned", label: "共享课程"}
    ]

    const { store, query, remove, clone } = useCourseSection(router);

    const search = async (params: CourseQueryParam) => {
      state.finished = false;
      state.error = false;
      state.loading = true;
      let { keyword } = state;
      if (keyword) {
        keyword = keyword.replace(/\s+/g, ' ').trim();
        params.keyword = keyword || undefined;
      }
      const resolvedCourseId = courseIdFromRoute() || (params as { course_id?: string })?.course_id;
      if (resolvedCourseId) {
        params.course_id = resolvedCourseId;
      }
      state.error = !(await query(params, activeTab.value))
      state.page = params.page;
      if (store[activeTab.value].pages <= state.page) {
        state.finished = true;
      }
      state.loading = false;
    }


    const onRefresh = async () => {
      state.refreshing = true;
      await search({page: 1, page_size: state.page_size});
      state.refreshing = false;
    };

    watch(() => state.keyword, () => {
      if (timer.value) {
        clearTimeout(timer.value);
      }
      timer.value = window.setTimeout(() => {
        onRefresh();
      }, 500)
    })

    watch(
      () => route.query.course_id,
      (next, prev) => {
        if (next !== prev) {
          onRefresh();
        }
      }
    );

    const onPage = async () => {
      if (state.finished) return;
      let { page, page_size } = state;
      await search({page: page + 1, page_size})
    }

    const dataset = computed(() => {
      return store[activeTab.value].list
    })

    const onClick = (id: string) => {
      router.push('/course/section/detail?id=' + id)
    }


    onMounted(() => onRefresh());

    const onRemove = (id: string) => {
      showConfirmDialog({
        title: "删除课程",
        message: "操作不可撤销，确认删除当前课程？"
      }).then(() => {
        remove(id, () => onRefresh());
      });
    };

    const onClone = async (item) => {
        showConfirmDialog({
            message: `确认复制课程【${item.course_name}(${item.section_name})】？`
        }).then(() => clone(router, item.id)).catch(() => {})
    }

    const datetime = (time: string | Date) => formatDate(time, DateFormatter.DateTime)

    return {
      state, dataset, onRefresh, onClick, onRemove, onPage, datetime, onClone, activeTab, tabs
    };
  }
});
</script>

<style scoped lang="less">

.main {
  width: 100vw;
  overflow: hidden;
  background: #f7f7f7;
  position: relative;

  :deep(.van-tabs) {
    height: 1.2rem;

    .van-tabs__content {
      display: none;
    }
  }

  .list {
    width: calc(100% - 0.32rem);
    height: calc(100% - 0.54rem - 0.64rem - 1.2rem);
    overflow: auto;

    margin: 0 0.16rem 0.32rem;

    &::-webkit-scrollbar {
      display: none;
    }

    .qs-author {
      span:not(:first-child) {
        margin-left: 1rem
      }
    }
  }

  .btn-add {
    position: absolute;
    right: 0.24rem;
    bottom: 0.32rem;
  }

  .btn-pick {
    position: absolute;
    bottom: 0.32rem;
    width: 90%;
    left: 5%;
  }

}
</style>
