
<template>
  <flow-form :data="formData" @submit="submitNextActivity">
    <card title="基础信息">
      <van-form required="auto" ref="form" :readonly="formRead">
        <van-cell-group inset>
          <van-field
            v-model="formData.userNickname"
            name="请假人"
            label="请假人"
            placeholder="请假人"
            readonly
            :rules="[{ required: true, message: '未获取请假人' }]"
          />
          <van-field
            v-model="formData.deptName"
            name="所在部门"
            label="所在部门"
            placeholder="所在部门"
            readonly
            :rules="[{ required: true, message: '未获取所在部门' }]"
          />
          <van-field
            v-model="formData.createTime"
            name="申请时间"
            label="申请时间"
            placeholder="申请时间"
            readonly
            :rules="[{ required: true, message: '请填写申请时间' }]"
          />
          <van-field
            v-model="formData.leaveNo"
            name="请假单号"
            label="请假单号"
            placeholder="请假单号"
            readonly
          />
          <van-field
            v-model="formData.leaveTypeText"
            is-link
            readonly
            name="休假类型"
            label="休假类型"
            placeholder="点击选择休假类型"
            :rules="[{ required: true, message: '请选择休假类型' }]"
            @click="pickerClick"
          />
          <van-popup v-model:show="showPicker" position="bottom">
            <van-picker
              v-model="leaveTypePiker"
              :columns="columns"
              @confirm="onConfirm"
              @change="onConfirm"
              @cancel="showPicker = false"
            />
          </van-popup>
          <van-field
            v-model="formData.leaveDays"
            name="休假天数"
            label="休假天数"
            placeholder="休假天数"
            readonly
            :rules="[{ required: true, message: '请填写休假天数' }]"
          />
          <van-field
            v-model="formData.leaveReason"
            name="请假原因"
            label="请假原因"
            placeholder="请假原因"
            type="textarea"
            rows="3"
            autosize
            :rules="[{ required: true, message: '请填写休假原因' }]"
          />
        </van-cell-group>
      </van-form>
    </card>
    <card title="请假时间信息">
      <template #right>
        <button class="add_btn" @click="popupShow = true" v-if="!formRead">
          新增
        </button>
      </template>
      <template #default>
        <div v-for="(item, index) in formData.leaveTimeCreateList" :key="index">
          <van-swipe-cell :disabled="formRead">
            <card-cell>
              <van-cell title="起始时间" :value="item.startTime" />
              <van-cell title="截止时间" :value="item.endTime" />
              <van-cell title="备注" :value="item.bz1" />
            </card-cell>
            <template #right>
              <van-button
                square
                type="primary"
                text="编辑"
                @click="detailView(index, item)"
              />
              <van-button
                square
                type="danger"
                text="删除"
                @click="detailDelte(index)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </template>
    </card>
  </flow-form>
  <van-popup class="detail-popup" v-model:show="popupShow" position="bottom">
    <h4 class="title">新增请假时间</h4>
    <van-cell-group inset>
      <date-time-range
        label="起始时间"
        v-model="detailData.startTime"
        placeholder="请选择起始时间"
        @change="startTimeChange"
      />
      <date-time-range
        label="截止时间"
        v-model="detailData.endTime"
        placeholder="请选择截止时间"
        @change="endTimeChange"
      />
      <van-field
        v-model="detailData.bz1"
        name="备注"
        label="备注"
        placeholder="备注"
        type="textarea"
        rows="3"
        autosize
      />
    </van-cell-group>
    <div class="fixed-btn">
      <van-button round block type="primary" @click="saveHandle">
        保存
      </van-button>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { FlowDTO, getNextActivity } from "@/service/flow";
import reqest from "@/utils/request";
import DateTimeRange from "@/components/dateTimeRange.vue";
import FlowForm from "@/components/flowForm.vue";
import Card from "@/components/card.vue";
import CardCell from "@/components/cardCell.vue";
import { showSuccessToast, showFailToast } from "vant";
import { getDictOptions, getDictLabel, DICT_TYPE } from "@/utils/dict";

const popupShow = ref<boolean>(false);
const form = ref(null);
const route = useRoute();
interface FormDataType {
  instanceId: string;
  id: string;
  leaveHours: number | null;
  userNickname: string;
  deptName: string;
  createTime: string;
  leaveNo: string;
  leaveType: number | null;
  leaveTypeText: string;
  leaveDays: string;
  leaveReason: string;
  leaveTimeCreateList: {
    leaveId: string;
    startTime: string;
    endTime: string;
    bz1: string;
  }[];
}
const formData = ref<FormDataType>({
  instanceId: "",
  id: "",
  leaveHours: null,
  userNickname: "",
  deptName: "",
  createTime: "",
  leaveNo: "",
  leaveType: null,
  leaveTypeText: "",
  leaveDays: "",
  leaveReason: "",
  leaveTimeCreateList: [],
});
const detailData = ref({
  leaveId: "",
  startTime: "",
  endTime: "",
  bz1: "",
});
const detailEdit = ref(false);
const formRead = ref(false);
const detailIndex = ref<any>(null);
const leaveTypePiker = ref(["11"]);
const showPicker = ref(false);
const columns = getDictOptions(DICT_TYPE.WF_LEAVE_TYPE, {
  label: "text",
});
const { activityInstanceId, participant, flowInstanceId, read, _o } =
  route.query as {
    activityInstanceId: string;
    participant: string;
    flowInstanceId: string;
    read: string;
    _o: string;
  };
const activityData: FlowDTO = {
  activityInstanceId,
  participantId: participant,
  flowOpinion: "",
};
const onConfirm = ({ selectedOptions }) => {
  formData.value.leaveTypeText = selectedOptions[0]?.text;
  formData.value.leaveType = selectedOptions[0]?.value;
  showPicker.value = false;
};
const submitNextActivity = async (NextActivity: () => Promise<any>) => {
  form.value.validate().then(async () => {
    formData.value.leaveTimeCreateList.forEach((x: any) => {
      x.startTime = Date.parse(x.startTime);
      x.endTime = Date.parse(x.endTime);
    });
    //更新表单业务数据
    if (!formRead.value) {
      const result = await reqest.post(
        "/business/Leave/update",
        formData.value
      );
      if (result.code === 200 || result.code === 0) {
        //工作流转件
        NextActivity();
      }
    } else {
      //工作流转件
      NextActivity();
    }
  });
};

/** 初始化表单数据 */
const initFormData = async () => {
  const result = await reqest.get(
    `/business/Leave/mobileAdd?flowInstanceId=${flowInstanceId}`
  );
  formData.value = result.data;
  formData.value.leaveTypeText = getDictLabel(
    DICT_TYPE.WF_LEAVE_TYPE,
    result.data.leaveType
  );
};

/** 细节数据保存 */
const saveHandle = async () => {
  detailData.value.leaveId = formData.value.id;
  if (detailEdit.value) {
    formData.value.leaveTimeCreateList[detailIndex.value] = detailData.value;
  } else {
    formData.value.leaveTimeCreateList.push(detailData.value);
  }
  detailData.value = {
    leaveId: "",
    startTime: "",
    endTime: "",
    bz1: "",
  };
  const prarms: Object[] = [];
  formData.value.leaveTimeCreateList.forEach((x: any) => {
    const startTime = Date.parse(x.startTime);
    const endTime = Date.parse(x.endTime);
    const obj = new Object({
      startTime: startTime,
      endTime: endTime,
    });
    prarms.push(obj);
  });
  const result = await reqest.post(`/business/Leave/getLeaveDays`, prarms);
  if (result.data) {
    const totalMin = result.data;
    const totalHours = totalMin / 60;
    const totalDays = Math.floor(totalHours / 7.5);
    const subHours = totalHours % 7.5;
    let leaveDaysText = "";
    if (totalDays > 0) {
      leaveDaysText += totalDays + "天";
    }
    if (subHours > 0) {
      leaveDaysText += subHours + "小时";
    }
    formData.value.leaveDays = leaveDaysText;
    formData.value.leaveHours = totalHours;
  }
  popupShow.value = false;
  detailEdit.value = false;
  detailIndex.value = null;
};

/** 细节编辑 */
const detailView = (index: number, item: any) => {
  popupShow.value = true;
  detailEdit.value = true;
  detailIndex.value = index;
  detailData.value = item;
};

/** 选择框事件 */
const pickerClick = () => {
  if (!formRead.value) {
    showPicker.value = true;
  }
};

/** 细节删除 */
const detailDelte = (index: number) => {
  formData.value.leaveTimeCreateList.splice(index, 1);
};
/** 起始时间变化事件 */
const startTimeChange = (value: string) => {
  if (Date.parse(value) > Date.parse(detailData.value.endTime)) {
    showFailToast("起始时间不能大于开始时间!");
    detailData.value.startTime = "";
  }
};
/** 截止时间变化事件 */
const endTimeChange = (value: string) => {
  if (Date.parse(value) < Date.parse(detailData.value.startTime)) {
    showFailToast("截止时间不能小于开始时间!");
    detailData.value.endTime = "";
  }
};
/** 初始化 */
onMounted(() => {
  initFormData();
  if (read === "1" || _o === "v") {
    formRead.value = true;
  }
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>