<template>
  <div class="form">
    <el-form :model="form" ref="ruleFormRef" status-icon :rules="rules">
      <el-form-item prop="name">
        <el-input v-model="form.name" :placeholder="L['请输入姓名']" />
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="form.email" :placeholder="L['请输入邮箱']" />
      </el-form-item>
      <el-form-item prop="quantity">
        <el-input
          v-model="form.quantity"
          min="0"
          type="number"
          :placeholder="L['请输入数量']"
        />
      </el-form-item>
      <el-form-item prop="message">
        <el-input
          v-model="form.message"
          type="textarea"
          :rows="5"
          :placeholder="L['请输入留言']"
        />
      </el-form-item>

      <el-form-item>
        <el-col :span="12">
          <el-button
            type="primary"
            class="self-btn"
            :loading="loading"
            block
            @click="submitForm(ruleFormRef)"
            >{{ L["立即发布您的需求"] }}</el-button
          >
        </el-col>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import {
  ElForm,
  ElFormItem,
  ElButton,
  ElSelect,
  ElOption,
  ElInput,
  ElCol,
  ElMessage,
} from "element-plus";
import { useFiltersStore } from "@/store/filter.js";
import { useRouter } from "vue-router";

const router = useRouter();

const filtersStore = useFiltersStore();
const L = getCurLanguage();
const loading = ref(false);
const ruleFormRef = ref(null);

// do not use same name with ref
const form = reactive({
  name: "",
  message: "",
  email: "",
  quantity: "",
});

const email = computed(() => filtersStore.getMemberInfo.memberEmail ?? "");
const name = computed(
  () =>
    filtersStore.getMemberInfo.memberNickName ||
    filtersStore.getMemberInfo.memberName
);

const checkEmailFun = (rule, value, callback) => {
  if (checkEmail(value) !== true) {
    callback(new Error(checkEmail(value)));
  }
  callback();
};

const rules = reactive({
  name: [{ required: true, message: L["请输入姓名"], trigger: "blur" }],
  quantity: [{ required: true, message: L["请输入数量"], trigger: "blur" }],
  email: [
    { required: true, message: L["请输入邮箱"], trigger: "blur" },
    { validator: checkEmailFun, trigger: "blur" },
  ],
  message: [
    {
      required: true,
      message: L["请输入留言"],
      trigger: "blur",
    },
  ],
});

// 设置表单缓存
const setFormData2Cache = () => {
  localStorage.setItem("quotations", JSON.stringify(form));
};

// 删除表单缓存
const clearFormDataFromCache = () => {
  localStorage.removeItem("quotations");
};

// 获取表单缓存
const getFormDataFromCache = () => {
  const data = localStorage.getItem("quotations") ?? "";
  try {
    return JSON.parse(data);
  } catch {
    return undefined;
  }
};

//提交按钮
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url = apiUrl + "v3/member/front/enquiry/save";
      if (!filtersStore.getLoginFlag) {
        return openLoginDialog({
          onRegister: () => {
            setFormData2Cache();
            router.push({
              path: "/register",
            });
          },
          onForgot: () => {
            setFormData2Cache();
            router.push({
              path: "/member/login/forget",
            });
          },
        });
      }
      loading.value = true;
      form.pageUrl = window.location.href;
      form.itemType = "MALL";
      post(url, form).then((res) => {
        loading.value = false;
        if (res.state == 200) {
          ElMessage.success(res.msg);
          clearFormDataFromCache();
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(() => {
  if (getFormDataFromCache() !== undefined) {
    const data = getFormDataFromCache();
    form.email = data.email;
    form.name = data.name;
    form.message = data.message;
    form.quantity = data.quantity;
  } else {
    form.email = email.value;
    form.name = name.value;
  }
});
</script>

<style lang="scss">
.self-btn {
  width: 100%;
  background: #00985e;
}

.self-btn:focus,
.self-btn:hover {
  border-color: #1ba66c;
  background-color: #1ba66c;
}
</style>
