<template>
  <div class="self_background">
        <StoreHeaderCat />

    <div class="bottom_line"></div>

    <div class="wrap clearfix">
      <div class="s1">
        <div class="sr-layout-block fl">
          <div class="sr-txt-title">
            <h2 class="sr-txt-h2">{{ L["联系我们"] }}</h2>
          </div>

            <div class="item">
              <img src="/contactUsPng3.png" />
              <p class="t1">{{ L["邮箱"] }}</p>
              <p>{{email}}</p>
            </div>

            <div class="item">
              <img src="/contactUsPng2.png"  />
              <p class="t1">{{ L["联系方式"] }}</p>
              <p>{{phone}}</p>
            </div>

            <div class="item">
              <img src="/contactUsPng1.png" />
              <p class="t1">{{ L["公司地址"] }}</p>
              <p>{{address}}</p>
            </div>

        </div>
        <div class="sr-layout-block fr" v-loading="!ifMapReload">
          <div class="sr-txt-title">
            <h2 class="sr-txt-h2">{{ L["发布采购需求"] }}</h2>
          </div>
          <el-form
            ref="ruleFormRef"
            :model="form"
            label-position="top"
            label-width="120px"
            :rules="rules"
            size="large"
            status-icon
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label= "L['姓名']" prop="name">
                  <el-input
                    v-model="form.name"
                    :placeholder="L['请输入姓名']"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <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-col>
              <el-col :span="12">
                <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-col>
              <el-col :span="12">
                <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-col>
              <el-col :span="24">
                <el-form-item :label="L['公司名称']" prop="company">
                  <el-input
                    v-model="form.company"
                    :placeholder="L['请输入公司名称']"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="L['需求描述']" prop="message">
                  <el-input
                    v-model="form.message"
                    type="textarea"
                    :rows="8"
                    :placeholder="L['请输入采购需求']"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitForm(ruleFormRef)"
                    style="flex: 48% 0 0; margin: 10px 1% 0"
                    class="self-btn"
                    :loading="loading"
                  >{{ L["发送"]}}</el-button
                  >
                  <el-button
                    @click="closeModal(ruleFormRef)"
                    style="flex: 48% 0 0; margin: 10px 1% 0"
                    class="cancel-btn"
                    >{{ L["重置"]}}</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div v-if="ifMapReload && center.lat && center.lng">
        <GoogleMap
          api-key="AIzaSyAvTVnnDLfxdaK2i-f0pRMJOrdwZvxUBjU"
          style="width: 100%; height: 500px"
          :center="center"
          :zoom="5"
          >
            <Marker :options="{ position: center }" />
          </GoogleMap>

      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ElSelect,
  ElOption,
  ElMessage,
  ElForm,
  ElFormItem,
  ElButton,
  ElInput,
  ElRow,
  ElCol,
} from "element-plus";
import { useFiltersStore } from "@/store/filter.js";
import { GoogleMap, Marker } from 'vue3-google-map'
import { getCurLanguage } from '@/composables/common.js';
import { getContactType } from "@/utils/common";

const L = getCurLanguage();
const center = reactive({lat: '', lng: '' })
const address = ref()
const email = ref()
const phone = ref()
const route = useRoute();
const router = useRouter();

const vid = calcUrlShopId(route.path);
const ruleFormRef = ref(null);
const ifMapReload = ref(false)
const loading = ref(false);
const form = reactive({
  name: "",
  email: "",
  phoneCode: "",
  phone: "",
  company: "",
  message: "",
});
const filtersStore = useFiltersStore();
const countryPhone = ref([]);
const contactType = getContactType();

useHead({
    title: 'Store Contact Us',
    meta: [
      {
        name: "description",
        content:'Store Contact Us',
      },
      {
        name: "keywords",
        content: 'Store Contact Us',
      },
    ],
  });

if(filtersStore.getMemberInfo.memberEmail){
  form.email = filtersStore.getMemberInfo.memberEmail
}
if(filtersStore.getMemberInfo.memberNickName || filtersStore.getMemberInfo.memberName){
  form.name = filtersStore.getMemberInfo.memberNickName || filtersStore.getMemberInfo.memberName
}

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

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

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

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

const closeModal = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  loading.value = false;
};

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


//提交按钮
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",
            });
          },
        });
      }

      let d = {}
      d = Object.assign({},form)

      d.pageUrl = window.location.href;
      d.itemId = vid ? vid : "";
      d.itemType = vid ? "SHOP" : "MALL";
      let a = d.phoneCode

      d.phoneCode = a.split('/')[1] ?  a.split('/')[1] : ''
      d.country = a.split('/')[0]

      loading.value = true;
      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);
    }
  });
};

//获取经纬度
const getMapInfo = () => {
  get('v3/seller/front/store/detail?storeId='+ vid).then(res=>{
    address.value = res.data.address
    email.value = res.data.email
    phone.value = res.data.servicePhone
    center.lat = Number(res.data.storeMapInfo)
    center.lng = Number(res.data.storeMapInfoW)
    ifMapReload.value =true
  })

}

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

getMapInfo()
  getPhoneCode()

onMounted(() => {

  setTimeout(() => {
    sldStatEvent({ behaviorType: 'spv', storeId: vid ,pageUrl: defaultUrl + router.currentRoute.value.path, referrerPageUrl: apiUrl });
    }, 3000)
})

</script>

<style lang="scss" scoped>
@import "@/assets/style/store/contac-about.scss";
@import "@/assets/style/contact.scss";
</style>
