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

<script name="LaboratoryAdd" setup>
import LaboratoryForm from "@/views/components/LaboratoryForm";
import tab from "@/plugins/tab";
import {
  casLaboratoryAdd,
  casLaboratoryDetail,
  casLaboratoryUpdate,
} from "@/api/dataList/laboratory";
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 laboratoryFormRef = 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 laboratoryFormRef.value.validateForm();
  if (valid) {
    form.value.keyword = form.value.keywords.join(",");
    form.value.researchDirection = form.value.researchs?.join(",") ?? null;
    if (form.value.id != undefined) {
      await casLaboratoryUpdate(form.value);
      cancel();
      ElMessage.success("修改成功");
    } else {
      await casLaboratoryAdd(form.value);
      cancel();
      ElMessage.success("新增成功");
    }
  } else {
    console.log("校验未通过");
  }
};

const getDetailById = async () => {
  if (route.query.id) {
    const { data } = await casLaboratoryDetail(route.query.id);
    form.value = data;
    form.value.researchs = data.researchDirection?.split(",") ?? [];
    form.value.keywords = data.keyword ? data.keyword.split(",") : [];
    // form.value.district = data.area;
  }
};
getDetailById();
</script>

<!-- <script>
export default {
  components: {
    ExpertForm,
  },
  data() {
    return {
      // formType: 2,
      // labelWidth: 140,
    };
  },
  methods: {},
  created() {
    const { id } = this.$route.query;
    if (id) {
      companyDetail({ id }).then((res) => {
        form.value = res.data;
      });
    }
  },
};
</script> -->
