<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" placeholder="请输入课程体系类型Key或名称搜索"></van-search>
    <div class="list">
      <van-pull-refresh v-model="state.loading" @refresh="onRefresh">
        <van-list v-model:loading="state.loading" :finished="state.finished"
                  finished-text="No more data." v-model:error="state.error"
                  error-text="请求失败，点击重新加载"
        >
          <template v-for="item in dataset" :key="item.id">
            <van-swipe-cell>
              <van-cell center :title="item.category_name" :value="item.category_key"
                        :label="item.category_desc" :icon="item.is_default ? 'star': ''">
              </van-cell>
              <template #right>
                <van-button v-if="item.is_default" class="action-button" square type="warning" @click="unsetDefault(item)" text="取消默认"></van-button>
                <van-button v-else class="action-button" square type="success" @click="setToDefault(item)" text="设为默认"></van-button>
                <van-button class="action-button" square type="primary" @click="edit(item)" text="编辑"></van-button>
                <van-button class="action-button" square type="danger" @click="del(item)" text="删除"></van-button>
              </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>
  <van-dialog confirm-button-text="保存" :before-close="save" :show="state.showDialog" :title="state.entity?.id ? '编辑课程体系类型' : '新增课程体系类型'" show-cancel-button show-confirm-button>
    <div class="form">
      <van-field v-model="state.entity.category_key" label="Key" required colon />
      <van-field v-model="state.entity.category_name" label="名称" required colon />
      <van-field v-model="state.entity.category_desc" label="描述" colon autosize rows="3"
                 type="textarea" placeholder="请输入课程体系类型说明" />
    </div>
  </van-dialog>
</template>

<script lang="ts">
import {computed, defineComponent, onMounted, reactive} from 'vue';
import {Button, Cell, Icon, List, PullRefresh, Search, Field, Dialog, Toast, SwipeCell, showConfirmDialog, showFailToast} from 'vant';
import useCourseCategory from "~/store/qumu-category";
import {CourseCategory} from "~/types";
import useUser from "~/store/user";

export interface CourseCategoryState {
  loading: boolean,
  finished: boolean,
  error: boolean,
  keyword: string,
  showDialog: boolean,
  entity: CourseCategory
}

export default defineComponent({
  name: "course-category",
  components: {
    [List.name]: List,
    [Cell.name]: Cell,
    [Search.name]: Search,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Dialog.name]: Dialog,
    [SwipeCell.name]: SwipeCell,
    [Icon.name]: Icon,
    [Field.name]: Field
  },
  props: {params: {} as any},
  setup({}) {
    const state = reactive<CourseCategoryState>({
      loading: false,
      finished: false,
      error: false,
      keyword: '',
      showDialog: false,
      entity: {} as CourseCategory
    });


    const {store, query, create, update, remove} = useCourseCategory();

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

    const dataset = computed(() => {
      return store.list.filter(x => (!state.keyword || x.category_key.includes(state.keyword) || x.category_name.includes(state.keyword)));
    })

    const add = () => {
      state.showDialog = true;
      state.entity = {} as CourseCategory;
    }

    const edit = (item: CourseCategory) => {
      state.showDialog = true;
      state.entity = item;
    }

    const save = async (action: string) => {
      if (action === 'cancel') {
        state.entity = {} as CourseCategory;
      }
      if (action === 'confirm') {
        if (!state.entity?.category_key) {
          showFailToast('请输入课程体系类型Key')
          return Promise.resolve(false);
        }
        if (!state.entity?.category_name) {
          showFailToast('请输入课程体系类型名称')
          return Promise.resolve(false);
        }

        if (state.entity?.id) {
          await update(state.entity);
        } else {
          await create(state.entity);
        }
      }
      state.showDialog = false;
      return Promise.resolve(true);
    }

    const del = async (item: CourseCategory) => {
      showConfirmDialog({
        message: `确认删除课程体系【${item.category_name}(${item.category_key})】？`,
      }).then(() => remove(item.id as string)).catch(() => {})
    }

    const setToDefault = async (item: CourseCategory) => {
      let prev = store.list.find(x => x.is_default);
      await showConfirmDialog({
        message: `确认将课程体系【${item.category_name}(${item.category_key})】设为默认？`,
      });
      if (prev) {
        await update({...prev, is_default: false})
      }
      await update({...item, is_default: true})
    }

    const unsetDefault = async (item: CourseCategory) => {
      await showConfirmDialog({
        message: `确认将课程体系【${item.category_name}(${item.category_key})】设为默认？`,
      });
      await update({...item, is_default: false})
    }

    onMounted(() => onRefresh());


    return {
      state, dataset, save, add, edit, del, onRefresh, setToDefault, unsetDefault
    };
  }
});
</script>

<style scoped lang="less">

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

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

    margin: 0.32rem 0.16rem;

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

    .action-button {
      height: 100%;
    }

    :deep(.van-cell .van-icon) {
      color: gold
    }
  }

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

  .btn-edit {
    margin-right: 0.2rem;
  }

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

}

.input-content {
  padding: 0.25rem;
  text-align: center;

}
</style>
