<template>
    <div class="main">
        <van-form @submit="onSubmit">
            <van-field label="打卡名称" required colon v-model="store.current.name"/>
            <van-field v-model="start_date" readonly clickable right-icon="arrow"
                       @click="state.showCalendar = true"
                       label="打卡周期" required colon/>
            <van-field readonly disabled label="打卡截止" required colon
                       :model-value="end_date + ' (' + store.current.duration_days + '天)'"/>
            <van-field label="学生" required readonly :border="!store.current.students?.val?.users?.vals?.length">
              <template #button>
                <div>
                  <van-button type="success" @click="pickUserGroup" size="mini">选小组</van-button>
                  <van-button type="success" @click="pickStudent" size="mini">选学生</van-button>
                </div>
              </template>
            </van-field>
            <div class="picked-items" v-if="store.current.students?.val?.users?.vals?.length">
              <van-tag :closeable="!state.readonly" type="primary" @close="removeStudent(user)" v-for="user in store.current.students?.val?.users?.vals">{{user.real_name}}</van-tag>
            </div>
            <van-cell is-link @click="pickCourseSection" title="课程"
                      title-class="van-field__label van-field__label--required" colon>
                <div v-for="course in store.current.course_sections">
                    <van-tag type="primary" size="medium">
                        {{ course.course_name }}({{ course.section_name }})
                    </van-tag>
                </div>
            </van-cell>
            <van-cell is-link @click="pickTeachers" title="批阅老师" v-if="isSupervisor"
                      title-class="van-field__label" colon>
                <div v-for="teacher in store.current.teachers?.vals">
                    <van-tag type="primary" size="medium">
                      {{ teacher.teacher_name }}
                    </van-tag>
                </div>
            </van-cell>
            <van-field v-model="store.current.desc" label="备注" colon autosize rows="3"
                       type="textarea" placeholder="请输入备注"/>
            <van-calendar v-model:show="state.showCalendar" @confirm="onChangeDate" type="range"
                          :min-date="state.minDate" color="#1989fa"/>
            <div class="footer">
                <van-button block type="primary" :disabled="!!loading" @click="onSubmit">提交</van-button>
            </div>
        </van-form>
    </div>
</template>

<script lang="ts">
import {computed, defineComponent, onBeforeUnmount, onMounted, reactive} from "vue";
import {Button, Calendar, Cell, Field, Form, Tag} from 'vant';
import {DateFormatter, formatDate} from "~/utils";
import {useRouter} from 'vue-router';
import useDaka from "~/store/daka";
import useClazz from "~/store/clazz";
import useUser from '~/store/user';
import useLoading from "~/store/loading";
import {GroupUser, HtySuperRoles, PickTargets} from "~/types";
import usePool from "~/store/pool";

export default defineComponent({
    name: "daka-add",
    components: {
        [Calendar.name]: Calendar,
        [Form.name]: Form,
        [Field.name]: Field,
        [Button.name]: Button,
        [Tag.name]: Tag,
        [Cell.name]: Cell
    },
    props: {params: {}},
    setup({params}: any) {
        const router = useRouter();
        const {set_editing} = useUser();
        const {store, create, reset} = useDaka();
        const {store:{current}} = useUser()
        const {loading} = useLoading();
        const { get: getPool, remove: removePool, set: setPool } = usePool()
        const {setDakasForClazz} = useClazz()

        const genName = () => {
          let name = "打卡";
          let { start_date } = store.current;
          if (start_date) {
            name += " " + formatDate(start_date, DateFormatter.Date)
          }
          return name;
        }

        if (!store.hanging) {
          reset();
        }
        store.current.name = genName();
        const start_date = computed(() => formatDate(store.current.start_date))
        const end_date = computed(() => formatDate(store.current.end_date))

        const state = reactive({
            showCalendar: false,
            minDate: new Date(2021, 0, 1),
        });

        const isSupervisor = computed(() => current.roles?.some(r => r.role_key === HtySuperRoles.SUPERVISOR))
        const onSubmit = async () => {
            let id = await create();
            if (id) {
                if (params.clazz_id) {
                  let { name, start_date, duration_days } = store.current;
                  await setDakasForClazz({id, name, start_date, duration_days});
                  reset();
                  await router.back();
                } else {
                  reset();
                  await router.replace("/daka");
                }
            }
        };

        onMounted(() => {
            set_editing(true);
            let { course_sections, teachers, students } = getPool();
            if (course_sections) {
              store.current.course_sections = JSON.parse(JSON.stringify(course_sections));
            }
            if (teachers?.val.users.vals.length) {
              store.current.teachers = { vals: teachers.val.users.vals.map(u => ({teacher_id: u.user_id, teacher_name: u.real_name}))}
            }
            if (students?.val.users.vals.length) {
              store.current.students = JSON.parse(JSON.stringify(students))
            }

        })

        onBeforeUnmount(() => {
            removePool("course_sections")
            removePool('teachers')
            removePool('students')
        })

        const onChangeDate = (values: Date[]) => {
            let [start, end] = values;
            store.current.start_date = formatDate(start, DateFormatter.DateTimeSave);
            store.current.end_date = formatDate(end, DateFormatter.DateTimeSave);
            store.current.duration_days = (end.valueOf() - start.valueOf()) / (1000 * 3600 * 24)
            state.showCalendar = false;
            store.current.name = genName();
        };

        const pickUserGroup = () => {
          store.hanging = true;
          router.push('/user-group/pick?target=' + PickTargets.DAKA)
        }

        const pickStudent = () => {
          store.hanging = true;
          router.push('/student?multiple=1&target=' + PickTargets.DAKA)
        }
        const pickCourseSection = () => {
            store.hanging = true;
            router.push("/course/mix-pick?target=" + PickTargets.DAKA);
        }

      const removeStudent = (user: GroupUser) => {
        store.current.students.val.users.vals = store.current.students.val.users.vals.filter(x => x.user_id !== user.user_id)
      }

        const pickTeachers = () => {
          store.hanging = true;
          router.push("/teacher/subsidiaries?multiple=1&target=" + PickTargets.DAKA)
        }

        return {
            state, store, start_date, end_date, onSubmit, onChangeDate, pickUserGroup, pickStudent, pickCourseSection, removeStudent, loading, pickTeachers, isSupervisor
        };
    }
});
</script>

<style scoped lang="less">
.main {

  .footer {
    margin-top: 0.3rem;
    padding: 0 5%;

  }
}

.picked-items {
  margin: 0 var(--van-cell-horizontal-padding);
  padding: 0 0 5px 0;
  border-bottom: 1px solid var(--van-cell-border-color);

  &:empty {
    padding: 0;
  }

  :deep(.van-tag) {
    margin: 0.04rem 0.06rem;
  }
}
</style>
