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

<script name="ResearchAdd" setup>
import ResearchForm from "@/views/components/ResearchForm";
import tab from "@/plugins/tab";
import { reactive, ref, toRefs } from "vue";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  researchAdd,
  researchDetail,
  researchEdit,
} from "@/api/dataList/research";

const router = useRouter();
const route = useRoute();
const formType = ref(2);
const researchFormRef = ref();
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: [],
    industry: "",
    keywords: [],
    directions: [],
    introduce: undefined,
    license: undefined,
    workTime: "",
  },
});
const { form } = toRefs(data);
const cancel = () => {
  router.back();
  tab.closeOpenPage();
};

const submitForm = async () => {
  const valid = await researchFormRef.value?.validateForm();
  if (valid) {
    if (form.value.id) {
      await researchEdit(form.value);
      cancel();
      ElMessage.success("修改成功");
    } else {
      await researchAdd(form.value);
      cancel();
      ElMessage.success("新增成功");
    }
  } else {
    console.log("校验未通过");
  }
};

const getDetailById = async () => {
  if (route.query.id) {
    const { data } = await researchDetail(route.query.id);
    form.value = data;

    form.value.industrys =
      data.industry?.split(",")?.map((item) => parseInt(item)) ?? [];
    form.value.researchs = data.research?.split(",") ?? [];
  }
};
getDetailById();
if (route.query.id) {
  console.log(route.query.id);
  const obj = Object.assign({}, route, { title: "修改研究机构" });
  tab.updatePage(obj);
} else {
  const obj = Object.assign({}, route, { title: "添加研究机构" });
  tab.updatePage(obj);
}
</script>
