<template>
  <div class="app-container">
    <div style="width: 50%">
      <ExpertForm
        v-model="form"
        :showTitle="true"
        :formType="formType"
        :labelWidth="140"
        ref="expertFormRef"
      />
    </div>
    <el-button @click="cancel">取消</el-button>
    <el-button type="primary" @click="submitForm">提交</el-button>
  </div>
</template>

<script setup name="EnterpriseAdd">
import ExpertForm from "@/views/components/ExpertForm";
import tab from "@/plugins/tab";
import { companyAdd, companyDetail, companyEdit } from "@/api/expert/expert";
import { reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();
const formType = ref(1);
const expertFormRef = ref(null);
const data = reactive({
  form: {
    image: undefined,
    name: undefined,
    tenantId: undefined,
    province: undefined, // 省code
    city: undefined, // 市code
    district: undefined, // 区code
    address: undefined, // 详细地址
    product: undefined,
    kind: undefined,
    code: undefined,
    inviterCode: undefined,
    url: undefined,
    industrys: [],
    keywords: [],
    directions: [],
    introduce: undefined,
    license: undefined,
  },
});
const { form } = toRefs(data);
const cancel = () => {
  router.back();
  tab.closeOpenPage();
};
const submitForm = async () => {
  const valid = await expertFormRef.value.validateForm();
  form.value.area = form.value.district;
  if (valid) {
    if (form.value.id != undefined) {
      await companyEdit(form.value);
      cancel();
      ElMessage.success("修改成功");
    } else {
      await companyAdd(form.value);
      cancel();
      ElMessage.success("新增成功");
    }
  } else {
    console.log("校验未通过");
  }
};

const getDetailById = async () => {
  if (route.query.id) {
    const obj = Object.assign({}, route, { title: "修改专家" });
    tab.updatePage(obj);
    const { data } = await companyDetail(route.query.id);
    form.value = data;
    form.value.keywords = data.keyword ? data.keyword.split(",") : [];
    form.value.researchs = data.research ? data.research.split(",") : [];
    console.log(form.value);
    form.value.district = data.area;
  }
};
getDetailById();
</script>
