<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" placeholder="请输入分组名称搜索"></van-search>
    <div class="check-list" ref="checkList">
      <van-tag type="primary" @close="onClick(item)" @click="onClick(item)" closeable v-for="item in state.checked">{{item.group_name}}</van-tag>
    </div>
    <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" :style="{'height': height}">
      <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"
        >
          <div v-for="item in dataset" :key="item.id" class="course-item">
            <van-cell center :title="item.group_name" inset>
              <template #right-icon>
                <van-icon color="#07c160" size="0.5rem" name="checked" v-if="item.checked" @click="() => onClick(item)" />
                <van-icon color="#07c160" size="0.5rem" name="circle" v-else @click="() => onClick(item)" />
              </template>
              <template #label>
                <div class="course-tags" v-if="item.course_sections?.length">
                  <van-tag type="primary" text-color="#fff" v-for="course in item.course_sections">
                    {{ course.course_name }} ({{course.section_name}})
                  </van-tag>
                </div>
              </template>
            </van-cell>
            <div class="qs-author-time van-cell__label">
              <strong>{{item.creator_name || "未知用户"}}</strong> 于 <strong>{{datetime(item.created_at) || "未知时间"}}</strong> 创建
            </div>
            <div class="qs-author-time van-cell__label">
              <strong>{{item.updator_name || "未知用户"}}</strong> 于 <strong>{{datetime(item.updated_at) || "未知时间"}}</strong> 更新
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    <van-button class="btn-pick" type="primary" block :disabled="!state.checked.length" @click="onPick">确认</van-button>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, onMounted, ref, watch, nextTick } from 'vue';
import {
  Button,
  Cell,
  SwipeCell,
  List,
  PullRefresh,
  Search,
  Icon,
  Tag,
  ActionSheet,
  Popover,
  Tabs,
  Tab,
  showFailToast
} from 'vant';
import useJihua from "~/store/jihua";
import useDaka from '~/store/daka';
import useClazz from "~/store/clazz";
import useCoursePackage from "~/store/course-package";
import {useRouter} from "vue-router";
import {CourseGroup, PickTargets} from '~/types';
import {DateFormatter, formatDate} from "~/utils";
import useCourseGroup from "~/store/qumu-section-group";
import useUser from "~/store/user";
import request from "~/utils/request";

export interface CourseState {
  loading: boolean,
  finished: boolean,
  error: boolean,
  keyword: string,
  refreshing: boolean,
  checked: CourseGroup[],
  opening: string[]
}

export default defineComponent({
  name: "course-section-group-pick",
  components: {
    [List.name]: List,
    [Cell.name]: Cell,
    [Search.name]: Search,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Icon.name]: Icon,
    [SwipeCell.name]: SwipeCell,
    [Tag.name]: Tag,
    [ActionSheet.name]: ActionSheet,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab
  },
  props: {params: {} as any},
  setup({params}) {
    const usingJihua = useJihua();
    const usingDaka = useDaka();
    const usingClazz = useClazz();
    const usingCoursePackage = useCoursePackage();
    const {store:{current:{hty_id}}} = useUser()
    const isForCoursePackage = params.target === PickTargets.COURSE_PACKAGE;
    const state = reactive<CourseState>({
      loading: false,
      finished: false,
      error: false,
      keyword: '',
      refreshing: false,
      checked: isForCoursePackage ? usingCoursePackage.store.selectedGroups : ({
        [PickTargets.JIHUA]: usingJihua.store.current.course_groups,
        [PickTargets.DAKA]: usingDaka.store.current.course_groups
      }[params.target as PickTargets] || []),
      opening: []
    });
    const router = useRouter();
    const checkList = ref(null)
    const caches: {[key: string]: any} = {};

    const height = ref("calc(100% - 1.08rem - 1.04rem - 0.16rem - 0.32rem - var(--van-button-default-height) - 0.16rem)");

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

    const orgVisibleList = ref<CourseGroup[]>([]);

    const activeTab = ref(isForCoursePackage ? "org" : "mine")

    const tabs = isForCoursePackage
      ? [
          {name: "mine", label: "我的课节"},
          {name: "org", label: "机构可见课节"}
        ]
      : [
          {name: "mine", label: "我的课节"},
          {name: "assigned", label: "共享课节"}
        ]

    const search = async () => {
      state.finished = false;
      state.error = false;
      state.loading = true;
      if (isForCoursePackage) {
        // 同时拉取自己的课节和机构可见课节
        const [qResult, orgResult] = await Promise.all([
          query().then(() => true).catch(() => false),
          request({url: '/api/v1/ws/find_org_visible_course_groups'}).then(r => r).catch(() => ({r: false, d: []}))
        ]);
        orgVisibleList.value = orgResult.d || [];
        state.error = !qResult && !orgResult.r;
      } else {
        state.error = !(await query());
      }
      state.finished = true;
      state.loading = false;
    }

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

    const onPage = async () => {
      if (state.finished) return;
      await search()
    }


    const dataset = computed(() => {
      let data = isForCoursePackage
        ? activeTab.value === "mine" ? store.list : orgVisibleList.value
        : 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;
        case "org":
          // org-visible list already filtered by backend
          break;
      }
      let { keyword } = state;
      if (keyword) {
        keyword = keyword.replace(/\s+/g, ' ').trim();
        data = data.filter(x => x.group_name.includes(keyword))
      }
      return data.map(x => {
        let item = {...x, checked: false}
        if (state.checked.some(c => c.id === x.id)) {
          item.checked = true;
        }
        return item;
      });
    })

    const onClick = (item: CourseGroup) => {
      if (state.checked.some(x => x.id === item.id)) {
        state.checked = state.checked.filter(x => x.id !== item.id)
      } else {
        state.checked.push(item);
      }
      nextTick(() => {
        let el = checkList.value as unknown as HTMLDivElement;
        height.value = `calc(100% - 1.08rem - 1.04rem - ${el.offsetHeight}px - 0.32rem - var(--van-button-default-height) - 0.16rem)`;
      })
    }

    const onToggle = async (item: CourseGroup) => {
      let id = item.id as string;
      if (state.opening.includes(id)) {
        state.opening = state.opening.filter(x => x !== id)
      } else {
        state.opening.push(id)
      }
    }

    const onPick = async () => {
      let course_sections = [];
      state.checked.forEach(group => {
        group.course_sections?.forEach(qs => {
          if (!course_sections.some(q => q.id === qs.id)) {
            course_sections.push(qs)
          }
        })
      })
      switch (params.target) {
        case PickTargets.JIHUA:
          usingJihua.store.current.course_sections = course_sections;
          break;
        case PickTargets.DAKA:
          usingDaka.store.current.course_sections = course_sections;
          break;
        case PickTargets.CLAZZ:
          usingClazz.store.current.course_sections = {vals: course_sections};
          break;
        case PickTargets.COURSE_PACKAGE:
          sessionStorage.setItem('cp-selected-groups', JSON.stringify(state.checked));
          usingCoursePackage.store.selectedGroups = state.checked;
          (window as any).__cp_debug = { action: 'onPick', checked: state.checked.length, target: params.target, ts: Date.now() };
          break;
      }
      router.back();
    }

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


    onMounted(() => onRefresh());

    return {
      state, dataset, onRefresh, onClick, onPick, datetime, onPage, checkList, height, caches, activeTab, tabs, onToggle, orgVisibleList
    };
  }
});
</script>

<style scoped lang="less">

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

  .check-list {
    padding: 0.08rem 0.16rem;

    :deep(.van-tag) {
      margin: 0 0.08rem;
      cursor: pointer;
    }
  }

  .list {
    width: calc(100% - 0.32rem);
    height: calc(100% - 1.08rem - 1.04rem - 0.16rem - 0.32rem - var(--van-button-default-height) - 0.16rem);
    overflow: auto;

    margin: 0.16rem;

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

    .course-item  {
      background: #fff;
      margin-bottom: 10px;

      :deep(.van-cell__title) {
        flex: 4;
      }

      .course-toggle {
        margin: 0 4px 0 -12px;
      }

      .course-tags {
        :deep(.van-tag:not(:last-child)) {
          margin-right: 5px;
        }
      }

      .qs-author-time {
        padding: var(--van-padding-xs) var(--van-padding-sm) 0;
      }
    }


  }

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

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

}


.warning-tip {
  font-size: 0.24rem;
  padding: 0.24rem;
  color: var(--van-gray-6);
}
</style>
