<template>
  <CommonTopBanner title="发贴图">
    <FlexCol position="relative" padding="space.lg" align="center">   
      <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]"
        >
          <Field v-model="title" type="text" placeholder="输入标题(可选)" :maxLength="30" />
          <Field 
            v-model="content" 
            type="text" 
            multiline 
            placeholder="说点什么吧..."
            :maxLength="1000" 
            rows="20" 
            :inputStyle="{
              height: '700rpx',
            }"
            showWordLimit 
          />
          <Uploader 
            ref="uploader"
            listType="grid"
            :maxUploadCount="9" 
            :upload="uploadImage"
            @updateList="onUpdateList"
            @allUploaded="onAllUploaded"
          />
          <FlexRow justify="flex-end" align="center" gap="gap.md">
            <Button text="AI看图写作" @click="openImageWriting" />
            <Tbutton 
              :title="title"
              :content="content"
              :images="images"
              @showAi="showAgentPopup = true" 
            />
          </FlexRow>
        </BackgroundBox>
        <Height :height="50" />
        <FlexRow center>
          <PrimaryButton
            text="发布"
            width="500rpx"
            @click="publish"
          />
        </FlexRow>
      </ProvideVar>
      <Agent 
        ref="agentRef"
        v-model:showAgentPopup="showAgentPopup"
        v-model:title="title"
        v-model:content="content"
        v-model:images="images"
        :villageInfo="villageInfoForAI.content.value ?? undefined"
        :tag="querys.tag"
        @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, formatError } from '@imengyu/imengyu-utils';
import { confirm, toast, alert } from '@/components/dialog/CommonRoot';
import { useAuthStore } from '@/store/auth';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
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 FlexRow from '@/components/layout/FlexRow.vue';
import Popup from '@/components/dialog/Popup.vue';
import Agent from './components/agent.vue';
import OfficialApi, { PostMessage } from '@/api/light/OfficialApi';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import PrimaryButton from '@/common/components/PrimaryButton.vue';
import Tbutton from './components/tbutton.vue';
import Height from '@/components/layout/space/Height.vue';
import type { UploaderAction, UploaderItem } from '@/components/form/Uploader';
import { back, backAndCallOnPageBack } from '@/components/utils/PageAction';
import { confirm as uniConfirm } from '@/components/utils/DialogAction';
import LightVillageApi from '@/api/light/LightVillageApi';
import Button from '@/components/basic/Button.vue';

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

  const info = uni.getSystemInfoSync();
  console.log(info.platform);
  
  if (!(uni as any).shareToOfficialAccount || (info.platform !== 'android' && info.platform !== 'ios')) {
    uniConfirm({
      title: '提示',
      content: '抱歉，微信目前不支持在电脑端编写贴图，您可以在手机版微信中编写贴图哦！',
    }).then(() => {
      back();
    })
    return;
  }

  villageInfoForAI.load();
});
const authStore = useAuthStore();

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

const agentRef = ref<InstanceType<typeof Agent>>();
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,
    });
  }
});
const villageInfoForAI = useSimpleDataLoader(async () => {
  const villageId = querys.value.villageId;
  if (villageId) 
    return await LightVillageApi.getVillageDetails(villageId);
  return null;
}, false);

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 || '亮乡源'}`
    ],
  };
  console.log('发布数据', data, authStore.userInfo);
  (uni as any).shareToOfficialAccount({
    ...data,
    success: (postObj: { postUrl: string }) => {
      OfficialApi.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`,
        villageId: querys.value.villageId,
        userId: authStore.userId,
        jumpUrl: postObj.postUrl,
        topicName: querys.value.tag || '亮乡源',
      })).then(() => {
        console.log('发布成功');
      }).catch((e) => {
        console.error(e);
      });
      uni.removeStorageSync('postDraft');
      toast('发布成功, 文章可能需要审核稍后才能展示');
      setTimeout(() => {
        backAndCallOnPageBack('refreshOfficialAccount', { })
      }, 2000);
    },
    fail: (error: any) => {
      console.error(error);
      const errmsg = formatError(error);
      if (!errmsg.includes('cancel')) 
        toast('发布失败: ' + errmsg);
    },
  });
}
function openImageWriting() {
  agentRef.value?.openImageWriting();
}

function onAllUploaded() {
  agentRef.value?.openImageWritingDialogIfLastClicked();
}
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>