<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" placeholder="请输入课包名称搜索" @search="onSearch" @clear="onSearch" />
    <div class="tab-bar">
      <van-tabs v-model:active="state.activeTab" @change="onTabChange">
        <van-tab title="我的课包" name="my" />
        <van-tab title="机构课包" name="org" />
      </van-tabs>
    </div>
    <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="onLoad">
          <template v-for="item in store.list" :key="item.id">
            <van-swipe-cell>
              <van-cell center @click="viewDetail(item)">
                <template #title>
                  <div class="pkg-title">
                    <span>{{ item.package_name }}</span>
                    <van-tag :type="item.package_status === 'ACTIVE' ? 'success' : 'warning'" size="small">
                      {{ item.package_status === 'ACTIVE' ? '上架中' : '已下架' }}
                    </van-tag>
                  </div>
                </template>
                <template #label>
                  <div class="pkg-info">
                    <span v-if="item.total_lessons">{{ item.total_lessons }} 课次</span>
                    <span v-if="item.selling_price">售价 ¥{{ (item.selling_price / 100).toFixed(2) }}</span>
                    <span v-if="item.original_price">原价 ¥{{ (item.original_price / 100).toFixed(2) }}</span>
                    <span v-if="item.validity_days">{{ item.validity_days }} 天有效</span>
                  </div>
                  <div v-if="item.description" class="pkg-desc">{{ item.description }}</div>
                </template>
              </van-cell>
              <template #right>
                <van-button square type="primary" @click="edit(item)" text="编辑" />
                <van-button square type="danger" @click="del(item)" text="删除" />
              </template>
            </van-swipe-cell>
          </template>
        </van-list>
      </van-pull-refresh>
    </div>
    <van-icon name="add" class="btn-add" size="0.96rem" color="#2196f3" @click="add" />
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, onMounted, reactive} from 'vue';
import {Button, Cell, Icon, List, PullRefresh, Search, SwipeCell, Tag, Tabs, Tab, showConfirmDialog} from 'vant';
import useCoursePackage from "~/store/course-package";
import {useRouter} from "vue-router";
import {CoursePackage} from "~/types";
import {showFailToast} from "vant";

interface CoursePackageState {
  loading: boolean;
  finished: boolean;
  error: boolean;
  refreshing: boolean;
  keyword: string;
  activeTab: string;
  page: number;
}

export default defineComponent({
  name: "course-package",
  components: {
    [List.name]: List,
    [Cell.name]: Cell,
    [Search.name]: Search,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [SwipeCell.name]: SwipeCell,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
  },
  setup() {
    const router = useRouter();
    const {store, queryMyPackages, queryOrgPackages, remove} = useCoursePackage();

    const state = reactive<CoursePackageState>({
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      keyword: '',
      activeTab: 'my',
      page: 1,
    });

    const PAGE_SIZE = 20;

    const loadData = async () => {
      state.loading = true;
      state.error = false;
      let ok: boolean;
      if (state.activeTab === 'my') {
        ok = await queryMyPackages(state.keyword || undefined, state.page, PAGE_SIZE);
      } else {
        ok = await queryOrgPackages(state.keyword || undefined, state.page, PAGE_SIZE);
      }
      if (!ok) state.error = true;
      state.loading = false;
      state.finished = true;
    };

    const onRefresh = async () => {
      state.page = 1;
      state.finished = false;
      state.error = false;
      state.refreshing = true;
      await loadData();
      state.refreshing = false;
    };

    const onLoad = async () => {
      await loadData();
    };

    const onSearch = () => {
      state.page = 1;
      state.finished = false;
      loadData();
    };

    const onTabChange = () => {
      state.page = 1;
      state.finished = false;
      loadData();
    };

    const add = () => {
      router.push('/course/course-package/add');
    };

    const edit = (item: CoursePackage) => {
      router.push(`/course/course-package/edit?id=${item.id}`);
    };

    const viewDetail = (item: CoursePackage) => {
      router.push(`/course/course-package/detail?id=${item.id}`);
    };

    const del = async (item: CoursePackage) => {
      try {
        await showConfirmDialog({message: `确认删除课包【${item.package_name}】？`});
        const ok = await remove(item.id!);
        if (ok) await onRefresh();
      } catch { /* cancelled */ }
    };

    onMounted(() => loadData());

    return {
      state, store, onRefresh, onLoad, onSearch, onTabChange, add, edit, viewDetail, del,
    };
  }
});
</script>

<style scoped lang="less">
.main {
  width: 100vw;
  overflow: hidden;
  background: #f7f7f7;
  position: relative;

  .tab-bar {
    margin: 0 0.16rem;
  }

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

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

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

.pkg-title {
  display: flex;
  align-items: center;
  gap: 0.16rem;
}

.pkg-info {
  display: flex;
  flex-wrap: wrap;
  gap: 0.12rem;
  font-size: 0.24rem;
  color: #666;
  margin-top: 0.08rem;
}

.pkg-desc {
  font-size: 0.22rem;
  color: #999;
  margin-top: 0.04rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
