<template>
  <BasicLayout :fixed="false">
    <view class="p-15">
      <BasicForm @register="register" />
      
      <!-- 审批信息显示区域 -->
      <view class="approver-section">
        <view class="section-title">审批信息</view>
        <view class="approver-list">
          <view class="approver-item">
            <text class="label">审批人：</text>
            <text class="value">{{ approverName }}</text>
            <text class="role">（班主任）</text>
          </view>
        </view>
      </view>
    </view>
    <template #bottom>
      <view class="white-bg-color py-5">
        <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 { navigateBack } from "@/utils/uniapp";
import { useForm } from "@/components/BasicForm/hooks/useForm";
import { jzAddXsQjApi } from "@/api/base/xsQjApi";
import { useDicStore } from "@/store/modules/dic";
import { showToast } from "@/utils/uniapp";
import dayjs from "dayjs";
import { useUserStore } from "@/store/modules/user";
import { useCommonStore } from "@/store/modules/common";

const { getCurXs, getUser } = useUserStore();
const { findByPid } = useDicStore();
const commonStore = useCommonStore();

// 接收外部传入属性
const props = withDefaults(defineProps<{
  data: any
}>(), {
  data: () => ({
    id: "",
    qjlx: "事假",
    qjkssj: "2025-07-07 09:00:00",
    qjjssj: "2025-07-08 10:00:00",
    qjsc: "25小时",
    qjsy: "我有事情",
    sflx: 1
  })
});

let formData = ref<any>({});
let approverName = ref<string>(''); // 审批人姓名（班主任）

const [register, { getValue, setValue }] = useForm({
  schema: [
    {
      field: "qjlx",
      label: "请假类型",
      required: true,
      component: "BasicPicker",
      componentProps: {
        api: findByPid,
        param: { pid: 1007011432 },
        rangeKey: "dictionaryValue",
        savaKey: "dictionaryCode",
      },
    },
    { interval: true },
    {
      field: "qjkstime",
      label: "开始时间",
      component: "BasicDateTimes",
      required: true,
      componentProps: {
        type: 'datetime',
        change: (e: string) => changeKsTime(e)
      },
    },
    {
      field: "qjjstime",
      label: "结束时间",
      component: "BasicDateTimes",
      required: true,
      componentProps: {
        type: 'datetime',
        change: (e: string) => changeJsTime(e)
      },
    },
    {
      field: "qjsc",
      label: "请假时长",
      component: "BasicInput",
      componentProps: { 
        disabled: true,
        placeholder: "请输入选择开始时间和结束时间"
      },
    },
    { interval: true },
    {
      field: "qjsy",
      label: "请假事由",
      component: "BasicInput",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        type: "textarea",
      },
    },
    {
      field: "sflx",
      label: "是否离校",
      component: "BasicCheckbox",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        data: [
          { value: 0, text: "否" },
          { value: 1, text: "是" },
        ],
      },
    },
    // {
    //   field: "qjtp",
    //   label: "请假图片",
    //   component: "BasicUpload",
    //   required: true,
    //   itemProps: {
    //     labelPosition: "top",
    //   },
    //   componentProps: {},
    // },
  ],
});

setValue(props.data)

// 获取默认审批人信息
onMounted(async () => {
  await getDefaultApprover();
});

const getDefaultApprover = async () => {
  try {
    // 根据学生ID获取班级信息，再获取班主任信息
    if (getCurXs && getCurXs.bzrId) {
      approverName.value = getCurXs.bzrXm;
    }
  } catch (error) {
    console.error('获取审批人信息失败:', error);
    approverName.value = '获取失败';
  }
};

const changeKsTime = (selectedTime?: string) => { 
  if (!selectedTime) {
    return;
  }
  formData.value.qjkstime = selectedTime;
  validateTime();
};

const changeJsTime = (selectedTime?: string) => { 
  if (!selectedTime) {
    return;
  }
  formData.value.qjjstime = selectedTime;
  validateTime();
};

const validateTime = () => {
  const data = formData.value;
  if (!data.qjkstime || !data.qjjstime) {
    return false;
  }
  // 使用dayjs库进行时间比较
  const ksTime = dayjs(data.qjkstime).valueOf();
  const jsTime = dayjs(data.qjjstime).valueOf();
  if (ksTime > jsTime) {
    uni.showToast({
      title: "请假开始时间不能大于请假结束时间!",
      icon: "none",
    });
    return false;
  }
  // 计算请假时长（小时）
  data.qjsc = Math.round((jsTime - ksTime) / (1000 * 60 * 60)) + "小时";
  setValue({ qjsc: data.qjsc  });
  return true;
}

const submit = async () => {
  const fd = await getValue();
  if (!validateTime()) {
    return;
  }
  const params = { ...fd };
  if (props.data && props.data.id) {
    params.id = props.data.id;
  } else {
    params.id = null;
    params.xsId = getCurXs.id; // 学生ID
    params.xsxm = getCurXs.xm; // 学生姓名
    params.jsId = getCurXs.bzrId; // 班主任ID
    params.jsxm = approverName.value; // 教师姓名（班主任姓名）
    params.xqId = getCurXs.xqId; // 学期ID
    params.jzId = getUser.jzId; // 家长ID
    params.jzxm = getUser.jzxm || getUser.xm; // 家长姓名
  }
  params.flag = 2;
  
  // 添加日志输出，方便调试
  console.log('当前学生信息:', getCurXs);
  console.log('提交参数:', params);
  
  uni.showLoading({ title: "提交中..." });
  await jzAddXsQjApi(params).then(() => {
    showToast({ title: "提交成功", icon: "success" });
    uni.reLaunch({ 
      url: "/pages/base/home/index"
    });
  });
  uni.hideLoading();
};

</script>

<style lang="scss" scoped>
.approver-section {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  
  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #007bff;
  }
  
  .approver-list {
    .approver-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      
      .label {
        width: 80px;
        color: #666;
        font-weight: 500;
      }
      
      .value {
        color: #333;
        font-weight: 600;
        margin-right: 8px;
      }
      
      .role {
        color: #007bff;
        font-size: 12px;
        background: rgba(0, 123, 255, 0.1);
        padding: 2px 6px;
        border-radius: 4px;
      }
    }
  }
}
</style>
