<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form
        class="ls-form flex"
        ref="formRef"
        :model="formData"
        label-placement="left"
        label-width="85px"
      >
        <div style="width: 880px; flex: none" :style="{ height: fwbHeight + 'px' }">
          <n-form-item label-width="0px" path="content">
            <Editor ref="editorRef" :height="fwbHeight" name="ad" />
          </n-form-item>
        </div>
        <div style="flex: 1; margin-left: 10px">
          <n-form-item
            label="广告标题"
            path="title"
            :rule="{ required: true, message: '请输入广告标题', trigger: 'blur' }"
          >
            <n-input placeholder="请输入广告标题" :maxlength="50" v-model:value="formData.title" />
          </n-form-item>
          <n-form-item
            label="广告位"
            path="adSortId"
            class="flex-1"
            :rule="{ type: 'number', required: true, message: '请选择广告位', trigger: 'change' }"
          >
            <n-select
              v-model:value="formData.adSortId"
              class="flex-1"
              clearable
              placeholder="请选择广告位"
              :options="adSortList"
              label-field="name"
              value-field="id"
            />
          </n-form-item>
          <n-form-item
            label="广告格式"
            path="type"
            :rule="{ type: 'number', required: true, message: '请选择广告格式', trigger: 'change' }"
          >
            <n-select
              v-model:value="formData.type"
              placeholder="请选择广告格式"
              :options="typeList"
            />
          </n-form-item>
          <n-form-item
            label="广告封面"
            path="cover"
            :rule="{ 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>
          </n-form-item>
          <n-form-item
            label="广告链接"
            path="url"
            :rule="{ required: true, message: '请输入广告链接', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.url" type="textarea" placeholder="请输入广告链接" />
          </n-form-item>
          <n-form-item
            label="广告宽度"
            path="width"
            :rule="{ required: true, message: '请输入广告宽度', trigger: 'change' }"
          >
            <number-input v-model="formData.width" placeholder="请输入广告宽度" clearable />
          </n-form-item>
          <n-form-item
            label="广告高度"
            path="height"
            :rule="{ required: true, message: '请输入广告高度', trigger: 'blur' }"
          >
            <number-input v-model="formData.height" placeholder="请输入广告高度" clearable />
          </n-form-item>
          <n-form-item
            label="广告时间"
            path="adTime"
            class="flex-1"
            :rule="{ type: 'array', required: true, message: '请选择广告时间', trigger: 'change' }"
          >
            <n-date-picker
              v-model:formatted-value="formData.adTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
              :placeholder="['开始时间', '结束时间']"
            />
          </n-form-item>
          <n-form-item
            label="点击率"
            path="click"
            :rule="{ required: true, message: '请输入点击率', trigger: 'blur' }"
          >
            <number-input v-model="formData.click" placeholder="请输入点击率" clearable />
          </n-form-item>
          <n-form-item
            label="广告描述"
            path="note"
            :rule="{ required: true, message: '请输入备注', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.note" type="textarea" placeholder="请输入广告描述" />
          </n-form-item>
          <n-form-item label="排序" path="sort">
            <n-input-number v-model:value="formData.sort" :max="9999" placeholder="请输入排序" />
          </n-form-item>
          <n-form-item label="状态">
            <n-radio-group v-model:value="formData.status" path="status">
              <n-radio :value="1">在用</n-radio>
              <n-radio :value="2">停用</n-radio>
            </n-radio-group>
          </n-form-item>
        </div>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { adAdd, adUpdate, getAdDetail } from '@/api/content/ad';
  import { getAdSortAllList } from '@/api/content/adSort';
  import { onMounted, reactive, ref, defineAsyncComponent } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useModal } from '@/components/Modal';
  import Editor from '@/components/Editor/tinymce.vue';
  import UploadImg from '@/components/Upload/Image.vue';
  import { useLockFn } from '@/utils/useLockFn';

  /**
   * 定义变量
   */
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();
  const message = useMessage();
  const adSortList = ref([]);
  const editorRef = ref();

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

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

  /**
   * 定义常量数据
   */
  const typeList = [
    { label: '图片', value: 1 },
    { label: '文字', value: 2 },
    { label: '视频', value: 3 },
    { label: '推荐', value: 4 },
  ];

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.adId ? '编辑广告' : '添加广告',
    subBtuText: '确定',
    width: 1350,
  });

  /**
   * 执行提交
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        formData.startTime = formData.adTime.length > 0 ? formData.adTime[0] : '';
        formData.endTime = formData.adTime.length > 0 ? formData.adTime[1] : '';
        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('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };
  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

  /**
   * 关闭窗体
   */
  const handleClose = () => {
    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) {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
    formData.width = formData.width + '';
    formData.height = formData.height + '';
    formData.click = formData.click + '';
    formData.adTime = [formData.startTime, formData.endTime];
    editorRef.value.myValue = formData.content;
  };

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

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

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>
