<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="500px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules">
        <el-form-item label="金额" prop="money">
          <el-input
            v-model="formData.money"
            type="number"
            clearable
            placeholder="请输入公司每天最多的金额"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>

<script lang="ts" setup name="taskSchedulingEdit">
import type { FormInstance } from "element-plus";
import Popup from "@/components/popup/index.vue";
import {
  apiTaskSchedulingAdd,
  apiTaskSchedulingEdit,
  apiTaskSchedulingEditMoney,
} from "@/api/task_scheduling";

const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");

// 弹窗标题
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑任务公司金额" : "新增任务公司金额";
});

// 表单数据
const formData = reactive({
  id: "",
  money: "",
});

const setFormData = (e) => {
  Object.keys(formData).forEach((key) => {
    if (e[key] != null && e[key] != undefined) {
      formData[key] = e[key];
    }
  });
};

// 表单验证
const formRules = reactive<any>({
  money: {
    required: true,
    message: "请输入正确金额",
    trigger: "change",
  },
});

// 提交按钮
const handleSubmit = async () => {
  await formRef.value?.validate();
  const data = { ...formData };
  await apiTaskSchedulingEditMoney(data);
  popupRef.value?.close();
  emit("success");
};

//打开弹窗
const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
};

// 关闭回调
const handleClose = () => {
  emit("close");
};

defineExpose({
  open,
  setFormData,
});
</script>
  