<template>
  <CommonRoot>
    <FlexCol :padding="30">
      <SearchBar
        v-model="searchText"
        placeholder="搜一搜" 
        @search="search"
      />

      <SimplePageListLoader :loader="listLoader" :noEmpty="true">
        <template #empty>
          <Empty image="search" text="暂无待审核志愿者" />
        </template>
        <FlexCol :gap="20" :margin="[20,0,0,0]">
          <VolunteerItem
            v-for="item in listLoader.list.value"
            :key="item.id" 
            :item="item"
          >
            <FlexRow :gap="20">
              <Image 
                :src="item.image"
                width="100rpx"
                height="100rpx"
                :defaultImage="UserHead"
                :failedImage="UserHead"
                round 
              />
              <FlexCol>
                <Text :fontSize="36" bold :text="`${item.name} ${item.sex === 0 ? '男' : '女'}`" />
                <Text :fontSize="26" :text="`手机：${item.mobile}`" />
                <Text :fontSize="26" :text="`地址：${item.address || ''}`" />
                <Text :fontSize="26" :text="`可采编：${item.collectModuleText || '暂无'}`" />
              </FlexCol>
            </FlexRow>
            <template #action>
              <Button type="primary" icon="task-filling" radius="radius.lgr" @click="handleShowDetail(item)" />
            </template>
          </VolunteerItem>
        </FlexCol>
      </SimplePageListLoader>

      <Popup
        v-model:show="reviewPopup"
        :title="`审核 ${reviewItem?.title}`"
        size="80%"
        round
        position="bottom"
        closeable
      >
        <FlexCol :gap="30" :padding="30">
          <DynamicForm
            v-if="reviewItem"
            :model="reviewItem"
            :options="reviewFormDefine"
            :formGlobalParams="querys"
          />
          <Button type="success" @click="handleReview(VolunteerInfo.STATUS_APPROVED)">通过审核</Button>
          <Button type="danger" @click="handleReview(VolunteerInfo.STATUS_REJECTED)">驳回审核</Button>
        </FlexCol>
      </Popup>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { useSimplePageListLoader } from '@/components/composeabe/loader/SimplePageListLoader';
import { closeToast, confirm, toast } from '@/components/dialog/CommonRoot';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { getVolunteerForm } from './data/volunteer';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import VillageApi, { VolunteerInfo } from '@/api/inhert/VillageApi';
import SimplePageListLoader from '@/components/loader/SimplePageListLoader.vue';
import Button from '@/components/basic/Button.vue';
import Image from '@/components/basic/Image.vue';
import Text from '@/components/basic/Text.vue';
import Empty from '@/components/feedback/Empty.vue';
import SearchBar from '@/components/form/SearchBar.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import VolunteerItem from './components/VolunteerItem.vue';
import Popup from '@/components/dialog/Popup.vue';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';

const UserHead = 'https://mncdn.wenlvti.net/app_static/xiangyuan/images/user/avatar.png';

const { querys } = useLoadQuerys({ 
  villageId: 0,
}, () => {
  listLoader.reload();
});

const searchText = ref('');
const listLoader = useSimplePageListLoader(8, async (page, pageSize, params) => {
  if (page === 1) {
    let res = await VillageApi.getVillageVolunteerList(querys.value.villageId, VolunteerInfo.STATUS_PENDING);
    if (searchText.value)
      res = res.filter((p) => p.name.includes(searchText.value));
    res.forEach((item) => {
      item.title = `${item.name} ${item.sex === 0 ? '男' : '女'}`;
      item.desc = ` 手机号：${item.mobile} 地址：${item.address || ''} 认领说明：${item.claimReason || ''}`;
    })
    return {
      page,
      total: res.length,
      list: res,
    }
  }
  return {
    page,
    total: 0,
    list: [],
  }
});

const reviewPopup = ref(false);
const reviewItem = ref<VolunteerInfo>();
const reviewFormRef = ref<IDynamicFormRef>();
const reviewFormDefine = ref<IDynamicFormOptions>();

function handleShowDetail(item: VolunteerInfo) {
  reviewItem.value = item;
  reviewPopup.value = true;
}
async function handleReview(status: number) {
  if (!reviewItem.value)
    return;

  if (!await confirm({
    title: '确认审核吗？',
    content: `确认审核${status === VolunteerInfo.STATUS_APPROVED ? '通过' : '驳回'}${reviewItem.value.title}吗？`,
  }))
    return;

  reviewPopup.value = false;
  toast({
    type: 'loading',  
    content: '请稍后',
  })
  try {
    await VillageApi.reviewVillageVolunteer(querys.value.villageId, reviewItem.value.id, status);
    toast({  type: 'success', content: '审核成功' });
  } catch (e) {
    showError(e);
  } finally {
    closeToast();
  }
}
function search() {
  listLoader.reload();
}

onMounted(() => {
  reviewFormDefine.value = {
    ...getVolunteerForm({
      canSetCatalog: false,
      villageId: querys.value.villageId,
      noPassword: true,
      isNew: ref(false),
      formRef: reviewFormRef,
    }),
    readonly: true,
  }
})
</script>
