<template>
  <CommonTopBanner title="文章编辑" customBack @backPressed="cancel">
    <FlexCol height="100vh">
      <sp-editor
        :toolbar-config="{
          excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
          iconSize: '18px'
        }"
        :maxlength="maxLength"
        @init="initEditor"
        @input="inputOver"
        @upinImage="upinImage"
        @overMax="overMax"
      />
      <FlexCol v-if="enableAi" padding="padding.md">
        <Uploader 
          ref="uploader"
          listType="grid"
          :maxUploadCount="9" 
          :upload="aliOss"
          @updateList="onUpdateList"
          @allUploaded="onAllUploaded"
        />
        <FlexRow justify="flex-end" align="center" gap="gap.md">
          <Button text="AI看图写作" @click="openImageWriting" />
          <Tbutton
            :content="currentContent"
            :title="currentTitle"
            :images="currentImages"
            @showAi="showAgentPopup = true" 
          />
        </FlexRow>
      </FlexCol>
      <Height :height="50" />
      <FlexRow center>
        <PrimaryButton
          text="保存"
          width="500rpx"
          @click="save"
        />
      </FlexRow>
      <XBarSpace />
      <Agent 
        ref="agentRef"
        v-model:showAgentPopup="showAgentPopup"
        v-model:title="currentTitle"
        v-model:content="currentContent"
        v-model:images="currentImages"
        :extraInfoFoAi="extraAiInfo"
        @recharge="handleRecharge"
        @upload="uploader?.pick()"
        @close="showAgentPopup = false" 
      />
    </FlexCol>
  </CommonTopBanner>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useAuthStore } from '@/store/auth';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { alert, confirm } from '@/components/utils/DialogAction';
import { back, backAndCallOnPageBack } from '@/components/utils/PageAction';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { useAliOssUploadCo } from '@/common/components/upload/AliOssUploadCo';
import { useRecharge } from './composables/recharge';
import spEditor from '../../components/sp-editor/components/sp-editor/sp-editor.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import Button from '@/components/basic/Button.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import Height from '@/components/layout/space/Height.vue';
import PrimaryButton from '@/common/components/PrimaryButton.vue';
import Tbutton from './components/tbutton.vue';
import Agent from './components/agent.vue';
import Uploader, { type UploaderInstance } from '@/components/form/Uploader.vue';
import type { UploaderItem } from '@/components/form/Uploader';

const { querys } = useLoadQuerys({
  enableAi: true,
  extraAiInfo: '',
  uploadSubpath: 'common',
  villageId: 0,
  maxLength: 1000,
}, () => {
  maxLength.value = querys.value.maxLength;
  enableAi.value = querys.value.enableAi;
  uploadSubpath.value = querys.value.uploadSubpath;
  extraAiInfo.value = querys.value.extraAiInfo.split(',');
  load();
});

const enableAi = ref(false);
const maxLength = ref(-1);
const uploadSubpath = ref('');
const currentTitle = ref('');
const currentContent = ref('');
const currentImages = ref<string[]>([]);

const authStore = useAuthStore();
const uploader = ref<UploaderInstance>();
const agentRef = ref<InstanceType<typeof Agent>>();

const { 
  handleRecharge, 
  handleRechargePaySuccess 
} = useRecharge(agentRef as any);

function cancel() {
  confirm({
    title: '提示',
    content: '是否放弃编辑？',
  }).then((res) => {
    if (res)
      back();
  })
}
function save() {
  uni.setStorage({
    key: 'editorContent',
    data: {
      title: currentTitle.value,
      images: currentImages.value,
      content: currentContent.value,
    },
    success: () => backAndCallOnPageBack('editor', {}),
    fail: (e) => showError(e),
  })
}
function load() {
  uni.getStorage({
    key: 'editorContent',
    success: (success) => {
      currentTitle.value = success.data.title;
      currentContent.value = success.data.content;
      currentImages.value = success.data.images;
      setTimeout(() => {
        uploader.value?.setList(currentImages.value.map((image) => ({
          url: image,
          type: 'image',
          filePath: image,
          uploadedPath: image,
          state: image ? 'success' : 'notstart',
        })));
      }, 1000);
    },
  })
}

const showAgentPopup = ref(false);
const extraAiInfo = ref<string[]>([]);
const aliOss = useAliOssUploadCo(uploadSubpath, {
  getVillageId: () => querys.value.villageId,
  overflow: () => {
    //todo
  },
});

function openImageWriting() {
  agentRef.value?.openImageWriting();
}
function onAllUploaded() {
  agentRef.value?.openImageWritingDialogIfLastClicked();
}
function onUpdateList(list: UploaderItem[]) {
  currentImages.value = list.map((item) => item.uploadedPath || '');
}


/**
* 获取输入内容
*/
function inputOver(e: { html: string; text: string; }) {
  // 可以在此处获取到编辑器已编辑的内容
  currentContent.value = e.html;
}
/**
 * 超出最大内容限制
 * @param {Object} e {html,text} 内容的html文本，和text文本
 */
function overMax(e: { html: string; text: string; }) {
  // 若设置了最大字数限制，可在此处触发超出限制的回调
  console.log('==== overMax :', e)
}
function initEditor(editor: any) {
  editor.setContents({
    html: currentContent.value
  })
}
function upinImage(tempFiles: any, editorCtx: any) {
  let path;
  // #ifdef MP-WEIXIN
  path = tempFiles[0].tempFilePath; 
  // #endif
  // #ifndef MP-WEIXIN
  path = tempFiles[0].path;
  // #endif

  //上传
  uploader.value?.addItemAndUpload({
    previewPath: path,
    filePath: path,
    state: 'notstart',
  }).then((res) => {  
    editorCtx.insertImage({
      src: res.uploadedPath,
      width: '80%',
      success: function () {}
    })
  }).catch((e) => showError(e, '上传图片失败'));
}

defineExpose({
  onPageBack(name: string, data: any) {
    if (name === 'paySuccessAndRefresh') {
      handleRechargePaySuccess();
    }
  },
});
</script>