<template>
  <el-drawer
    v-model="props.visible"
    :title="props.layoutId ? '编辑' : '新增'"
    :size="800"
    :close-on-click-modal="false"
    :before-close="dialogClose"
  >
    <el-form class="ls-form" ref="formRef" :model="formData" label-width="120px">
      <el-form-item
        label="页面布局"
        prop="layoutId"
        class="flex-1"
        :rules="{ required: true, message: '请选择页面布局', trigger: 'change' }"
      >
        <el-select
          v-model="formData.layoutId"
          class="flex-1"
          clearable
          placeholder="请选择页面布局"
        >
          <el-option
            v-for="(item, index) in layoutList"
            :key="index"
            :label="item.description"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="页面类型"
        prop="type"
        :rules="{ required: true, message: '请选择页面类型', trigger: 'change' }"
      >
        <el-select v-model="formData.type" placeholder="请选择页面类型" @change="handleType">
          <el-option label="CMS文章" :value="1" />
          <el-option label="通知公告" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="推荐内容"
        prop="typeId"
        :rules="{ required: true, message: '请选择推荐内容', trigger: 'blur' }"
      >
        <el-input v-model="formData.typeText" placeholder="请选择推荐内容" @click="getLayoutItem" />
      </el-form-item>
      <el-form-item label="图片路径" prop="image">
        <UploadImg
          :fileType="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
          name="article"
          :fileSize="20"
          v-model:image-url="formData.image"
        >
          <template #tip>支持扩展名: jpg png jpeg;文件大小不超过20M</template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit"> 确定 </el-button>
      </span>
    </template>
    <chooseArticle
      v-if="chooseVisible"
      v-model:visible="chooseVisible"
      :type="formData.type"
      @success="selectedCallback"
    />
  </el-drawer>
</template>
<script lang="ts" setup>
  import type { FormInstance } from 'element-plus';
  import { getLayoutDetail, layoutAdd, layoutUpdate } from '@/api/content/layoutItem';
  import { getLayoutAllList } from '@/api/content/layout';
  import { onMounted, reactive, shallowRef, ref, defineAsyncComponent } from 'vue';
  import { message } from '@/utils/auth';
  import UploadImg from '@/components/Upload/Image.vue';
  import { useLockFn } from '@/utils/useLockFn';

  const emit = defineEmits(['success', 'update:visible']);
  const chooseArticle = defineAsyncComponent(() => import('./layout/index.vue'));
  const formRef = shallowRef<FormInstance>();
  const chooseVisible = ref(false);
  const layoutList = ref([]);

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    layoutId: '',
    type: '',
    typeText: '',
    typeId: '',
    image: '',
    sort: 0,
  });

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    layoutId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    await formRef.value?.validate();
    props.layoutId ? await layoutUpdate(formData) : await layoutAdd(formData);
    message('操作成功');
    emit('update:visible', false);
    emit('success');
  };

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    emit('update:visible', false);
  };

  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

  /**
   * 获取推荐内容
   */
  const getLayoutItem = () => {
    if (!formData.type) {
      message('请选择页面类型', 'warning');
      return;
    }
    chooseVisible.value = true;
  };

  /**
   * 执行设置类型
   */
  const handleType = () => {
    formData.typeId = '';
    formData.typeText = '';
  };

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getLayoutDetail(props.layoutId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
  };

  /**
   * 选择推荐内容成功回调事件
   */
  const selectedCallback = (row) => {
    formData.typeText = row.title;
    formData.typeId = row.id;
    formRef.value?.validateField('typeId');
  };

  /**
   * 获取全部字典数据
   */
  const getAllDict = async () => {
    let list = await getLayoutAllList();
    layoutList.value = list ? list : [];
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getAllDict();
    if (props.layoutId) {
      setFormData();
    }
  });
</script>
