<template>
  <CommonTopBanner title="AI帮你写微信贴图">
    <FlexCol position="relative" padding="space.lg" align="center">   
      <FlexCol position="absolute" :right="0" :top="0">
        <PrimaryButton
          text="发布"
          @click="publish"
        />
      </FlexCol>
      <ProvideVar
        :vars="{
          FieldBackgroundColor: 'transparent',
          UploaderListAddItemBackgroundImage: 'url(https://xy.wenlvti.net/app_static/images/village/ButtonUpload.png)',
          UploaderAddIcon: '',
        }"
      >
        <BackgroundBox
          backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxLarge.png"
          :backgroundCutBorder="[50,50,50,50]"
          :backgroundCutBorderSize="[50,50,50,50]"
          direction="column"
          gap="gap.md"
          width="95%"
          :padding="[40, 30]"
        >
          <Uploader 
            ref="uploader"
            listType="grid"
            :maxUploadCount="9" 
            :upload="uploadImage"
            @updateList="onUpdateList"
          />
          <Field v-model="title" type="text" placeholder="输入标题(可选)" :maxLength="30" showWordLimit />
          <Field 
            v-model="content" 
            type="text" 
            multiline 
            placeholder="输入内容（可选）" 
            :maxLength="1000" 
            rows="4" 
            showWordLimit 
          />
        </BackgroundBox>
      </ProvideVar>
      <Agent 
        v-model:title="title"
        v-model:content="content"
        v-model:images="images"
        @upload="uploader?.pick()"
        @close="showAgentPopup = false" 
      />
    </FlexCol>
  </CommonTopBanner>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { Debounce } from '@imengyu/imengyu-utils';
import { confirm, toast } from '@/components/dialog/CommonRoot';
import { useAuthStore } from '@/store/auth';
import { envVersion } from '@/common/config/AppCofig';
import CommonContent from '@/api/CommonContent';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import Field from '@/components/form/Field.vue';
import Uploader, { type UploaderInstance } from '@/components/form/Uploader.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import ProvideVar from '@/components/theme/ProvideVar.vue';
import Height from '@/components/layout/space/Height.vue';
import ImageButton from '@/components/basic/ImageButton.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Button from '@/components/basic/Button.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import IconButton from '@/components/basic/IconButton.vue';
import Popup from '@/components/dialog/Popup.vue';
import Agent from './agent.vue';
import LightVillageApi, { PostMessage } from '@/api/light/LightVillageApi';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import type { UploaderAction, UploaderItem } from '@/components/form/Uploader';
import PrimaryButton from '@/common/components/PrimaryButton.vue';

const { querys } = useLoadQuerys({
  tag: '',
  villageId: 0,
});
const authStore = useAuthStore();

const title = ref('');
const content = ref('');
const images = ref<{
  url: string;
  localUrl: string;
}[]>([]);

const uploader = ref<UploaderInstance>();

const showAgentPopup = ref(false);
const saveDraftDebunce = new Debounce(1000, () => {
  if (title.value || content.value || images.value.length > 0) {
    uni.setStorageSync('postDraft', {
      title: title.value,
      content: content.value,
      images: images.value,
    });
  }
});

watch(title, () => saveDraftDebunce.executeWithDelay());
watch(content, () => saveDraftDebunce.executeWithDelay());
watch(images, () => saveDraftDebunce.executeWithDelay());

function loadDraft() {
  const draft = uni.getStorageSync('postDraft');
  if (draft) {
    confirm({
      content: '您有上次编辑未完成的草稿，是否要从上次的编辑数据继续？',
      confirmText: '继续',
      cancelText: '取消',
      width: 580,
    }).then((res) => {
      if (res) {
        title.value = draft.title;
        content.value = draft.content;
        images.value = draft.images;
        uploader.value?.setList(images.value.map((image) => ({
          url: image.url,
          type: 'image',
          filePath: image.localUrl,
          state: image.url ? 'success' : 'notstart',
        })));
      } else {
        uni.removeStorageSync('postDraft');
      }
    });
  }
}
function uploadImage(item: UploaderAction) {
  item.onStart('正在上传');

  let task: UniApp.UploadTask | null = null;
  CommonContent.uploadFile(item.item.filePath, 'image', 'file', undefined, (_task) => {
    task = _task;
    task.onProgressUpdate((res) => {
      item.onProgress(res.progress);
    });
  })
    .then((res) => {
      item.onFinish({
        uploadedUrl: res.fullurl,
        previewUrl: res.fullurl,
      }, '上传成功');
    })
    .catch((err) => {
      item.onError(err);
    });
  return () => {
    task?.abort();
  };
}
function publish() {
  if (images.value.length === 0) {
    toast('请上传图片');
    return;
  }
  const data = {
    title: title.value,
    content: content.value,
    images: images.value.map((image) => image.localUrl),
    tags: [
      '亮乡源',
      `${querys.value.tag || '亮乡源'}话题${querys.value.villageId ? `·${querys.value.villageId}` : ''}·${authStore.userInfo?.id || '0'}`
    ],
  };
  console.log('data', data, authStore.userInfo);
  (uni as any).shareToOfficialAccount({
    ...data,
    success: () => {
      LightVillageApi.publishMessage(new PostMessage().setSelfValues({
        title: title.value,
        content: content.value,
        images: images.value.map((image) => image.url),
        image: images.value[0].url,
        path: `/pages/index`,
      })).then(() => {
        console.log('发布成功');
      }).catch((e) => {
        console.error(e);
      });
      uni.removeStorageSync('postDraft');
      toast('发布成功');
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    },
    fail: (error: any) => {
      console.error(error);
      toast('发布失败');
    },
  });
}

function onUpdateList(list: UploaderItem[]) {
  images.value = list.map((item) => ({
    url: item.uploadedPath || '',
    localUrl: item.filePath,
  }));
}

onMounted(() => {
  setTimeout(() => {
    loadDraft();
    if (envVersion === 'develop') {
      showAgentPopup.value = true;
    }
  }, 1000);
});
</script>