<!--
 * @since: 2024-12-30
 * ContentConfig.vue
-->
<template>
  <div class="container"></div>
  <card-layout title="内容配置" :isShowWraning="false" :mandatory="false">
    <el-form
      ref="ruleFormRef"
      label-width="auto"
      :model="ruleForm"
      :label-position="labelPosition"
      class="el-form-outer"
    >
      <el-form-item label="简介内容" prop="introduction" class="transprant">
        <el-input
          v-model="ruleForm.introduction"
          placeholder="请输入500字以内的简介内容"
          type="textarea"
          :rows="5"
          maxlength="500"
          show-word-limit
          :disabled="isDisabled"
        />
      </el-form-item>

      <el-form-item label="详情内容" prop="contentType" class="transprant">
        <el-radio-group v-model="ruleForm.contentType" :disabled="isDisabled">
          <el-radio :value="item.value" v-for="item in contentTypeOptinos" :key="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label=" "
        prop="contentUrl"
        class="transprant"
        v-if="ruleForm.contentType === ContentTypeEnum.LINK"
      >
        <el-input
          v-model="ruleForm.contentUrl"
          placeholder="请将链接地址粘贴到此处"
          :disabled="isDisabled"
        />
      </el-form-item>
      <el-form-item
        label="  "
        prop="content"
        v-if="ruleForm.contentType === ContentTypeEnum.RICHTEXT"
      >
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            @onCreated="handleCreated"
            @onChange="handleChange"
            @onDestroyed="handleDestroyed"
            @onFocus="handleFocus"
            @onBlur="handleBlur"
          />
        </div>
      </el-form-item>
      <el-form-item label="操作人" prop="operator" class="transprant">
        <el-input v-model="ruleForm.operator" :disabled="true" />
      </el-form-item>
    </el-form>
  </card-layout>
</template>

<script setup lang="ts">
  import { onBeforeUnmount, ref, shallowRef, watch } from 'vue';
  import type { FormProps } from 'element-plus';
  import '@wangeditor/editor/dist/css/style.css'; // 引入 css
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import type { IEditorConfig } from '@wangeditor/editor';
  import { RuleFormView, ContentTypeEnum } from './../type';
  import { contentTypeOptinos } from '../../constant';
  import CardLayout from './CardLayout.vue';
  import { useUserStore } from '@/store/modules/user';

  interface Props {
    dataSoure: RuleFormView;
    isDisabled: boolean;
  }
  const props = defineProps<Props>();
  const labelPosition = ref<FormProps['labelPosition']>('left');
  const userStore = useUserStore();

  /**
   * 表单相关操作
   */
  type Rule = Pick<RuleFormView, 'introduction' | 'contentType' | 'content' | 'operator' | 'contentUrl'>;
  const ruleForm = ref<Rule>({
    introduction: '',
    contentType: ContentTypeEnum.RICHTEXT,
    content: '',
    operator: '',
    contentUrl: '',
  });

  watch(
    () => props.dataSoure,
    (value) => {
      if (value) {
        const { introduction, contentType, content, operator, contentUrl } = value;
        ruleForm.value = {
          introduction,
          contentType,
          content,
          operator,
          contentUrl,
        };
        if (content) {
          valueHtml.value = content;
        }
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  /********************* 富文本区域配置与方法 **********************/
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef();
  // 内容 HTML
  const valueHtml = ref();
  // 排除工具栏选项
  const toolbarConfig = {
    excludeKeys: [
      'insertTable', // 插入表格
      'deleteTable', // 删除表格
      'insertVideo',
      'uploadVideo',
      'codeBlock', // 代码块
      'emotion', // 表情
    ],
  };
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
  };
  
  editorConfig.MENU_CONF!['uploadImage'] = {
    // 上传图片的配置
    server: '/eye_api_bak/api/systemMessage/uploadPicture', // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: 'file',
    // 单个文件的最大体积限制，默认为 2M
    maxFileSize: 5 * 1024 * 1024, // 1M
    // 最多可上传几个文件，默认为 100
    maxNumberOfFiles: 10,
    // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ['image/*'],
    // 自定义上传参数。参数会被添加到 formData 中，一起上传到服务端。
    meta: {
      bizType: 'PUSH_MESSAGE',
      fileName: ''
    },
    // 将 meta 拼接到 url 参数中，默认 false
    metaWithUrl: false,
    // 自定义增加 http  header
    headers: {
      Accept: 'application/json, text/plain, */*',
      // ContentType: 'application/json;charset=UTF-8'
      Satoken: userStore.getToken,
      Tenantid: userStore.getTenantId,
    },
    // 跨域是否传递 cookie ，默认为 false
    withCredentials: true,
    // 超时时间，默认为 10 秒
    timeout: 10 * 1000, // 5 秒
    // 上传之前触发
    onBeforeUpload(file) {
      console.log('file: ', file); 
      return file;
      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    // 上传进度的回调函数
    onProgress(progress: number) {
      // progress 是 0-100 的数字
      console.log('progress', progress);
    },
    // 单个文件上传成功之后
    onSuccess(file: File, res: any) {
      console.log(`${file.name} 上传成功`, res);
    },
    // 单个文件上传失败
    onFailed(file: File, res: any) {
      console.log(`${file.name} 上传失败`, res);
    },
    // 上传错误，或者触发 timeout 超时
    onError(file: File, err: any, res: any) {
      console.log(`${file.name} 上传出错`, err, res);
    },
  };

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

  const handleCreated = (editor) => {
    editorRef.value = editor;
  };
  const handleChange = (editor) => {
    // console.log('change:', editor.children)
  };
  const handleDestroyed = (editor) => {
    console.log('destroyed', editor);
  };
  const handleFocus = (editor) => {
    // console.log('focus', editor)
  };
  const handleBlur = (editor) => {
    console.log('blur', editor);
  };

  const buildFormdata = () => {
    return {
      ...ruleForm.value,
      content: valueHtml.value,
    };
  };

  defineExpose({ buildFormdata });
</script>

<style scoped lang="scss"></style>
