<template>
  <BasicLayout :fixed="false">
    <view class="p-15">
      <BasicForm @register="register">
        <template #dkmx>
          <view class="back-f8f8f8">
            <view class="flex-row items-center justify-between py-15 global-bg-color">
              <view>
                <BasicTitle line title="代课明细" :isBorder="false" />
              </view>
              <view @click="addDk">
                <BasicIcon type="icon-tianjia" size="25" />
              </view>
            </view>
            <view v-if="dkList.xl.length > 0">
              <template v-for="(item, index) in dkList.xl" :key="index">
                <view class="po-re mb-15">
                  <BasicForm v-model="item.value" :schema="schema" :formsProps="{ labelWidth: 100 }" />
                  <view @click="delDk(index, item.value)" class="delete-icon">
                    <BasicIcon type="clear" size="30" />
                  </view>
                </view>
              </template>
            </view>
            <view v-else class="p-15 flex-row-center color-9 font-13 white-bg-color">暂无数据</view>
          </view>
        </template>
      </BasicForm>
    </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 { addQjApi } from "@/api/base/qjApi";
import { showToast } from "@/utils/uniapp";
import dayjs from "dayjs";
import { cloneDeep } from "lodash";
import { useUserStore } from "@/store/modules/user";
import { useDicStore } from "@/store/modules/dic";
const { getJs, getUser } = useUserStore();
const { findByPid } = useDicStore();

// 接收外部传入属性
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: "我有事情",
    dkfs: "1",
  })
});

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

const [register, { setValue, getValue }] = 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: "qjtp",
    //   label: "请假图片",
    //   component: "BasicUpload",
    //   required: true,
    //   itemProps: {
    //     labelPosition: "top",
    //   },
    //   componentProps: {},
    // },
    { interval: true },
    {
      field: "dkfs",
      label: "代课方式",
      component: "BasicCheckbox",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        data: [
          { value: 0, text: "自行协调" },
          { value: 1, text: "教科处协调" },
          { value: 2, text: "无须代课" },
        ],
      },
    },
    { colSlot: "dkmx" },
  ],
});

const schema = reactive<FormsSchema[]>([
  {
    field: "dktime",
    label: "日期",
    component: "BasicDateTimes",
    required: true,
    componentProps: {},
  },
  {
    field: "nl",
    label: "年级班级",
    component: "BasicInput",
    required: true,
    componentProps: {},
  },
  {
    field: "yhzgx",
    label: "节次",
    component: "BasicInput",
    required: true,
    componentProps: {},
  },
  {
    field: "yhzgx",
    label: "代课老师",
    component: "BasicInput",
    required: true,
    componentProps: {},
  },
]);

const dkList = reactive<any>({
  xl: [{ value: {} }],
});

function addDk() {
  dkList.xl.push({ value: {} });
}

function delDk(index: number, item: any) {
  const list = cloneDeep(dkList.xl);
  list.splice(index, 1);
  dkList.xl = list;
}

setValue(props.data)

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.jsId = getJs.bzrId; // 班主任ID
    params.xqId = getJs.xqId; // 学期ID
  }
  params.flag = 2;
  uni.showLoading({ title: "提交中..." });
  await addQjApi(params).then(() => {
    showToast({ title: "提交成功", icon: "success" });
    uni.reLaunch({
      url: "/pages/base/home/index"
    });
  });
  uni.hideLoading();
};

</script>
