<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="学生" disabled required readonly :border="!store.current.students?.val?.users?.vals?.length"></van-field>
      <div class="picked-items" v-if="store.current.students?.val?.users?.vals?.length">
        <van-tag :closeable="false" type="primary" 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, onBeforeMount, onBeforeUnmount, reactive} from "vue";
import {Button, Calendar, Cell, Field, Form, showNotify, Tag} from 'vant';
import {DateFormatter, formatDate, PiyueLockMinutes} from "~/utils";
import {useRouter} from 'vue-router';
import useDaka from "~/store/daka";
import useUser from "~/store/user";
import useLoading from "~/store/loading";
import {Daka, HtySuperRoles, PickTargets, TimeUnits} from "~/types";
import usePool from "~/store/pool";

export default defineComponent({
  name: "daka-edit",
  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 { set_editing, store:{current} } = useUser();
    const router = useRouter();
    const {store, read, update} = useDaka();
    const { loading } = useLoading()
    const {setRemoteCache, getRemoteCache, delRemoteCache} = usePool()
    let cache: Daka = {} as Daka

    const isSupervisor = computed(() => current.roles?.some(r => r.role_key === HtySuperRoles.SUPERVISOR))

    read(params?.id).then(() => {
      if (store.current.teachers?.vals?.length && !isSupervisor.value) {
        store.current.teachers = null;
      }
      cache = {...store.current}
    })

    const start_date = computed(() => formatDate(store.current.start_date))
    const end_date = computed(() => formatDate(store.current.end_date))
    const courses = computed(() => store.current.course_sections.map(x => `${x.course_name}(${x.section_name})`).join(','))

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



    const onSubmit = async () => {
      let r = await update();
      if (r) {
        await router.replace(`/daka/detail?id=${params?.id}`)
      }
    };

    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;
    };


    const pickCourseSection = () => {
      store.hanging = true;
      router.push("/course/section/pick?target=" + PickTargets.DAKA);
    }

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

    onBeforeMount(async () => {
      set_editing(true)
      let payload = {
        union_id: current.union_id,
        hty_id: current.hty_id,
        real_name: current.real_name
      }
      let key = "edit_daka_qs_" + store.current.id;
      let tmp = await getRemoteCache(key);
      if (tmp) {
        try {
          tmp = JSON.parse(tmp)
        } catch (e) {
          console.log('json parse failed...', e)
        }
        if (tmp.hty_id !== payload.hty_id) {
          showNotify(tmp.real_name + "老师正在编辑该打卡，您当前只能查看不可编辑！")
          setTimeout(() => router.back(), 200)
          return;
        } else {
          await setRemoteCache(key, payload, PiyueLockMinutes, TimeUnits.MINUTE)
        }
      } else {
        await setRemoteCache(key, payload, PiyueLockMinutes, TimeUnits.MINUTE)
      }
      state.editing = key;
    })

    onBeforeUnmount(() => {
      if (state.editing) {
        delRemoteCache(state.editing)
      }
    })

    return {state, store, start_date, end_date, onSubmit, onChangeDate, pickCourseSection, courses, 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>
