<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" placeholder="请输入分组名称搜索"></van-search>
    <van-tabs v-model:active="activeTab">
      <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="请求失败，点击重新加载"
          >
            <template v-for="item in dataset" :key="item.id">
              <van-swipe-cell>
                <van-cell center :title="item.group_name" @click="() => onClick(item.id)" >
                  <template #label>
                    <div v-if="item.course_sections?.length">
                      <label>课程：</label>
                      <div class="course-tags">
                        <van-tag type="primary" text-color="#fff"
                                 v-for="course in item.course_sections">{{ course.course_name }} ({{course.section_name}})</van-tag>
                      </div>
                    </div>
                    <div v-if="item.teachers?.vals?.length">
                      <label>共享老师：</label>
                      <div class="course-tags">
                        <van-tag type="primary" text-color="#fff"
                                 v-for="item in item.teachers.vals">{{ item.teacher_name }}</van-tag>
                      </div>
                    </div>
                    <div>
                      <label>创建人：</label>{{item.creator_name}}
                    </div>
                    <div>
                      <label>创建时间：</label>{{datetime(item.created_at)}}
                    </div>
                    <div>
                      <label>更新人：</label>{{item.updator_name}}
                    </div>
                    <div>
                      <label>更新时间：</label>{{datetime(item.updated_at)}}
                    </div>
                  </template>
                </van-cell>
                <template #right>
                  <van-button class="swipe-btn" square type="primary" @click="$router.push('/course/group/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/group/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, Tag} from 'vant';
import useCourseGroup from "~/store/qumu-section-group";
import {useRouter} from "vue-router";
import {DateFormatter, formatDate} from '~/utils'
import useUser from "~/store/user";

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

export default defineComponent({
  name: "course-section-group",
  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,
    [Tag.name]: Tag
  },
  props: {params: {} as any},
  setup({}) {
    const state = reactive<CourseGroupState>({
      loading: false,
      finished: false,
      error: false,
      keyword: '',
      refreshing: false,
    });

    const router = useRouter();
    const timer = ref(0);
    const activeTab = ref("mine")
    const {store:{current:{hty_id}}} = useUser()

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

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

    const search = async () => {
      state.finished = false;
      state.error = false;
      state.loading = true;
      state.error = !(await query())
      state.finished = true;
      state.loading = false;
    }


    const onRefresh = async () => {
      state.refreshing = true;
      await search();
      state.refreshing = false;
    };

    const dataset = computed(() => {
      let data = store.list;
      switch (activeTab.value) {
        case "mine":
          data = data.filter(x => x.created_by === hty_id)
          break;
        case "assigned":
          data = data.filter(x => x.created_by !== hty_id)
          break;
      }
      let { keyword } = state;
      if (keyword) {
        keyword = keyword.replace(/\s+/g, ' ').trim();
        data = data.filter(x => x.group_name.includes(keyword))
      }
      return data;
    })

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


    onMounted(() => onRefresh());

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

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

    return {
      state, dataset, onRefresh, onClick, onRemove, datetime, 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
      }
    }

    .course-tags {
      display: inline-block;
      span:not(:last-child) {
        margin-right: 6px;
      }
    }
  }

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

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

}
</style>
