<template>
  <a-modal
    v-model:visible="props.visible"
    :title="dialogTitle"
    width="1350px"
    style="top: 15px"
    @cancel="dialogClose"
  >
    <a-form
      style="display: flex"
      ref="formRef"
      :model="formData"
      :label-col="{ style: { width: '80px' } }"
    >
      <div style="width: 880px; flex: none" :style="{ height: fwbHeight + 'px' }">
        <a-form-item label-width="0px" name="content">
          <Editor ref="editorRef" :height="fwbHeight" name="ad" />
        </a-form-item>
      </div>
      <div style="flex: 1; margin-left: 10px">
        <a-form-item
          label="广告标题"
          name="title"
          :rules="{ required: true, message: '请输入广告标题', trigger: 'blur' }"
        >
          <a-input placeholder="请输入广告标题" :maxlength="50" v-model:value="formData.title" />
        </a-form-item>
        <a-form-item
          label="广告位"
          name="adSortId"
          class="flex-1"
          :rules="{ required: true, message: '请选择广告位', trigger: 'change' }"
        >
          <a-select
            v-model:value="formData.adSortId"
            class="flex-1"
            allow-clear
            placeholder="请选择广告位"
          >
            <a-select-option v-for="(item, index) in adSortList" :key="index" :value="item.id">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="广告格式"
          name="type"
          :rules="{ required: true, message: '请选择广告格式', trigger: 'change' }"
        >
          <a-select v-model:value="formData.type" placeholder="请选择广告格式">
            <a-select-option :value="1">图片</a-select-option>
            <a-select-option :value="2">文字</a-select-option>
            <a-select-option :value="3">视频</a-select-option>
            <a-select-option :value="4">推荐</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="广告封面"
          name="cover"
          :rules="{ required: true, message: '请上传广告封面', trigger: 'change' }"
        >
          <UploadImg
            :fileType="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
            name="ad"
            :fileSize="200"
            v-model:image-url="formData.cover"
          >
            <template #tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
          </UploadImg>
        </a-form-item>
        <a-form-item
          label="广告链接"
          name="url"
          :rules="{ required: true, message: '请输入广告链接', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.url" type="textarea" placeholder="请输入广告链接" />
        </a-form-item>
        <a-form-item
          label="广告宽度"
          name="width"
          :rules="{ required: true, message: '请输入广告宽度', trigger: 'change' }"
        >
          <number-input v-model:value="formData.width" placeholder="请输入广告宽度" allow-clear />
        </a-form-item>
        <a-form-item
          label="广告高度"
          name="height"
          :rules="{ required: true, message: '请输入广告高度', trigger: 'blur' }"
        >
          <number-input v-model:value="formData.height" placeholder="请输入广告高度" allow-clear />
        </a-form-item>
        <a-form-item
          label="广告时间"
          name="adTime"
          class="flex-1"
          :rules="{ required: true, message: '请选择广告时间', trigger: 'change' }"
        >
          <a-range-picker
            v-model:value="formData.adTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :show-time="{ format: 'HH:mm' }"
            :placeholder="['开始时间', '结束时间']"
          />
        </a-form-item>
        <a-form-item
          label="点击率"
          name="click"
          :rules="{ required: true, message: '请输入点击率', trigger: 'blur' }"
        >
          <number-input v-model:value="formData.click" placeholder="请输入点击率" allow-clear />
        </a-form-item>
        <a-form-item
          label="广告描述"
          name="note"
          :rules="{ required: true, message: '请输入备注', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.note" type="textarea" placeholder="请输入广告描述" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="formData.sort" :max="9999" placeholder="请输入排序" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="formData.status" name="status">
            <a-radio :value="1">在用</a-radio>
            <a-radio :value="2">停用</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <span class="dialog-footer">
        <a-button @click="dialogClose">取消</a-button>
        <a-button :loading="subLoading" type="primary" @click="submit">确认</a-button>
      </span>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { adAdd, adUpdate, getAdDetail } from '@/api/content/ad';
  import { getAdSortAllList } from '@/api/content/adSort';
  import { computed, onMounted, ref, shallowRef, reactive } from 'vue';
  import type { FormInstance } from 'ant-design-vue';
  import UploadImg from '@/components/Upload/Image.vue';
  import { useLockFn } from '@/utils/useLockFn';
  import Editor from '@/components/Editor/tinymce.vue';
  import { message } from 'ant-design-vue';

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

  /**
   * 定义参数变量
   */
  const adSortList = ref([]);
  const formRef = shallowRef<FormInstance>();
  const emit = defineEmits(['success', 'update:visible']);

  /**
   * 定义弹窗标题
   */
  const dialogTitle = computed(() => {
    return props.adId ? '编辑内容' : '新增内容';
  });

  const fwbHeight = document.body.clientHeight - 180;

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    title: '',
    adSortId: undefined,
    cover: '',
    type: undefined,
    note: '',
    content: '',
    url: '',
    width: '',
    height: '',
    adTime: [],
    startTime: '',
    endTime: '',
    click: '',
    status: 1,
    sort: 0,
  });

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

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getAdDetail(props.adId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
    formData.adTime = [formData.startTime, formData.endTime];
    editorRef.value.myValue = formData.content;
  };

  /**
   * 执行提交表单
   */
  const editorRef = ref();
  const handleSubmit = async () => {
    formData.startTime = formData.adTime.length > 0 ? formData.adTime[0] : '';
    formData.endTime = formData.adTime.length > 0 ? formData.adTime[1] : '';
    await formRef.value?.validate();
    let ruleForm = JSON.parse(JSON.stringify(formData));
    ruleForm.content = editorRef.value.myValue;
    if (!ruleForm.content) {
      message.error('请添加内容');
      return;
    }
    props.adId ? await adUpdate(ruleForm) : await adAdd(ruleForm);
    message.success('操作成功');
    emit('update:visible', false);
    emit('success');
  };

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

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

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