<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="850"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑文章' : '添加文章'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
    >
      <a-form-item label="发布者" name="userId">
        <SelectUser
          placeholder="请选择会员"
          v-model:value="form.nickname"
          @done="chooseUserId"
        />
      </a-form-item>
      <a-form-item label="这一刻想法" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="这一刻想法"
          v-model:value="form.content"
        />
      </a-form-item>
      <a-form-item label="上传图片" name="files" extra="建议尺寸: 300*300">
        <ele-image-upload
          v-model:value="files"
          :limit="9"
          :drag="true"
          :item-style="{ width: '80px', height: '80px' }"
          :upload-handler="uploadHandler"
          @upload="onUpload"
        />
      </a-form-item>
      <a-form-item label="上传视频" name="video" extra="视频大小不超过30M">
        <a-space direction="vertical">
          <a-upload
            :accept="'video/*'"
            :show-upload-list="false"
            :customRequest="onUploadVideo"
          >
            <a-button type="primary" class="ele-btn-icon">
              <template #icon>
                <UploadOutlined />
              </template>
              <span>上传视频</span>
            </a-button>
          </a-upload>
          <div>{{ form.video }}</div>
        </a-space>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-space direction="horizontal">
          <a-radio-group v-model:value="form.status">
            <a-radio :value="0">显示</a-radio>
            <a-radio :value="1">屏蔽</a-radio>
          </a-radio-group>
        </a-space>
      </a-form-item>
      <a-form-item label="获赞数" name="likes">
        <a-input-number
          :min="0"
          :max="99999"
          class="ele-fluid"
          placeholder="请输入获赞数"
          v-model:value="form.likes"
        />
      </a-form-item>
      <a-form-item label="排序号" name="sortNumber">
        <a-input-number
          :min="0"
          :max="99999"
          class="ele-fluid"
          placeholder="请输入排序号（数字越小越靠前）"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { Article } from '@/api/cms/article/model';
  import { addArticle, updateArticle } from '@/api/cms/article';
  import { FormInstance, Rule, RuleObject } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from '@/api/system/file';
  import useFormData from '@/utils/use-form-data';
  import { assignObject, messageLoading } from "ele-admin-pro";

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Article | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const files = ref<ItemType[]>([]);
  const formRef = ref<FormInstance | null>(null);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Article>({
    articleId: undefined,
    image: '',
    files: undefined,
    video: '',
    accept: 'image',
    content: '',
    comments: '',
    sortNumber: 100,
    status: 0,
    userId: 0,
    likes: 0,
    nickname: undefined
  });

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        files.value.push({
          uid: data.id,
          thumb: data.thumb,
          url: data.url,
          status: 'done'
        });
        if (data.contentType == 'video/mp4') {
          form.accept = 'video';
        }
        // form.image = data.thumbnail;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 上传文件
  const onUploadVideo = (item) => {
    const { file } = item;
    if (!file.type.startsWith('video')) {
      message.error('只能选择视频文件');
      return;
    }
    if (file.size / 1024 / 1024 > 30) {
      message.error('大小不能超过 30MB');
      return;
    }
    const hide = messageLoading({
      content: '上传中..',
      duration: 0,
      mask: true
    });
    uploadFile(file)
      .then((data) => {
        hide();
        form.video = data.url;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
        hide();
      });
  };

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    userId: [
      {
        required: true,
        type: 'string',
        message: '请选择会员',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: number) => {
          if (value == 0) {
            return Promise.reject('请选择会员');
          }
          return Promise.resolve();
        }
      }
    ],
    sortNumber: [
      {
        required: true,
        type: 'number',
        message: '请输入排序号',
        trigger: 'blur'
      }
    ]
  });

  const chooseUserId = (data: Article) => {
    form.userId = data.userId;
    form.nickname = data.nickname;
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const dataForm = {
          ...form,
          files: JSON.stringify(files.value)
        };
        const saveOrUpdate = isUpdate.value ? updateArticle : addArticle;
        saveOrUpdate(dataForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            resetFields();
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          isUpdate.value = true;
          assignObject(form, props.data);
          files.value = props.data.files;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .flex-sb {
    display: flex;
    justify-content: space-between;
  }
</style>
