<script setup lang="ts">
import { reactive, ref } from "vue";
import { addBanner, modifyBanner, getBannerDetail } from "@/api/banner";
import { uploadFile } from "@/api/file";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);

const formRef = ref();
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    bannerUrl: "",
    bannerDesc: "",
    linkUrl: "",
    startTime: "",
    endTime: "",
    status: 1,
    remark: ""
  },
  rules: {
    startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
    endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    bannerUrl: "",
    bannerDesc: "",
    linkUrl: "",
    startTime: "",
    endTime: "",
    status: 1,
    remark: ""
  };
  formRef.value?.resetFields();
};

const getTitle = () => {
  return dialogType.value === "add" ? "新增横幅广告" : "编辑横幅广告";
};

const open = async (type: "add" | "edit", row?: any) => {
  dialogType.value = type;
  resetForm();
  if (type === "edit" && row) {
    loading.value = true;
    try {
      const res = await getBannerDetail(row.id);
      Object.assign(state.ruleForm, res);
    } catch (e) {
      ElMessage.error("获取详情失败");
    } finally {
      loading.value = false;
    }
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleUploadSuccess = (url: string) => {
  state.ruleForm.bannerUrl = url;
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  if (new Date(state.ruleForm.startTime).getTime() > new Date(state.ruleForm.endTime).getTime()) {
    ElMessage.error("开始时间不能晚于结束时间");
    return;
  }

  loading.value = true;
  try {
    if (dialogType.value === "add") {
      await addBanner(state.ruleForm);
    } else {
      await modifyBanner(state.ruleForm);
    }
    ElMessage.success("操作成功");
    handleClose();
    emit("refresh");
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="820px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" label-width="125px" :disabled="loading">
      <el-form-item label="Banner图片" prop="bannerUrl">
        <el-input v-model="state.ruleForm.bannerUrl" placeholder="请输入图片地址" clearable />
      </el-form-item>
      <el-form-item label="描述" prop="bannerDesc">
        <el-input
          v-model="state.ruleForm.bannerDesc"
          placeholder="请输入描述"
          maxlength="200"
          show-word-limit
          type="textarea"
          :rows="2"
        />
      </el-form-item>
      <el-form-item label="关联跳转地址" prop="linkUrl">
        <el-input v-model="state.ruleForm.linkUrl" placeholder="请输入跳转地址" clearable />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="state.ruleForm.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="state.ruleForm.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="state.ruleForm.remark"
          placeholder="备注信息"
          maxlength="500"
          show-word-limit
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
