<template>
  <BasicLayout>
    <!-- 选项卡 -->
    <BasicTabs
      class="leave-tabs"
      ref="tabsRef"
      :list="tabList"
      bar-width="60px"
      scroll-count="4"
      :current="curTabIndex"
      @change="switchTab"
    />
    <view class="pl-15 pr-15" v-show="curTabIndex === 0">
      <JsQjDkEdit
        :data="formData"
        ref="dkRef"
        v-if="formData && formData.dkfs === '1'"
      />
    </view>
    <JsQjDetail
      v-show="curTabIndex === 1"
      :qjId="qjId"
      :dbFlag="dbFlag"
      v-if="qjId && qjId.length"
      @loadQjData="loadQjData"
    />
    <template #bottom>
      <view class="white-bg-color py-5">
        <view class="divider"></view>
        <view class="flex-row items-center pb-10 pt-5">
          <u-button
            text="取消"
            class="ml-15 mr-7"
            :plain="true"
            @click="navigateBack"
          />
          <u-button
            text="提交"
            class="mr-15 mr-7"
            type="primary"
            @click="submit"
          />
        </view>
      </view>
    </template>
  </BasicLayout>
</template>

<script setup lang="ts">
import { jsQjJwcXtApi } from "@/api/base/jsQjApi";
import { xxtsFindByIdApi } from "@/api/base/server";
import { useDataStore } from "@/store/modules/data";
import { useUserStore } from "@/store/modules/user";
import { navigateBack, showToast } from "@/utils/uniapp";
import { onLoad } from "@dcloudio/uni-app";
import { ref, nextTick } from "vue";
import JsQjDetail from "./components/jsQjDetail.vue";
import JsQjDkEdit from "./components/jsQjDkEdit.vue";
const { getJs, loginByOpenId } = useUserStore();
const { setData, getData, setXxts, getXxts } = useDataStore();

const dkRef = ref<any>(null);

const formData = ref<any>({});

const dbFlag = ref(false);

const qjId = ref<string>();

const tabList = ref([
  { name: "代课协调", id: "dk-edit" },
  { name: "请假信息", id: "qj-info" },
]);

const curTabIndex = ref(1);
let initDkTabFlag = false;

const switchTab = (index: number) => {
  curTabIndex.value = index;
  if (index === 0 && !initDkTabFlag) {
    nextTick(() => {
      dkRef.value.getPkkbList();
      initDkTabFlag = true;
    });
  }
};

const loadQjData = (data: any) => {
  formData.value = data;
  switchTab(0);
};

const submit = async () => {
  const params = {
    qjId: qjId.value,
    jsId: getJs.id,
    dkList: [],
  };
  const flag = await dkRef.value.validate();
  if (!flag) {
    uni.showToast({
      title: "请选择代课教师",
      icon: "none",
    });
    return;
  }
  let dkList = dkRef.value.getDkList() || [];
  if (dkList.length) {
    params.dkList = dkList.map((item: any) => {
      const newItem = { ...item };
      newItem.jsId = item.dkJsId;
      newItem.jsName = item.dkJsName;
      newItem.pkkbId = item.id;
      newItem.dktime = item.dktime + " 00:00:00";
      newItem.id = "";
      newItem.qjId = "";
      return newItem;
    });
  }
  uni.showLoading({ title: "提交中..." });
  await jsQjJwcXtApi(params).then(() => {
    showToast({ title: "提交成功", icon: "success" });
    uni.reLaunch({
      url: "/pages/base/service/index",
    });
  });
  uni.hideLoading();
};

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 });
          let url = "/pages/view/hr/jsQj/detail";
          uni.navigateTo({ url });
          return;
        }
        setXxts(xxts);
        
        // 使用消息推送中的主表ID
        qjId.value = xxts.xxzbId;
      }
    } catch (error) {
      console.error("获取待办信息失败", error);
      // 如果获取Xxts失败，回退到原来的逻辑
      qjId.value = data.id;
      const xxtsData = getXxts();
      if (xxtsData && xxtsData.dbZt === "B") {
        setData({ id: data.id });
        let url = "/pages/view/hr/jsQj/detail";
        uni.navigateTo({ url });
        return;
      }
    }
  } else {
    qjId.value = getData.id;
    dbFlag.value = false;
  }
});
</script>

<style scoped>
.popup-content {
  width: 80vw;
  background: #fff;
  border-radius: 12px;
  padding: 24px 16px 16px 16px;
}
.popup-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
}
.popup-actions {
  margin-top: 16px;
}
</style>
