<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 
              v-model="images" 
              listType="grid"
              :maxUploadCount="9" 
              :upload="uploadImage"
            />
            <Field v-model="title" type="text" placeholder="请输入标题" :maxLength="30" showWordLimit bac />
            <Field v-model="content" type="text" multiline placeholder="请输入内容" :maxLength="1000" rows="10" 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 size="60vh" round>
      <Agent />
    </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 } from '@/components/dialog/CommonRoot';
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 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 } 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';

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

const title = ref('');
const content = ref('');
const images = ref([] as string[]);

const showAgentPopup = ref(false);
const saveDraftDebunce = new Debounce(1000, () => {
  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: '取消',
    }).then((res) => {
      if (res) {
        title.value = draft.title;
        content.value = draft.content;
        images.value = draft.images;
      }
    });
  }
}
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() {
  console.log('publish', title.value, content.value, images.value);
}

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