<template>
  <BasicLayout>
    <template #top>
      <view>
        <BasicTabs 
          class="detail-tabs"
          :list="tabList" 
          bar-width="60px" 
          scroll-count="4"
          :current="curTabIndex" 
          @change="switchTab"
        />
      </view>
    </template>
    <view class="qj-detail">
      <!-- 请假信息 -->
      <view v-show="curTabIndex === 0">
        <JsQjDetailInfo
          :qjId="qjId"
          :dbFlag="dbFlag"
          @loadQjData="handleQjDataLoaded"
        />
      </view>

      <!-- 代课信息 -->
      <view v-show="showDkTab && curTabIndex === 1">
        <JsQjDetailDk
          :qjId="qjId"
          @loadDkList="handleDkListLoaded"
        />
      </view>

      <!-- 审批流程 -->
      <view v-show="curTabIndex === 2">
        <ProgressList :qjId="qjId" />
      </view>
    </view>
    <template #bottom>
      <view class="white-bg-color py-5">
        <view class="px-15">
          <BasicForm @register="register" />
        </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 { onLoad } from "@dcloudio/uni-app";
import { useForm } from "@/components/BasicForm/hooks/useForm";
import { navigateBack } from "@/utils/uniapp";
import { jsQjSpApi } from "@/api/base/jsQjApi";
import { useUserStore } from "@/store/modules/user";
import { useDataStore } from "@/store/modules/data";
import { ref, computed } from "vue";
import { xxtsFindByIdApi } from "@/api/base/server";
import JsQjDetailInfo from "./components/jsQjDetailInfo.vue";
import JsQjDetailDk from "./components/jsQjDetailDk.vue";
import ProgressList from "./components/progressList.vue";

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

const tabList = ref<any>([{ name: "请假信息", id: "tab-qj" }]);
const curTabIndex = ref(0);

const dbFlag = ref(false);
const qjId = ref('');
const showDkTab = ref(false);

const [register, { getValue }] = useForm({
  schema: [
    {
      field: "spStatus",
      label: "审批意见",
      component: "BasicCheckbox",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        data: [
          { value: 'approved', text: "同意" },
          { value: 'rejected', text: "拒绝" },
        ],
      },
    },
    {
      field: "spYj",
      label: "审批说明",
      component: "BasicInput",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        type: "textarea",
        placeholder: "请输入审批说明",
      },
    },
  ],
});

// 构建Tab列表
const rebuildTabList = (showDk: boolean) => {
  // 构建Tab列表
  tabList.value = [
    { name: "请假信息", id: "tab-qj" },
  ];
  if (showDk) {
    tabList.value.push({ name: "代课信息", id: "tab-dk" });
  }
  tabList.value.push({ name: "审批流程", id: "tab-sp" });
};

// 切换Tab
const switchTab = (index: number) => {
  curTabIndex.value = index;
};

const handleQjDataLoaded = (data: any) => {
  setData(data);
  showDkTab.value = !!(data && data.dkfs != 2);
  rebuildTabList(showDkTab.value);
};

const handleDkListLoaded = (list: any[]) => {
  // 代课明细数据已由JsQjDetail组件处理
};

const submit = async () => {
  try {
    const formData = await getValue();
    if (!formData.spStatus || !formData.spYj) {
      uni.showToast({
        title: '请填写完整的审批信息',
        icon: 'none'
      });
      return;
    }

    const params = {
      qjId: qjId.value,
      jsId: getJs.id,
      spStatus: formData.spStatus,
      spYj: formData.spYj,
    };

    uni.showLoading({
      title: "提交中...",
    });

    const res = await jsQjSpApi(params);

    uni.hideLoading();
    uni.showToast({
      title: '审批提交成功',
      icon: 'success'
    });

    setTimeout(() => {
      navigateBack();
    }, 1500);

  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    });
    console.error('审批提交失败:', error);
  }
};

onLoad(async (data?: any) => {
  // 从待办过来的，需要从后端获取数据
  console.log(data);
  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);
        qjId.value = xxts.xxzbId;
      }
    } catch (error) {
      console.error("获取待办信息失败", error);
      // 如果获取Xxts失败，回退到原来的逻辑
      const xxtsData = getXxts;
      if (xxtsData && xxtsData.dbZt === "B") {
        setData({ id: data.id });
        let url = "/pages/view/hr/jsQj/detail";
        uni.navigateTo({ url });
        return;
      }
      qjId.value = data.id;
    }
  } else {
    dbFlag.value = false;
    // 直接加载请假详情
    qjId.value = getData.id || '';
  }
});
</script>

<style lang="scss" scoped>
.qj-detail {
  background-color: #f5f7fa;
}

.info-card {
  margin: 15px;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);

  .card-header {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;

    .applicant-name {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }

  .divider {
    height: 1px;
    background-color: #eee;
    margin-bottom: 15px;
  }

  .card-body {
    padding: 15px;
  }
}
</style>
