<template>
  <CommonRoot>
    <FlexCol :innerStyle="{
      backgroundImage: 'url(https://xy.wenlvti.net/app_static/images/dig/TopBanner.png)',
      backgroundSize: '100% auto',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'top center',
      minHeight: '100vh',
    }">
      <StatusBarSpace />
      <NavBar title="发布微信贴图" leftButton="back" rightButton="add" />
      <FlexCol padding="space.lg">
        <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"
            :padding="[40, 30]"
          >
            <Uploader 
              ref="uploader"
              listType="grid"
              :maxUploadCount="9" 
              :upload="uploadImage"
              @updateList="onUpdateList"
            />
            <Field v-model="title" type="text" placeholder="输入标题(可选)" :maxLength="30" showWordLimit bac />
            <Field 
              v-model="content" 
              type="text" 
              multiline 
              placeholder="请输入内容（可选）" 
              :maxLength="1000" 
              rows="20" 
              :inputStyle="{
                height: '600rpx',
              }"
              showWordLimit 
            />
          </BackgroundBox>
        </ProvideVar>
        <Height :height="50" />
        <ImageButton
          src="https://xy.wenlvti.net/app_static/images/village/ButtonPrimary.png"
          text="发布"
          width="500rpx"
          height="80rpx"
          @click="publish"
        />
      </FlexCol>

      <BackgroundBox 
        position="fixed" :inset="{ b: 0, l: 0, r: 0 }"
        backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxLarge.png"
        :backgroundCutBorder="[50,50,0,50]"
        :backgroundCutBorderSize="[50,50,0,50]"
        direction="column"
        :padding="[20, 10]"
      >
        <FlexRow padding="space.md" align="center" justify="space-between">
          <FlexRow align="center" justify="center">
            <Button icon="https://xy.wenlvti.net/app_static/images/village/IconAi.png" @click="showAgentPopup = true">AI伴写</Button>
          </FlexRow>
          <FlexRow align="center" justify="center">
            <IconButton
              icon="setting"
              width="40rpx"
              height="40rpx"
            />
          </FlexRow>
        </FlexRow>
        <XBarSpace />
      </BackgroundBox>
    </FlexCol>
    <Popup v-model:show="showAgentPopup" position="bottom" closeable :closeIcon="false" size="60vh" round>
      <Agent 
        v-model:title="title"
        v-model:content="content"
        v-model:images="images"
        @upload="uploader?.pick()"
        @close="showAgentPopup = false" 
      />
    </Popup>
  </CommonRoot>
</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 CommonRoot from '@/components/dialog/CommonRoot.vue';
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 StatusBarSpace from '@/components/layout/space/StatusBarSpace.vue';
import NavBar from '@/components/nav/NavBar.vue';
import ProvideVar from '@/components/theme/ProvideVar.vue';
import type { UploaderAction, UploaderItem } from '@/components/form/Uploader';
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';

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>