<template>
  <div class="main">
    <van-search v-model.trim="state.keyword" placeholder="请输入课程体系名称搜索"></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 v-if="!state.isPicking">
              <van-cell center :title="item.course_name" @click="() => onClick(item.id)"></van-cell>
              <template #right>
                <van-button square type="primary" @click="edit(item)" text="编辑"></van-button>
                <van-button square type="danger" @click="del(item)" text="删除"></van-button>
              </template>
            </van-swipe-cell>
            <van-cell v-else center :title="item.course_name" @click="() => onClick(item.id)"></van-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="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="input-content">
      <input type="text" class="block-input" placeholder="请输入课程体系名称" v-model="state.entity.course_name" />
    </div>
  </van-dialog>
</template>

<script lang="ts">
import {computed, defineComponent, onMounted, reactive} from 'vue';
import {Button, Cell, Icon, List, PullRefresh, Search, Dialog, showFailToast, SwipeCell, showConfirmDialog} from 'vant';
import useCourse from "~/store/qumu";
import {useRouter} from "vue-router";
import useCourseSection from "~/store/qumu-section";
import {Course} from "~/types";
import useUser from "~/store/user";

export interface CourseState {
  loading: boolean,
  finished: boolean,
  error: boolean,
  keyword: string,
  isPicking: boolean,
  showDialog: boolean,
  entity: Course
}

export default defineComponent({
  name: "course",
  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
  },
  props: {params: {} as any},
  setup({params}) {
    const router = useRouter();
    const usingSection = useCourseSection(router);
    const usingUser = useUser()
    const state = reactive<CourseState>({
      loading: false,
      finished: false,
      error: false,
      keyword: '',
      isPicking: !!params.picking,
      showDialog: false,
      entity: {} as Course
    });


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

    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(() => {
      const courseList = Array.isArray(store.list) ? store.list : [];
      return courseList.filter(
        (courseItem) =>
          (!courseItem.created_by || courseItem.created_by === usingUser.store.current.hty_id) &&
          (!state.keyword || courseItem.course_name.includes(state.keyword))
      );
    })

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

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

    const onClick = (id: string) => {
      if (state.isPicking) {
        let course = store.list.find(x => x.id === id);
        usingSection.store.current.course_id = course?.id;
        usingSection.store.current.course_name = course?.course_name;
        router.go(-1);
      } else {
        router.push('/course/section?course_id=' + id)
      }
    }

    const save = async (action: string) => {
      if (action === 'cancel') {
        state.entity = {} as Course;
      }
      if (action === 'confirm') {
        if (!state.entity?.course_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: Course) => {
      let course = await read(item.id as string);
      if (course) {
        if (course.sections?.some(x => !x.is_delete)) {
          showFailToast('课程体系下存在课程！不能删除！');
          return;
        }
        showConfirmDialog({
          message: `确认删除课程体系【${item.course_name}】？`,
        }).then(() => remove(item.id as string)).catch(() => {})
      }
      
    }

    onMounted(() => onRefresh());


    return {
      state, dataset, save, add, edit, del, onRefresh, onClick
    };
  }
});
</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;
    }
  }

  .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>
