<template>
  <CommonTopBanner :title="subTitle">
    <FlexCol padding="space.md" gap="space.md">
      <Result v-if="error" 
        :title="error"
      />
      <template v-else>
        <FlexRow justify="space-between" align="center" gap="space.sm">
          <SearchBar
            v-model="searchText"
            placeholder="搜一搜" 
            :innerStyle="{ width: querys.isView ? '600rpx' : '460rpx' }"
            @search="search"
          />
          <PrimaryButton 
            v-if="!querys.isView"
            text="+ 编写"
            @click="newData"
          />
        </FlexRow>
        <Height :height="5" />
        <SimplePageListLoader :loader="listLoader" :noEmpty="true">
          <FlexCol :gap="20">
            <BoxMid 
              v-for="item in listLoader.list.value"
              :key="item.id" 
              direction="row"
              :padding="[16, 30]"
              align="center"
            >
              <Touchable 
                :gap="20"
                :padding="[15,20]"
                touchable
                flex="1"
                @click="goDetail(item)"
              >
                <Image 
                  :src="item.image"
                  :showFailed="false"
                  :width="100"
                  :height="100"
                  radius="radius.sm"
                  mode="aspectFill"
                />
                <FlexCol>
                  <H4 :size="36">{{ item.title }}</H4>
                  <Text :size="23">{{ item.desc }}</Text>
                </FlexCol>
              </Touchable>
            </BoxMid>
          </FlexCol>
          <template #empty>
            <Empty v-if="querys.isView" image="search" description="暂无数据，等待志愿者编写中..." />
            <Empty v-else image="search" description="这里还没有数据，快来编写完善吧！">
              <Height :height="40" />
              <Button type="primary" :text="`+ 新增${subTitle}数据`" @click="newData" />
            </Empty>
          </template>
        </SimplePageListLoader>
      </template>
      <XBarSpace />
    </FlexCol>
  </CommonTopBanner>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onPullDownRefresh } from '@dcloudio/uni-app';
import { DataDateUtils } from '@imengyu/js-request-transform';
import { useSimplePageListLoader } from '@/components/composeabe/loader/SimplePageListLoader';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { useAuthStore } from '@/store/auth';
import { type TaskMenuDefGoForm } from './tasks';
import { useUserTools } from '@/common/composeabe/UserTools';
import { navTo } from '@/components/utils/PageAction';
import { confirm, alert } from '@/components/utils/DialogAction';
import SimplePageListLoader from '@/components/loader/SimplePageListLoader.vue';
import VillageInfoApi from '@/api/inhert/VillageInfoApi';
import Image from '@/components/basic/Image.vue';
import Empty from '@/components/feedback/Empty.vue';
import Button from '@/components/basic/Button.vue';
import SearchBar from '@/components/form/SearchBar.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Text from '@/components/basic/Text.vue';
import Height from '@/components/layout/space/Height.vue';
import H4 from '@/components/typography/H4.vue';
import Touchable from '@/components/feedback/Touchable.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import Result from '@/components/feedback/Result.vue';
import { CollectableModulesIdMap, getVillageInfoForm } from './forms';
import VillageApi from '@/api/inhert/VillageApi';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import BackgroundImageButton from '@/components/basic/BackgroundImageButton.vue';
import PrimaryButton from '@/common/components/PrimaryButton.vue';
import BoxMid from '@/common/components/box/BoxMid.vue';

const subTitle = ref('');
const searchText = ref('');
const { getIsVolunteer, getIsJoinedVillage, volunteerInfo } = useUserTools();
const isJoined = ref(false);
const authStore = useAuthStore();
const error = ref('');

const listLoader = useSimplePageListLoader<{
  id: number,
  image: string,
  title: string,
  desc: string,
  villageVolunteerId: number,
}, {
  villageId: number,  
  villageVolunteerId: number,
  collectModuleId: number,
  subId: number,
  subKey: string,
}>(8, async (page, pageSize, params) => {
  if (!params )
    throw new Error("未传入参数，当前页面需要参数");
  if (!params.collectModuleId)
    throw new Error("params.collectModuleId");
  if (!params.villageId)
    throw new Error("params.villageId");
  let res = await VillageInfoApi.getList(
    params.collectModuleId,
    params.subKey ? params.subId : undefined,
    params.subKey,
    params.villageId,
    undefined,
    querys.value.catalogId,
    page,
    pageSize,
  )
  if (searchText.value)
    res = res.filter((p) => p.title.includes(searchText.value));
  const list = res.map((item) => {
    return {
      id: item.id,
      image: item.image,
      title: item.title,
      villageVolunteerId: item.villageVolunteerId,
      desc: DataDateUtils.formatDate(item.updatedAt, 'YYYY-MM-dd') + (
        authStore.isAdmin ? (' 投稿人：' + item.villageVolunteerName) : ''
      )
    }
  })
  return {
    list: list,
    total: list.length,
  };
}, false);

function newData() {
  if (!isJoined.value) {
    confirm({ 
      title: '提示', 
      content: "您还不是当前村社的志愿者，请先加入志愿者队伍", 
      confirmText: '去点亮',
    }).then((res) => {
      if (res) {
        goJoin();
      }
    });
    return;
  }
  if (querys.value.isView) {
    alert({ title: '提示', content: "查看模式下不能新增数据" });
    return;
  }
  navTo('common', { 
    id: -1,
    villageId: querys.value.villageId,  
    villageVolunteerId: querys.value.villageVolunteerId,  
    catalogId: querys.value.catalogId,
    collectModuleId: querys.value.collectModuleId,  
    subId: querys.value.subId,  
  });
}
function goDetail(item: { id: number, villageVolunteerId: number }) {
  navTo('common', { 
    id: item.id,
    villageId: querys.value.villageId,
    villageVolunteerId: querys.value.villageVolunteerId,
    catalogId: querys.value.catalogId,
    collectModuleId: querys.value.collectModuleId,
    subKey: querys.value.subKey,
    subId: querys.value.subId,
    subTitle: querys.value.subTitle,
    //非当前村社志愿者或者不是自己提交的文章，只能查看详情
    isView: querys.value.isView ? true : (!authStore.isAdmin 
      && (!isJoined.value || item.villageVolunteerId !== volunteerInfo.value?.id) ? true : false),
  });
}
function search() {
  listLoader.reload();
}
function goJoin() {
  navTo('/pages/home/light/submit', {
    villageId: querys.value.villageId,
  });
}

const { querys } = useLoadQuerys({ 
  villageId: 0,  
  villageVolunteerId: 0,
  catalogId: 0,
  collectModuleId: 0,
  subKey: '',
  subId: 0,
  subTitle: '',
  isView: false,
}, async (querys) => {
  isJoined.value = await getIsJoinedVillage(querys.villageId);

  if (querys.collectModuleId) {
    //普通用户进入预览模式
    await getIsVolunteer();

    try {
      const formDefine = getVillageInfoForm(querys.collectModuleId, -1);
      querys.subId = -1;
      querys.subKey = formDefine?.[2].typeName || 'type';
      querys.villageVolunteerId = volunteerInfo.value?.id || 0;
      listLoader.load(false, {
        villageId: querys.villageId,
        villageVolunteerId: querys.villageVolunteerId,
        collectModuleId: querys.collectModuleId,
        subId: querys.subId,
        subKey: querys.subKey,
      })
    } catch {
      error.value = '任务不存在';
      return;
    }

  } else {
    //原有采集页进入
    listLoader.load(false, querys)
  }

  if (querys.subTitle) {
    subTitle.value = querys.subTitle;
    uni.setNavigationBarTitle({  title: subTitle.value + '列表', })
  }
});

onPullDownRefresh(() => {
  listLoader.reload();
});

defineExpose({
  onPageBack(name: string, param: any) {
    if (param && param.needRefresh)
      listLoader.reload();
  }
})
</script>
