<template>
  <view class="leave-page">
    <JsQjEdit :data="qjData" v-if="qjData.id" />
  </view>
</template>

<script setup lang="ts">
import { findQjById } from "@/api/base/jsQjApi";
import { xxtsFindByIdApi } from "@/api/base/server";
import { useDataStore } from "@/store/modules/data";
import { useUserStore } from "@/store/modules/user";
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed, nextTick } from "vue";
import JsQjEdit from "./components/jsQjEdit.vue";

const { getJs, loginByOpenId } = useUserStore();
const { setData, getData, setXxts, getXxts } = useDataStore();

const dbFlag = ref(false);

const qjData = computed(() => getData);

onLoad(async (data: any) => {
  // 从待办过来的，需要从后端获取数据
  if (data && data.from && data.from == "db") {
    dbFlag.value = true;
    
    // 检查登录状态
    const isLoggedIn = await loginByOpenId(data.openId);
    if (!isLoggedIn) {
      console.log("用户未登录，跳过处理");
      return;
    }
    
    try {
      // 优先从后端根据url中的id去查询Xxts
      const xxtsRes = await xxtsFindByIdApi({ id: data.id });
      if (xxtsRes && xxtsRes.result) {
        const xxts = xxtsRes.result;
        
        // 检查待办状态
        if (xxts.dbZt === "B") {
          setData({ id: xxts.xxzbId }); // 使用消息推送中的主表ID
          let url = "/pages/view/hr/jsQj/detail";
          uni.navigateTo({ url });
          return;
        }
        setXxts(xxts);
        
        // 根据主表ID去查询请假信息
        const res = await findQjById({ id: xxts.xxzbId });
        nextTick(() => {
          setData(res.result);
        });
      }
    } catch (error) {
      console.error("获取待办信息失败", error);
      // 如果获取Xxts失败，回退到原来的逻辑
      const xxtsData = getXxts();
      if (xxtsData && xxtsData.dbZt === "B") {
        setXxts(xxtsData);
        let url = "/pages/view/hr/jsQj/detail";
        uni.navigateTo({ url });
        return;
      }
      const res = await findQjById({ id: data.id });
      nextTick(() => {
        setData(res.result);
      });
    }
  } else {
    dbFlag.value = false;
  }
});
</script>

<style lang="scss" scoped>
.leave-page {
  height: 100vh;
}
</style>
