<template>
  <a-button v-permission="['message:bulletin:create']" v-if="props.isCreate" type="primary" @click="handleClick">
    <template #icon><icon-plus /></template>
    新建
  </a-button>
  <a-button
    v-permission="['message:bulletin:update']"
    v-if="!props.isCreate"
    type="outline"
    size="small"
    :style="{ marginRight: '10px', padding: '7px' }"
    @click="handleClick"
  >
    <template #icon><icon-edit /></template>
    修改
  </a-button>

  <a-modal
    width="900px"
    height="500px"
    :visible="visible"
    @cancel="handleCancel"
  >
    <template #title>{{ modalTitle }}</template>
    <a-form ref="CreateRef" :model="formData" :style="{ width: '800px',height: '420px' }">
      <a-form-item
        field="title"
        label='标题'
        :validate-trigger="['change', 'input']"
        :rules="[
          { required: true, message: '请输入标题' },
        ]"
      >
        <a-input
          v-model="formData.title"
          placeholder='请输入公告标题'
        />
      </a-form-item>
      <a-form-item
        field="top"
        label='置顶'
        :validate-trigger="['change', 'input']"
      >
        <a-switch
          v-model="formData.top"
          :checked-value="true"
          :unchecked-value="false"
        />
      </a-form-item>
      <a-form-item
        field="remark"
        label='备注'
        :validate-trigger="['change', 'input']"
      >
        <!--        v-if="isCreate"-->
        <a-input
          v-model="formData.remark"
          placeholder='请输入备注'

        />
      </a-form-item>
      <a-form-item
        label='附件'
      >
        <!--        v-if="isCreate"-->
        <a-upload
          v-model="formData.attachments"
          show-file-list
          :file-list="fileList"
          :custom-request="customRequest"
          @before-remove="beforeRemove"
        >
        </a-upload>
      </a-form-item>
      <a-form-item field="content" label='内容' :rules="[{ required: true}]">
        <div style="border: 1px solid #ccc;min-width: 600px;">
          <Toolbar
            style="border-bottom: 1px solid #ccc;"
            :editor="editorRef"
            :default-config="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 200px;overflow-y: hidden;"
            v-model="formData.content"
            :default-config="editorConfig"
            :mode="mode"
            @on-created="handleCreated"

          />
        </div>
        <!--        <a-textarea v-model="formData.content" placeholder="请输入公告内容" style="height: 100px" />-->
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel" style="position: static">取消</a-button>
      <a-button @click="handleSubmit" style="position: static" type="primary">确定</a-button>
    </template>
  </a-modal>

</template>

<script lang="ts" setup>
import useVisible from '@/hooks/visible';
import { computed, defineEmits, ref, shallowRef,onBeforeUnmount } from 'vue';
import { BulletinRecord } from '@/api/bulletin-mgmt';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { Message } from '@arco-design/web-vue';
import { useBulletinStore } from '@/store';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { IEditorConfig } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'

const props = defineProps({
  id: {
    type: Number,
    default: -1,
  },
  isCreate: Boolean,
});
const emit = defineEmits(['refresh']);
const modalTitle = computed(() => {
  return props.isCreate ? '新增公告' : '编辑公告';
});
const { visible, setVisible } = useVisible(false);
const checkKeys = ref<number[]>([]);

const CreateRef = ref<FormInstance>();
const formData = ref<BulletinRecord>({
  id: -1,
  title: '',
  top: false,
  content: '',
  remark: '',
  createTime: '',
  createBy: '',
  updateTime: '',
  state: '',
  editUserId: 0,
  publishUserId: 0,
  publishTime: '',
  closeUserId: 0,
  closeTime: '',
  attachments: [],

});
const bulletinStore = useBulletinStore();
const editorRef = shallowRef()
const mode = 'default';
const toolbarConfig = { excludeKeys: ['uploadVideo', 'insertImage','insertVideo']}
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
}
const fileList = computed(() => {
  return formData.value.attachments?.map((item: any) => {
    return {
      name: item.fileName,
      url: item.url,
      uid: item.id,
    };
  });
});
// const fileList = [
//   {
//     uid: '-1',
//     name: 'ice.png',
//     url: '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp',
//   },
//   {
//     status: 'error',
//     uid: '-2',
//     percent: 0,
//     response: '上传错误提示',
//     name: 'cat.png',
//     url: '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/e278888093bef8910e829486fb45dd69.png~tplv-uwbnlip3yd-webp.webp',
//   },
//   {
//     uid: '-3',
//     name: 'light.png',
//     url: '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp',
//   },
// ];


// 组件被点击
const handleClick = () => {
  setVisible(true);
  if(!props.isCreate){
    bulletinStore.queryBulletinDetail(props.id).then((res: any) => {
      formData.value = res.data;
    })
  }
};

const editorConfig: Partial<IEditorConfig> = { placeholder: '请输入内容...',MENU_CONF:{
  // 隐藏菜单
  hide: ['code', 'table', 'emoticon', 'uploadImage', 'video', 'todo', 'specialChar'],
    // 配置上传图片
    uploadImage: {
      base64LimitSize: 1024 * 1024,
      // server: '/api/rest/bulletin/1/add',
    }
  },
}
// 提交
const handleSubmit = async () => {
  const valid = await CreateRef.value?.validate();
  if (!valid) {
    // 新增
    if (props.isCreate) {
      // formData.value.username = formData.value.email;
      const res = await bulletinStore.createBulletin(formData.value);
      if (res.status === 200) {
        Message.success({
          content: '新建成功',
          duration: 5 * 1000,
        });
        emit('refresh');
        setVisible(false);
      }
      CreateRef.value?.resetFields();
    } else {
      // 编辑
        const res = await bulletinStore.updateBulletin(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '修改成功',
            duration: 5 * 1000,
          });
          emit('refresh');
          setVisible(false);
        }
      }
    }
};

// 自定义文件上传
const customRequest = async (option: any) => {
  const { fileItem,onSuccess,onError } = option
  const formDataFile = new FormData();
  formDataFile.append('file', fileItem.file);
  formDataFile.append('type', '其他');
  const res = await bulletinStore.addAttachments(formDataFile);
  if (res.status === 200) {
    onSuccess(res.data);
    formData.value.attachments?.push(res.data);
  } else {
    onError(res.data);
  }
}

// 删除附件
const beforeRemove = async (file: any) => {
  const res = await bulletinStore.deleteAttachment(file.response.id);
  return res.status === 200;
}

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

// 关闭
const handleCancel = async () => {
  checkKeys.value = [];
  setVisible(false);
}
</script>

