<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 v-if="contactType === 'email'" prop="email">
        <el-input
          v-model="form.email"
          :placeholder="L['请输入邮箱']"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item v-if="contactType === 'mobile'" prop="phone">
        <el-input v-model="form.phone" :placeholder="L['请输入手机号']" />
      </el-form-item>
      <el-form-item prop="quantity">
        <el-input-number
          v-model="form.quantity"
          :min="0"
          :max="1999999999"
          :controls="false"
          :placeholder="L['请输入数量'] + ' ( 0~1999999999 ) '"
        />
      </el-form-item>
      <el-form-item prop="message">
        <el-input
          v-model="form.message"
          type="textarea"
          maxlength="1000"
          show-word-limit
          :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";
import { getContactType } from "../../utils/common";

const router = useRouter();

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

const contactType = getContactType();

// do not use same name with ref
const form = reactive({
  name: "",
  message: "",
  email: "",
  phone: "",
  quantity: undefined,
});
const email = computed(() => filtersStore.getMemberInfo.memberEmail ?? "");
const name = computed(
  () =>
    filtersStore.getMemberInfo.memberNickName ||
    filtersStore.getMemberInfo.memberName
);
const phone = computed(() => filtersStore.getMemberInfo.memberMobile ?? "");

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

const checkMobileFun = (rule, value, callback) => {
  if (checkPhone(value) !== true) {
    callback(new Error(checkPhone(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" },
  ],
  phone: [
    { required: true, message: L["请输入手机号"], trigger: "blur" },
    { validator: checkMobileFun, trigger: "blur" },
  ],
  message: [
    {
      required: true,
      message: L["请输入采购需求"],
      trigger: "blur",
    },
  ],
});

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

// 删除表单缓存
const clearFormDataFromCache = () => {
  form.quantity = undefined;
  form.message = '';
  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 = "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;
    form.phone = data.phone;
  } else {
    form.phone = phone.value;
    form.email = email.value;
    form.name = name.value;
  }
});
</script>

<style lang="scss" scoped>
.form {
  width: 531px;
  :deep(.el-input) {
    height: 48px !important;
  }

  :deep(.el-button) {
    width: 200px;
    height: 42px;
    font-weight: bold;
    font-size: 14px;
    color: #ffffff;
    margin-top: 20px;
  }

  :deep(.el-textarea) {
    height: 148px !important;
  }
  :deep(.el-input-number) {
    width: 100% !important;

    .el-input__inner {
      text-align: left;
    }
    .el-input__validateIcon {
      display: none;
    }
  }
}

.self-btn {
  width: 100%;
  background: $colorMain;
}

.self-btn:focus,
.self-btn:hover {
  border-color: $colorMain;
  background-color: $colorMain;
}
</style>
