<template>
  <FlexCol gap="gap.md">
    <Image
      v-if="currentTaskBanner"
      :src="currentTaskBanner"
      radius="radius.md"
      :width="690"
      mode="widthFix"
    />
    <TaskList
      v-for="item in currentTaskDefItems"
      :key="item.title"
      :icon="item.icon"
      :title="item.title"
      :desc="item.desc"
      :extra="item.extra"
      :goButtonText="isView ? '查看' : '去完成'"
      :enable="item.enable"
      @click="handleClick(item)"
    />
  </FlexCol>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useCollectStore } from '@/store/collect';
import { useTaskEntryForm } from '../forms/composeable/TaskEntryForm';
import { useAuthStore } from '@/store/auth';
import { type TaskMenuDefGoForm, type TaskMenuDefItem } from '../forms/tasks';
import { alert } from '@/components/utils/DialogAction';
import { CollectableModulesIdMap, getVillageInfoForm } from '../forms/forms';
import { navTo } from '@/components/utils/PageAction';
import FlexCol from '@/components/layout/FlexCol.vue';
import Image from '@/components/basic/Image.vue';
import TaskList from '../components/TaskList.vue';
import VillageApi from '@/api/inhert/VillageApi';
import { waitTimeOut } from '@imengyu/imengyu-utils';

const { goForm, goPreviewForm } = useTaskEntryForm();
const authStore = useAuthStore();
const { canCollectCatalog } = useCollectStore();

const props = withDefaults(defineProps<{
  villageId: number,
  villageVolunteerId: number,
  taskTitle: string,
  taskPid: number,
  isView?: boolean,
}>(), {
  isView: false,
});


async function loadList() {
  await waitTimeOut(400);

  const res = (await VillageApi.getCatalogList(
    props.villageId, 
    authStore.isAdmin ? undefined : props.villageVolunteerId,
    props.taskPid
  ));
  if (res.length === 0)
    return;
  currentTaskDefItems.value = res
    .map(item => {
      try {
        const formDefine = item.collectModuleId ? getVillageInfoForm(item.collectModuleId, -1) : undefined;
        return {
          ...item,
          extra: authStore.isAdmin && item.total >= 0 ? `已采编 ${item.total}` : '',
          enable: canCollectCatalog(item.id) || item.haschild,
          catalogItem: item,
          collectModuleId: item.collectModuleId,
          goForm: !item.haschild ? [ 
            item.collectModuleId, 
            item.typeId ?? -1, 
            formDefine?.[2].typeName, 
            item.collectModuleId === CollectableModulesIdMap['overview'] ? 'common' : undefined,
            item.title,
            item.id
          ] as TaskMenuDefGoForm : undefined,
          onClick: () => {
            if (item.haschild) {
              navTo('/pages/dig/forms/task', {
                ...props,
                taskTitle: item.title,
                taskPid: item.id,
                isView: props.isView,
              })
            } else {
              alert({
                title: item.title,
                content: `未找到表单定义：collectModuleId: ${item.collectModuleId}`,
              })
            }
          }
        }
      } catch (e) {
        return {
          ...item,
          desc: '' + (e instanceof Error ? e.message : e),
          enable: false,
        }
      }
    });
}

watch(() => props.taskPid, loadList);
onMounted(loadList);

const currentTaskDefItems = ref<(TaskMenuDefItem & { collectModuleId: number })[]>([]);
const currentTaskBanner = ref('');
const handleClick = (item: TaskMenuDefItem) => {
  
  if (!item.enable && !authStore.isAdmin) {
    uni.showToast({
      title: '您没有完成任务的权限，如需要请联系管理员',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  if (item.goForm instanceof Array) {
    if (props.isView)
      goPreviewForm(...item.goForm);
    else
      goForm(...item.goForm);
    return;
  }
  else if (item.goForm) {
    navTo('/pages/dig/forms/task', {
      ...props,
      taskName: item.goForm.name,
      taskTitle: item.title,
      taskPid: (item as any).id,
      isView: props.isView,
    })
    return;
  }
  if (item.onClick) {
    item.onClick();
  }
}
</script>
