<template>
  <el-dialog title="请假申请" v-model="visible" width="600px" :before-close="Cancel">
    <el-form :model="leaveDialog.form" ref="form" :rules="leaveDialog.rules" label-width="160px">
      <el-form-item label="请假开始/结束时间：" prop="date">
        <el-date-picker
          v-model="leaveDialog.form.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD"
          style="flex: 1"
          :disabled-date="disabledDate"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="请假理由：" prop="reason">
        <el-input type="textarea" :rows="5" resize="none" v-model="leaveDialog.form.reason"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span>
        <el-button @click="Cancel">取消</el-button>
        <el-button type="primary" @click="ConfirmLeave">确认请假</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Leave } from '@/api/leave/leave';
import { StateData } from '@/api/leave/leave/types';
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: true
  }
});
const emit = defineEmits(['update:modelValue', 'update']);
const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit('update:modelValue', val);
  }
});
const leaveDialog = ref<StateData>({
  form: {
    date: [],
    reason: ''
  },
  rules: {
    date: [{ required: true, message: '请选择请假时间', trigger: 'blur' }],
    reason: [{ required: true, message: '请输入请假理由', trigger: 'blur' }]
  }
});
const form = ref<ElFormInstance>(null);
const Cancel = () => {
  form.value.resetFields();
  emit('update:modelValue', false);
  emit('update');
};
const ConfirmLeave = () => {
  form.value.validate(async (valid) => {
    if (!valid) return;
    const params: any = {
      startDate: leaveDialog.value.form.date[0],
      endDate: leaveDialog.value.form.date[1],
      leaveReason: leaveDialog.value.form.reason
    };
    let res = await Leave(params);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }
    ElNotification({
      title: '提示',
      message: `请假成功！`,
      type: 'success'
    });
    Cancel();
  });
};
</script>

<style lang="scss" scoped></style>
