<template>
  <CommonTopBanner :title="currentTitle">
    <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">
          <FlexRow align="center" gap="space.sm" backgroundColor="white" radius="50">
            <SearchBar
              v-model="searchText"
              placeholder="搜一搜" 
              :innerStyle="{ width: '200rpx' }"
              @search="search"
            />
            <picker @change="handleCatalogChange" :value="currentCatalogIndex" :range="currentCatalogList" range-key="name">
              <FlexRow center gap="space.md">
                <Text :text="(currentCatalog?.title || '未选择栏目')" :lines="1" :maxWidth="180" />
                <Icon icon="arrow-down" :size="40" />
              </FlexRow>
            </picker>
            <Width :width="10" />
          </FlexRow>

          <PrimaryButton 
            text="+ 编写"
            @click="newData"
          />
        </FlexRow>
        <NotVolTip 
          v-if="!isJoined" 
          @goJoin="goJoin"
        /> 
        <Height :height="5" />
        <SimplePageListLoader :loader="listLoader" :noEmpty="true">
          <FlexCol :gap="20">
            <BackgroundBox 
              v-for="item in listLoader.list.value"
              :key="item.id" 
              direction="row"
              backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxMid.png"
              :backgroundCutBorder="30"
              :backgroundCutBorderSize="30"
              :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" fontFamily="SongtiSCBlack">{{ item.title }}</H4>
                  <Text :size="23">{{ item.desc }}</Text>
                </FlexCol>
              </Touchable>
            </BackgroundBox>
          </FlexCol>
          <template #empty>
            <Empty 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 { computed, 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, type TaskMenuDefItem } 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, { CommonInfoModel } 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, { type VillageCatalogListItem } from '@/api/inhert/VillageApi';
import Icon from '@/components/basic/Icon.vue';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import BackgroundImageButton from '@/components/basic/BackgroundImageButton.vue';
import Width from '@/components/layout/space/Width.vue';
import PrimaryButton from '@/common/components/PrimaryButton.vue';
import NotVolTip from '@/pages/home/components/NotVolTip.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 = [] as CommonInfoModel[];

  if (params.collectModuleId === CollectableModulesIdMap['overview']) {
    //村社概览特殊处理
    const info = await VillageInfoApi.getInfoByVillageId(params.villageId);
    const overviewId = info.myOverviewId || info.overviewId;
    if (overviewId) {
      res = [
        new CommonInfoModel().setSelfValues({
          id: info.myOverviewId || info.overviewId || 0,
          title: info.title,
          image: info.image,
          villageVolunteerId: params.villageVolunteerId,
        }),
      ];
    }
  } else {
    res = await VillageInfoApi.getList(
      params.collectModuleId,
      params.subKey ? params.subId : undefined,
      params.subKey,
      params.villageId,
      undefined,
      currentCatalog.value?.id || 0,
      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;
  }
  navTo('common', { 
    id: -1,
    villageId: querys.value.villageId,  
    villageVolunteerId: querys.value.villageVolunteerId,  
    catalogId: currentCatalog.value?.id || 0,
    collectModuleId: currentLoadData.value.collectModuleId,  
    subId: currentLoadData.value.subId,  
    subTitle: currentLoadData.value.subTitle,
    subKey: currentLoadData.value.subKey,
  });
}
function goDetail(item: { id: number, villageVolunteerId: number }) {

  let goToFormDisplay = false;
  let canEdit = false;

  if (!authStore.isAdmin 
    && (!isJoined.value || item.villageVolunteerId !== volunteerInfo.value?.id)
  ) {
    //非当前村社志愿者或者不是自己提交的文章，只能查看详情
    //村社概览表单特殊处理
    if ([
      CollectableModulesIdMap['overview'],
      CollectableModulesIdMap['environment'], 
      CollectableModulesIdMap['distribution'],
      CollectableModulesIdMap['ich'],
      CollectableModulesIdMap['relic'],
      CollectableModulesIdMap['folkCulture'],
      CollectableModulesIdMap['building'],
    ].includes(currentLoadData.value.collectModuleId)) {
      goToFormDisplay = true;
    }
  } else {
    goToFormDisplay = true;
    canEdit = true;
  }

  if (goToFormDisplay) {
    navTo('common', {
      id: item.id,
      villageId: querys.value.villageId,
      villageVolunteerId: querys.value.villageVolunteerId,
      catalogId: currentCatalog.value?.id || 0,
      collectModuleId: currentLoadData.value.collectModuleId,
      isView: !canEdit,
    });
  } else {
    navTo('/pages/home/discover/details', {
      villageId: querys.value.villageId,
      id: item.id,
    });
  }
}
function search() {
  listLoader.reload();
}
function goJoin() {
  navTo('/pages/home/light/submit', {
    villageId: querys.value.villageId,
  });
}

const currentTitle = ref('');
const catalogs = ref<VillageCatalogListItem[]>([]);
const currentCatalogIndex = ref(0);
const currentCatalogList = computed(() => {
  return catalogs.value.map((p) => ({
    id: p.id,
    name: p.title,
  }));
});
const currentCatalog = ref<VillageCatalogListItem | null>(null);
const currentLoadData = ref({
  collectModuleId: 0,
  subId: 0,
  subKey: '',
  subTitle: '',
  catalogId: 0,
  villageId: 0,
  villageVolunteerId: 0,
});

function handleCatalogChange(e: any) {
  currentCatalogIndex.value = e.detail.value;
  loadListCatalog(catalogs.value[currentCatalogIndex.value] as VillageCatalogListItem);
}

function loadListCatalog(catalog: VillageCatalogListItem) {
  if (currentCatalog.value?.id === catalog.id) 
    return;
  currentCatalog.value = catalog;  
  try {
    const formDefine = getVillageInfoForm(querys.value.collectModuleId, -1);
    const goForm = [ 
      querys.value.collectModuleId, 
      catalog.typeId ?? -1, 
      formDefine?.[2].typeName, 
      querys.value.collectModuleId === CollectableModulesIdMap['overview'] ? 'common' : undefined,
      catalog.title,
      catalog.id
    ] as TaskMenuDefGoForm;

    currentLoadData.value = {
      collectModuleId: querys.value.collectModuleId,
      subId: goForm[1],
      subKey: goForm[2] || 'type',
      subTitle: goForm[4] || querys.value.title,
      catalogId: goForm[5] || 0,
      villageId: querys.value.villageId,
      villageVolunteerId: volunteerInfo.value?.id || 0,
    }

    console.log('currentLoadData', currentLoadData.value);
    
  } catch (e) {
    console.error(e);
    error.value = '任务不存在';
    return;
  }
  listLoader.load(true, currentLoadData.value)
}

const { querys } = useLoadQuerys({ 
  collectModuleId: 0,
  villageId: 0,  
  villageVolunteerId: 0,
  title: '',
}, async (querys) => {
  //普通用户进入预览模式
  await getIsVolunteer();
  isJoined.value = await getIsJoinedVillage(querys.villageId);

  function pushCatalogWithCurrentCatalog(catalog: VillageCatalogListItem) {
    if (catalog.collectModuleId === querys.collectModuleId) {
      catalogs.value.push(catalog);
    }
    catalog.childlist.forEach((c) => {
      pushCatalogWithCurrentCatalog(c);
    });
  }
  (await VillageApi.getCatalogList(
    querys.villageId, 
    authStore.isAdmin ? undefined : querys.villageVolunteerId,
  )).forEach((catalog) => {
    pushCatalogWithCurrentCatalog(catalog);
  });

  if (catalogs.value.length === 0) {
    error.value = `本村暂未开通此栏目 （${querys.collectModuleId}）`;
    return;
  }
  loadListCatalog(catalogs.value[0] as VillageCatalogListItem);

  currentTitle.value = querys.title || '共编村史';
});

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

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