<template>
  <div class="app-container">
    <el-card shadow="always" style="width: 55%; margin: 0 auto">
      <p><b>企业资料</b></p>
      <EnterpriseForm
        ref="enterpriseFormRef"
        v-model="enterpriseInfoForm"
        :isAdd="false"
        :labelWidth="labelWidth"
      />
      <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button type="primary" @click="submitEnterpriseForm">提交</el-button>
      </div>
    </el-card>
  </div>
</template>
<script name="BasicInfo" setup>
import { getInfo } from "@/api/login";
import { updateEnterprise } from "@/api/admin/enterprise";
import EnterpriseForm from "@/views/components/EnterpriseForm";
import { ElMessage } from "element-plus";
import { reactive, ref, toRefs } from "vue";

const data = reactive({
  PersonalInfoForm: {}, // 个人基本资料
  enterpriseInfoForm: {},
  rules: {
    name: [{ required: true, message: "公司名称不能为空", trigger: "blur" }],
    dutyParagraph: [
      { required: true, message: "公司税号不能为空", trigger: "blur" },
    ],
    bank: [{ required: true, message: "开户行不能为空", trigger: "blur" }],
    bankAccount: [
      { required: true, message: "开户行账号不能为空", trigger: "blur" },
    ],
    bankPhone: [
      { required: true, message: "开户行电话不能为空", trigger: "blur" },
    ],
    email: [{ required: true, message: "电子邮箱不能为空", trigger: "blur" }],
    phone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
    address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
    username: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
    userPhone: [
      { required: true, message: "联系人电话不能为空", trigger: "blur" },
    ],
    userAddress: [
      { required: true, message: "邮寄地址不能为空", trigger: "blur" },
    ],
  },
});

const { PersonalInfoForm, rules, enterpriseInfoForm } = toRefs(data);

const labelWidth = 140;

// 获取基础信息用于回显
const getBasicInfo = async () => {
  const { data } = await getInfo();
  PersonalInfoForm.value = data.user ?? {};
  enterpriseInfoForm.value = data.enterprise ?? {};
};

const enterpriseFormRef = ref(null);

const submitEnterpriseForm = async (status) => {
  const enterpriseFormValid = await enterpriseFormRef.value.validateForm();
  if (enterpriseFormValid) {
    await updateEnterprise(enterpriseInfoForm.value);
    ElMessage.success("更新企业信息成功");
    const { data } = await getInfo();
    enterpriseInfoForm.value = data.enterprise ?? {};
  } else {
    console.log("校验未通过");
  }
};

getBasicInfo();
</script>
