<template>

    <div style="padding-bottom: 100px;">
      <a-breadcrumb>
        <a-breadcrumb-item>WebChat</a-breadcrumb-item>
        <a-breadcrumb-item>控制台</a-breadcrumb-item>
        <a-breadcrumb-item>公众号</a-breadcrumb-item>
        <a-breadcrumb-item>文章编辑</a-breadcrumb-item>
      </a-breadcrumb>

      <div class="edit-container">
        <Toolbar
            style="border: none; margin-top: 20px; background-color: whitesmoke; margin-bottom: 20px;"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <div class="article-edit-container">
          <div class="edit-body-container" style="min-height: 400px; height: auto;">
              <input class="edit-title" v-model="title" placeholder="文章标题">
              <Editor id="edit-content"
                  v-model="content"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
          </div>
          <div class="edit-plugin-container">
            <div class="edit-plugin-container-title">
              封面和摘要
            </div>
            <div style="display: flex;">
              <a-upload
              class="article-cover"
                name="articleCover"
                :action="uploadUrl"
                list-type="picture-card"
                :show-upload-list="false"
                :before-upload="beforeUpload"
              >
                <div v-if="!articleCover">
                  <a-icon type="plus" />
                  <div style="margin-top: 8px">上传封面</div>
                </div>
                <div v-else>
                  <img :src="articleCover" alt="封面图" style="width: 100%; display: block" />
                </div>
              </a-upload>
              <a-textarea
                style=" margin-left: 20px; height: 125px;"
                v-model:value="description"
                placeholder="文章摘要"
              />
            </div>
          </div>
          <div class="edit-plugin-container">
            <div class="edit-plugin-container-title">
              绑定公众号
            </div>
            <div>
              <a-select
                show-search
                placeholder="请选择推文公众号"
                style="width: 200px"
                :options="officalAccountOptions"
                @change="handleOfficialChange"
              >
              </a-select>
            </div>
          </div>
          <div class="edit-plugin-container">
            <div class="edit-plugin-container-title">
              计划推送时间
            </div>
            <div>
              <a-date-picker show-time v-model:value="planPushTime">
                <template #renderExtraFooter>extra footer</template>
              </a-date-picker>
            </div>
          </div>
          <div class="edit-plugin-container">
            <div class="edit-plugin-container-title">
              外部链接（非必填）
            </div>
            <div>
              <a-input class="edit-input" v-model:value="redirectUrl" placeholder="如果指定外部链接则优先跳转到指定链接地址" />
            </div>
          </div>
          <div class="edit-plugin-container">
            <div class="edit-plugin-container-title">
              文章标签
            </div>
            <div>
              <a-input class="edit-input" v-model:value="signs" placeholder="多个标签请用英文逗号分割，如：标签A,标签B,标签C" />
            </div>
          </div>
          <div class="edit-plugin-container">
            <div>
              <a-button type="primary" @click="submitArticle" style="width: 200px; height: 45px; background-color: black;">推送文章</a-button>
            </div>
          </div>
        </div>
    </div>
</div>

</template>

<script>
import axios from 'axios';
import { message } from 'ant-design-vue';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { useRoute, useRouter } from 'vue-router';

export default {
  components: { Editor, Toolbar },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const oauthCode = ref(route.query.oauthCode || new URLSearchParams(window.location.search).get('oauthCode'));
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    const title = ref('')
    const description = ref('')
    const signs = ref('')
    const redirectUrl = ref('')
    const officialAccount = ref('')
    const planPushTime = ref(null); 
    // 内容 HTML
    const content = ref('')
    const officalAccountOptions = ref([])
    const articleCover = ref(null); 
    const uploadUrl = '/admin-service/file/upload';
    
    const handleOfficialChange = (value) => {
      officialAccount.value = value;
    }

    const handleArticleCoverUpload = async (file) => {
        const formData = new FormData();
        formData.append('file', file);
        try {
          const response = await axios.post(uploadUrl, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'oauth-code': oauthCode.value,
              'origin-url': window.location.href,
              'upload-path': 'images/avatar'
            }
          });
          if (response.data.code === 40001) {
            window.location.href = response.data.redirect_url;
          }
          // 假设服务器返回头像的 URL
          articleCover.value = response.data.data.url; 
        } catch (error) {
          console.error('Error uploading avatar:', error);
        }
      };

      const beforeUpload = async (file) => {
        // 文件验证逻辑，例如限制文件大小和类型
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJpgOrPng) {
          message.error('请上传 JPG 或 PNG 格式的图片');
          return false;
        }
        if (!isLt2M) {
          message.error('图片大小不能超过 2MB');
          return false;
        }
        await handleArticleCoverUpload(file);
        return false;
      };

    const listOficalAccounts = async () => {
        try {
            const response = await axios.get(`/admin-service/account/page`, {
              params: {
                roleCode: 6,
                pageNo: 1,
                pageSize: 20
              },
              headers: {
                'oauth-code': oauthCode.value,
                'origin-url': window.location.href
              }
            });
            if (response.data.code === 40001) {
              // 未登录
              window.location.href = response.data.redirect_url;
            }
            // 使用 map 方法进行转换
            officalAccountOptions.value = response.data.data.map(item => ({
                value: item.userId,
                label: item.userName
            }));
        } catch (error) {
            message.error('公众号列表加载失败');
        }
    }

    listOficalAccounts();

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      
      
    })

    const toolbarConfig = {}
    const editorConfig = {
      placeholder: '请输入内容...'
    };


    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
      const { MENU_CONF } = editor.getConfig()
      MENU_CONF['uploadImage'] = {
        server: '/admin-service/file/upload/editor',
        fieldName: 'file',
        allowedFileTypes: ['image/*'],
        
        // 自定义 headers
        headers: {
          // 'Content-Type': 'multipart/form-data',
          'oauth-code': oauthCode.value,
          'origin-url': window.location.href,
          'upload-path': 'article/editor'
        },

        // 跨域携带 cookie（如果需要）
        withCredentials: true,

        // 上传前处理
        onBeforeUpload(file) {
          console.log('【上传文件】', file)
          return file // 返回 false 则终止上传
        },

        // 自定义插入
        customInsert(res, insertFn) {
          console.log('【上传响应】', res)
          if (res.code === 40001) {
            window.location.href = res.redirect_url
            return
          }
          if (res.code !== 200) {
            message.error(res.message || '上传失败')
            return
          }
          const url = res.data?.url || res.data?.imageUrl
          if (!url) {
            message.error('图片地址获取失败')
            return
          }
          insertFn(url, '', '')
        },

        // 错误处理
        onError(file, err, res) {
          console.error('【上传错误】', { file, err, res })
          message.error(`上传失败: ${err?.message || '服务器错误'}`)
        }
      }
    }

    // 公众号推文
    const submitArticle = async () => {
      if (!title.value) {
            message.error('标题不能为空');
            return;
        }
        if (!content.value) {
            message.error('正文不能为空');
            return;
        }
        if (!articleCover.value) {
            message.error('封面图不能为空');
            return;
        }
        if (!officialAccount.value) {
            message.error('未绑定公众号');
            return;
        }
        if (!signs.value) {
            message.error('标签不能为空');
            return;
        }
        if (!description.value) {
            message.error('摘要不能为空');
            return;
        }
         // 将 planPushTime 转换为 13 位时间戳
         let planPushTimeStamp = null;
            if (planPushTime.value) {
                planPushTimeStamp = planPushTime.value.valueOf();
            }
        try {
            const response = await axios.post('/admin-service/official/article/submit', 
              {
                publicAccount: officialAccount.value,
                title: title.value,
                signs: signs.value,
                description: description.value,
                content: content.value,
                redirectUrl: redirectUrl.value,
                planPushTime: planPushTimeStamp,
                cover: articleCover.value
              }, 
              {
                headers: {
                  'oauth-code': oauthCode.value,
                  'origin-url': window.location.href
                }
              }
            );
            if (response.data.code === 200) {
                message.success('文章已提交');
                 // 跳转到文章列表页
                router.push({ name: 'officialArticleManagement' });
            } else {
                message.error(response.data.message || '文章提交失败');
            }
        } catch (error) {
            message.error('文章提交失败');
        }
    } 

    return {
      title,
      description,
      signs,
      redirectUrl,
      officialAccount,
      articleCover,
      uploadUrl,
      editorRef,
      content,
      planPushTime,
      officalAccountOptions,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      listOficalAccounts,
      handleArticleCoverUpload,
      beforeUpload,
      submitArticle,
      handleOfficialChange
    }
  },
}
</script>

<style>
.edit-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.article-edit-container {
  width: 750px;
  padding: 50px 70px 100px 70px;
  box-shadow: 0px 0px 5px rgb(222, 221, 221);
  border-radius: 5px;
  overflow: hidden;
  border: 1px solid rgb(241, 239, 239);
}
.edit-body-container {
    width: 100%;
    min-width: 600px;
}
.edit-title {
    width: 100%;
    height: 60px;
    line-height: 60px;
    font-size: 30px;
    border: none;
    border-bottom: 1px solid whitesmoke;
}
.edit-title:focus {
    outline: 0px;
    background-color: white;
  }
  .edit-plugin-container {
    position: relative;
    width: 100%;
    margin-top: 30px;
  }
  .edit-plugin-container-title {
    text-align: left;
    font-size: 16px;
    line-height: 20px;
    margin-bottom: 20px;
    color: #353535;
  }
  .edit-input {
    position: relative;
    width: 100%;
    height: 45px;
    line-height: 45px;
    border-radius: 3px;
    border: 1px solid #d9d9d9;
  }
  .article-cover.ant-upload-wrapper.ant-upload-picture-card-wrapper {
    width: 250px;
    height: 125px;
    overflow: hidden;
  }
  .article-cover.ant-upload-wrapper.ant-upload-picture-card-wrapper .ant-upload.ant-upload-select {
    width: 100%;
    height: 100%;
    margin-inline-end: 8px;
    margin-bottom: 8px;
    text-align: center;
    vertical-align: top;
    background-color: rgba(0, 0, 0, 0.02);
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    transition: border-color 0.3s;
}
</style>