<template>
  <el-drawer v-model="visible" :title="title" :size="'70%'" :before-close="handleClose" destroy-on-close :close-on-click-modal="true">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="总金额" prop="totalAmount">
        <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
      </el-form-item>
      <el-form-item label="申请日期" prop="applyDate">
        <el-date-picker clearable v-model="form.applyDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择申请日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ReconApplicationForm } from '@/api/bill/reconApplication/types';
import { addReconApplication, updateReconApplication } from '@/api/bill/reconApplication';
import { ElMessage } from 'element-plus';

interface Props {
  modelValue: boolean;
  title?: string;
  formData?: ReconApplicationForm;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'success'): void;
}

const props = withDefaults(defineProps<Props>(), {
  title: '添加对账申请'
});

const emit = defineEmits<Emits>();

const formRef = ref();
const buttonLoading = ref(false);
const visible = ref(false);

const initFormData: ReconApplicationForm = {
  id: undefined,
  reconNo: undefined,
  totalAmount: undefined,
  applyDate: undefined,
  orderIds: undefined,
  status: undefined,
  remark: undefined
};

const form = ref<ReconApplicationForm>({ ...initFormData });

const rules = {};

watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val && props.formData) {
      form.value = { ...props.formData };
    } else if (val) {
      form.value = { ...initFormData };
    }
  }
);

watch(visible, (val) => {
  emit('update:modelValue', val);
});

const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
};

const handleSubmit = async () => {
  await formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateReconApplication(form.value);
        } else {
          await addReconApplication(form.value);
        }
        ElMessage.success('操作成功');
        visible.value = false;
        emit('success');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
</script>

<style scoped lang="scss">
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
