<template>
  <div class="app-container">
    <el-card shadow="always" style="width: 55%; margin: 0 auto">
      <ReleaseForm
        ref="releaseFormRef"
        v-model="form"
        :isAdd="false"
        :labelWidth="labelWidth"
      />
      <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button type="primary" @click="submitForm(`3`)"
          >{{ t("admin.form.saveDraft") }}
        </el-button>
        <el-button type="primary" @click="submitForm(`1`)"
          >{{ t("admin.common.submitAudit") }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>
<script name="ReleaseAchievement" setup>
import {
  expertAchievementInfo,
  insertAchievement,
  updateExpertAchievement,
} from "@/api/admin/expert/achievement";
import tab from "@/plugins/tab";
import { ElMessage } from "element-plus";
import { reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { updateCount } from "@/api/admin/count";
import ReleaseForm from "../components/ReleaseForm";
import { useI18n } from "vue-i18n";
import { updateAchievement } from "@/api/admin/laboratory/achievement";

const labelWidth = 140;

const data = reactive({
  form: { mode: 1, shelfStatus: "2" },
});
const formData = reactive({});

const { form } = toRefs(data);
const route = useRoute();
const router = useRouter();
const releaseFormRef = ref();
const { id } = route.query;
const { t } = useI18n();
if (id) {
  const obj = Object.assign({}, route, {
    title: t("admin.form.edit", {
      type: t("admin.common.achievement"),
    }),
  });
  tab.updatePage(obj);
  expertAchievementInfo({ id }).then((resp) => {
    form.value = resp.data;
    form.value.keywords =
      form.value.keyword?.split(",").filter((el) => el !== "") ?? [];
    form.value.customers =
      form.value.customer?.split(",").filter((el) => el !== "") ?? [];
  });
}

const submitForm = async (status) => {
  if (await releaseFormRef.value.validateForm()) {
    if (id) {
      await updateAchievement({ ...form.value, status });
      ElMessage.success(t("admin.common.editSuccess"));
      // router.back();
    } else {
      await insertAchievement({ ...form.value, status });
      ElMessage.success(t("admin.common.addSuccess"));
      // router.back();
    }
    updateCount("achievement");
    tab.closeOpenPage({ path: "/technology/achievement" });
  } else {
    console.log("validation failed");
  }
};
</script>
