<template>
  <div>
    <el-dialog title="推广渠道管理" v-model="dialogVisible">
      <div>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="推广渠道名称：" prop="name">
            <el-input v-model="form.name" placeholder="请输入推广渠道名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="备注信息：" prop="remark">
            <el-input v-model="form.remark" placeholder="输入备注信息" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit(formRef)">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { computed, defineProps, defineEmits, reactive, ref, watch } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { promotionSiteUpdateOrCreate } from "@/api/modules/promotion";
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {
      return {};
    }
  }
});
const form = reactive({
  id: undefined,
  name: "",
  remark: ""
});
const formRef = ref<FormInstance>();
const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(dialogVisible, newVal => {
  if (newVal) {
    if (props.rowData.id) {
      form.id = props.rowData.id;
      form.name = props.rowData.name;
      form.remark = props.rowData.remark;
    } else {
      form.id = undefined;
      form.name = "";
      form.remark = "";
    }
  } else {
    resetForm(formRef.value);
  }
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入推广渠道名称", trigger: "blur" }]
});

const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) {
      console.log("submit!");
      return;
    }
    let { message } = await promotionSiteUpdateOrCreate(form);
    ElMessage.success(message);
    dialogVisible.value = false;
    emits("success");
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
