<template>
  <BasicLayout :fixed="false">
    <view class="p-15">
      <BasicForm @register="register">
        <template #dkmx>
          <JsQjDkEdit :data="formData" ref="dkRef" v-if="formData.dkfs === 0" />
        </template>
        <template #spcs>
          <BasicSpCsMgr
            ruleId="yfzc_js_qj"
            :qjId="formData.id" 
            :defaultValue="defSpCs"
            @change="onSpCsChange"
          />
        </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 JsQjDkEdit from "./jsQjDkEdit.vue"
import BasicSpCsMgr from "@/components/BasicSpCsMgr/index.vue"
import { navigateBack } from "@/utils/uniapp";
import { useForm } from "@/components/BasicForm/hooks/useForm";
import { jsQjSqApi, jsQjCxtjApi } from "@/api/base/jsQjApi";
import { showToast } from "@/utils/uniapp";
import dayjs from "dayjs";
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: "事假",
    qjkstime: "2025-08-28 12:00:00",
    qjjstime: "2025-08-29 12:00:00",
    qjsc: "24小时",
    qjsy: "测试请假",
    dkfs: 0,
    sprList: [],
    csrList: [],
  })
});

let formData = ref<any>({
  ...props.data,
  jsId: getJs.id,
});

const defSpCs = computed(() => {
  return {
    sprList: formData.value.sprList,
    csrList: formData.value.csrList,
  }
})


const dkRef = ref<any>(null);

if (typeof props.data.dkfs === "string") {
  nextTick(() => {
    formData.value.dkfs = parseInt(props.data.dkfs);
  })
}

const [register, { setValue, getValue }] = useForm({
  schema: [
    {
      field: "qjlx",
      label: "请假类型",
      required: true,
      component: "BasicPicker",
      componentProps: {
        api: findByPid,
        param: { pid: 1007011432 },
        rangeKey: "dictionaryValue",
        savaKey: "dictionaryCode",
      },
    },
    {
      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: "请输入选择开始时间和结束时间"
      },
    },
    {
      field: "qjsy",
      label: "请假事由",
      component: "BasicInput",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        type: "textarea",
      },
    },
    { interval: true },
    {
      field: "dkfs",
      label: "代课方式",
      component: "BasicCheckbox",
      required: true,
      itemProps: {
        labelPosition: "top",
      },
      componentProps: {
        data: [
          { value: 0, text: "自行协调" },
          { value: 1, text: "教科处协调" },
          { value: 2, text: "无须代课" },
        ],
        change: (value: any) => {
          formData.value.dkfs = value;
          updateDk();
        },
      },
    },
    { colSlot: "dkmx" },
    { interval: true },
    { colSlot: "spcs" },
  ],
});

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 });
  updateDk();
  return true;
}

const updateDk = () => {
  nextTick(() => {
    if (dkRef.value) {
      dkRef.value.getPkkbList();
    }
  });
};

// 初始化
setValue(props.data)
updateDk();

const submit = async () => {
  const fd = await getValue();
  if (!validateTime()) {
    return;
  }
  const params = { ...fd };
  // 注入审批人/抄送人
  params.sprList = formData.value.sprList || [];
  params.csrList = formData.value.csrList || [];
  if (fd.dkfs === 0) {
    const dkList = dkRef.value.getDkList();
    if (!dkList.length) {
      uni.showToast({
        title: "请选择代课教师",
        icon: "none",
      });
      return;
    }
    if (dkList.length) {
      params.dkList = dkList.map((item: any) => {
        const newItem = {...item};
        newItem.jsId = item.dkJsId || item.jsId;
        newItem.jsName = item.dkJsName || item.jsName;
        newItem.pkkbId = item.id;
        newItem.dktime = item.dktime + " 00:00:00";
        newItem.id = "";
        newItem.qjId = "";
        return newItem;
      });
    } else {
      params.dkList = [];
    }
  }
  let submitApi = jsQjSqApi;
  if (props.data && props.data.id) {
    params.id = props.data.id;
    submitApi = jsQjCxtjApi
  } else {
    params.id = null;
    params.jsId = getJs.id;
    params.jsName = getJs.jsxm;
  }
  console.log("请假参数：", params);
  uni.showLoading({ title: "提交中..." });
  await submitApi(params).then(() => {
    showToast({ title: "提交成功", icon: "success" });
    uni.reLaunch({
      url: "/pages/base/service/index"
    });
  });
  uni.hideLoading();
};

// 审批/抄送选人变更回调
const onSpCsChange = (payload: any) => {
  if (payload) {
    formData.value.sprList = Array.isArray(payload.sprList) ? payload.sprList : [];
    formData.value.csrList = Array.isArray(payload.csrList) ? payload.csrList : [];
  }
};
</script>

<style lang="scss" scoped>
:deep(.global-bg-color) { background-color: #fff; }
/* 保持BasicForm区块背景统一 */
:deep(.white-bg-color) { background-color: #fff; }

</style>