<template>
  <div class="app-container">
    <el-card shadow="always" style="width: 55%; margin: 0 auto">
      <ReleaseForm
        v-model="form"
        :isAdd="false"
        :labelWidth="labelWidth"
        ref="releaseFormRef"
      />
      <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 setup name="ReleaseProduct">
import ReleaseForm from "@/views/components/ReleaseForm";
import tab from "@/plugins/tab";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import {
  getProductById,
  insertEnterpriseProduct,
  updateEnterpriseProduct,
} from "@/api/admin/enterprise/product";
import { reactive, ref, toRefs } from "vue";
import { updateCount } from "@/api/admin/count";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
// const router = useRouter();
const labelWidth = 140;
// const  = reactive({});
const data = reactive({
  form: {},
});
const { form } = toRefs(data);
const releaseFormRef = ref();
const submitForm = async (is_submit) => {
  const isValid = await releaseFormRef.value.validateForm();
  if (isValid) {
    form.value["status"] = is_submit;
    console.log(form.value.cooperationModeArr.join(","));
    form.value.cooperationMode = form.value.cooperationModeArr.join(",");
    if (route.query.id) {
      await updateEnterpriseProduct(form.value);
      ElMessage.success(t("admin.common.editSuccess"));
    } else {
      await insertEnterpriseProduct(form.value);
      ElMessage.success(t("admin.common.addSuccess"));
    }
    if (is_submit == "1") {
      updateCount("product");
    }
    // router.go(-1);
    tab.closeOpenPage({ path: "/extension/product" });
  } else {
    console.log("Validation failed");
  }
};

// 如果url参数包含id 则为修改，请求数据回显
const getProductDetail = async (id) => {
  const { data } = await getProductById({ id });
  form.value = data;
  form.value.cooperationModeArr = data.cooperationMode
    ? data.cooperationMode.split(",")
    : [];
};

if (route.query.id) {
  getProductDetail(route.query.id);
}
</script>
