<template>
  <el-form ref="contactFormRef" :model="contactForm" :rules="contactRules" label-width="120px" style="max-width: 600px">
    <el-form-item label="联系电话" prop="phone">
      <el-input v-model="contactForm.phone" placeholder="请输入联系电话" />
    </el-form-item>
    <el-form-item label="联系邮箱" prop="email">
      <el-input v-model="contactForm.email" placeholder="请输入联系邮箱" />
    </el-form-item>
    <el-form-item label="公司地址" prop="address">
      <el-input v-model="contactForm.address" placeholder="请输入公司地址" />
    </el-form-item>
    <el-form-item label="工作时间" prop="workTime">
      <el-input v-model="contactForm.workTime" placeholder="如：周一至周五 9:00-18:00" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveContactSettings">保存设置</el-button>
      <el-button @click="resetContactForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { getCompanyInfos, saveCompanyInfos } from "@/api/sitesettings";
import { useAuthStore } from "@/stores/auth";

const authStore = useAuthStore();
const contactFormRef = ref<FormInstance>();

const contactForm = reactive({
  phone: "",
  email: "",
  address: "",
  workTime: ""
});

const contactRules: FormRules = {
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }]
};

// 获取企业信息
const initCompanyInfos = async () => {
  const res = await getCompanyInfos(authStore.user.tid);
  if (res.code === 200 && res.data) {
    const data = res.data;
    contactForm.phone = data.contact_phone || "";
    contactForm.email = data.contact_email || "";
    contactForm.address = data.address || "";
    contactForm.workTime = data.worktime || "";
  }
};

const saveContactSettings = async () => {
  if (!contactFormRef.value) return;
  await contactFormRef.value.validate(async (valid) => {
    if (valid) {
      const data = {
        tid: authStore.user.tid,
        contact_phone: contactForm.phone,
        contact_email: contactForm.email,
        address: contactForm.address,
        worktime: contactForm.workTime
      };
      const res = await saveCompanyInfos(data);
      if (res.code === 200) {
        ElMessage.success("联系方式保存成功");
      } else {
        ElMessage.error(res.msg || "保存失败");
      }
    }
  });
};

const resetContactForm = () => {
  contactForm.phone = "";
  contactForm.email = "";
  contactForm.address = "";
  contactForm.workTime = "";
};

defineExpose({
  contactForm
});

// 初始化数据
onMounted(() => {
  initCompanyInfos();
});
</script>
