<!--登录弹框 @zjf-2021-01-08-->
<template>
  <div class="enquiry_modal">
    <el-dialog
      :title="L['发送询盘']"
      :model-value="modalVisible"
      :close-on-click-modal="false"
      :show-close="true"
      @close="closeModal"
    >
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-position="top"
        label-width="120px"
        :rules="rules"
        size="large"
        status-icon
      >
        <el-form-item :label="L['姓名']" prop="name">
          <el-input v-model="form.name" :placeholder="L['请输入姓名']" clearable />
        </el-form-item>
        <el-form-item v-if="contactType === 'email'" :label="L['邮箱']" prop="email">
          <el-input v-model="form.email" :placeholder="L['请输入邮箱']" />
        </el-form-item>
        <el-form-item v-if="contactType === 'mobile'" :label="L['电话']" prop="phone">
          <el-input v-model="form.phone" :placeholder="L['请输手机号']" />
        </el-form-item>
        <el-form-item :label="L['国家/地区']" prop="phoneCode">
          <el-select v-model="form.phoneCode" :placeholder="L['选择国家/地区']" filterable clearable allow-create   style="width: 100%">
            <el-option
                    v-for="item in countryPhone"
                    :key="item.value"
                    :label="item.label"
                    :value="(item.label+'/'+item.value)">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="contactType === 'mobile'" :label="L['邮箱']" prop="email">
          <el-input v-model="form.email" :placeholder="L['请输入邮箱']" />
        </el-form-item>
        <el-form-item v-if="contactType === 'email'" :label="L['电话']" prop="phone">
          <el-input v-model="form.phone" :placeholder="L['请输入电话']" />
        </el-form-item>
        <el-form-item :label="L['采购数量']" 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 :label="L['公司名称']" prop="company">
          <el-input v-model="form.company"  :placeholder="L['请输入公司名称']" />
        </el-form-item>
        <el-form-item :label="L['需求描述']" prop="message">
          <el-input
            v-model="form.message"
            type="textarea"
            :rows="8"
            :placeholder="L['请输入采购需求']"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="self-btn" @click="submitForm(ruleFormRef)" style="flex:48% 0 0;margin:10px 1% 0" :loading="loading"
            >{{ L["发送"]}}</el-button
          >
          <el-button class="cancel-btn" @click="closeModal(ruleFormRef)" style="flex:48% 0 0;margin:10px 1% 0">{{ L["取消"]}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
// import { lang_zn } from "@/assets/language/zh";
import { getCurLanguage } from '@/composables/common.js';
import {
  ElSelect,
  ElOption,
  ElMessage,
  ElForm,
  ElFormItem,
  ElButton,
  ElInput,
  ElDialog,
} from "element-plus";
import { useFiltersStore } from "@/store/filter.js";
import { getContactType } from "@/utils/common"
const filtersStore = useFiltersStore();
const countryPhone = ref([]);
const emit = defineEmits(["closeLoingModal"]);
const props = defineProps(['itemType','itemId'])
// const L = lang_zn;
const L = getCurLanguage();
const modalVisible = ref(true);
const loading = ref(false);
const ruleFormRef = ref(null);
const form = reactive({
  name: "",
  email: "",
  phoneCode: "",
  phone: "",
  quantity: undefined,
  company: "",
  message: "",
});

const { memberEmail, memberNickName, memberName, memberMobile, memberCompany} = filtersStore.getMemberInfo;
form.email = memberEmail ?? "";
form.name = memberNickName ?? memberName ?? "";
form.phone = memberMobile ?? '';
form.company = memberCompany ?? ""

const contactType = getContactType();

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


const checkPhoneFun = (rule, value, callback) => {
  if (checkPhone(value) !== true) {
    callback(new Error(checkPhone(value)))
  }
  callback()
}


const rules = reactive({
  name: [
    { required: true, message: L["请输入姓名"], trigger: "blur" },
  ],
  email: contactType === 'email' ?[
    { required: true, message: L["请输入邮箱"], trigger: "blur" },
    { validator: checkEmailFun, trigger: 'blur'}
  ] : [],
  phoneCode: [
    {
      required: true,
      message: L["请选择国家/地区"],
      trigger: ['blur','change'],
    },
  ],
  phone: contactType === 'mobile' ? [
    { required: true, message: L["请输入电话"], trigger: "blur" },
    { validator: checkPhoneFun, trigger: 'blur'}
  ] : [],
  company: [
    {
      required: true,
      message: L["请输入公司名称"],
      trigger: "blur",
    },
  ],
  message: [
    {
      required: true,
      message: L["请输入采购需求"],
      trigger: "blur",
    },
  ],
});




//关闭登录modal
const closeModal = (formEl) => {
  emit("closeLoingModal");
  if (!formEl) return;
  formEl.resetFields();
  loading.value = false;
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const url = "v3/member/front/enquiry/save";
      if (!filtersStore.getLoginFlag) {
        return openLoginDialog({
          onRegister: () => {
            router.push({
              path: "/register",
            });
          },
          onForgot: () => {
            router.push({
              path: "/member/login/forget",
            });
          },
        });
      }
      loading.value = true;
      let d = {}
      d = Object.assign({},form) 

      d.pageUrl = window.location.href
      d.itemId = props.itemId
      d.itemType = props.itemType
      let a = d.phoneCode
      d.phoneCode = a.split('/')[1] ?  a.split('/')[1] : ''
      d.country = a.split('/')[0]
      post(url,d).then((res) => {
        if(res.state == 200){
          ElMessage.success(res.msg)
          loading.value = false;
          closeModal(formEl);
        }else{
            ElMessage.error(res.msg)
        }
      }).finally(()=>{
        loading.value = false;
      })
    } else {
      console.log("error submit!", fields);
    }
  });
};

//获取国家电话code
const getPhoneCode = () => {
  get('v3/member/front/enquiry/phoneCode').then(res=>{
    countryPhone.value = res.data;
  })
}

onMounted(() => {
  getPhoneCode()
})
</script>

<style lang="scss">
@import "@/assets/style/enquiry.scss";
</style>
