<template>
  <div>
    <el-dialog title="推荐设置" v-model="dialogVisible">
      <div>
        <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          class="good-form"
        >
          <el-form-item label="名称" prop="configName">
            <el-input
              v-model="formData.configName"
              placeholder="请输入名称"
              show-word-limit
              :maxlength="20"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="排序值" prop="configRank">
            <el-input type="number" v-model="formData.configRank"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineProps, defineEmits, watch } from "vue";
import { request } from "@/utils";
import { ElMessage } from "element-plus";

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  id: {
    default: undefined
  }
});
const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});
const name = ref("");
const formData = ref({
  configId: undefined,
  configName: "",
  configRank: ""
});
const formRef = ref(null);
const rules = {
  configName: [
    { required: "true", message: "配置名称不能为空", trigger: ["change"] }
  ],
  configRank: [
    { required: "true", message: "排序不能为空", trigger: ["change"] }
  ]
};
watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      if (props.id) {
        request
          .get(`/mallService/mechanism/indexConfigs/${props.id}`)
          .then(resp => {
            formData.value = {
              configId: resp.data.configId,
              configName: resp.data.configName,
              configRank: resp.data.configRank
            };
          });
      }
    } else {
      formRef.value.resetFields();
    }
  }
);
const submitForm = () => {
  formRef.value.validate(valid => {
    if (!valid) return;
    if (props.id) {
      request
        .put("/mallService/mechanism/indexConfigs", {
          ...formData.value,
          configRank: Number(formData.value.configRank)
        })
        .then(resp => {
          ElMessage.success(resp.message);
          dialogVisible.value = false;
          emits("success");
        });
    } else {
      request
        .post("/mallService/mechanism/indexConfigs", {
          ...formData.value,
          configRank: Number(formData.value.configRank)
        })
        .then(resp => {
          ElMessage.success(resp.message);
          dialogVisible.value = false;
          emits("success");
        });
    }
  });
};
</script>
