<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="180px">
      <el-form-item label="发票类型" prop="invoiceType">
        <el-select v-model="form.invoiceType" placeholder="请选择发票类型">
          <el-option v-for="dict in invoice_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发票抬头" prop="invoiceTitle">
        <el-input v-model="form.invoiceTitle" placeholder="请输入发票抬头" />
      </el-form-item>
      <el-form-item label="纳税人识别号" prop="taxNumber">
        <el-input v-model="form.taxNumber" placeholder="请输入纳税人识别号/统一社会信用代码" />
      </el-form-item>
      <el-form-item label="注册地址" prop="regAddress">
        <el-input v-model="form.regAddress" placeholder="请输入注册地址" />
      </el-form-item>
      <el-form-item label="注册电话" prop="regPhone">
        <el-input v-model="form.regPhone" placeholder="请输入注册电话" />
      </el-form-item>
      <el-form-item label="开户银行" prop="bankName">
        <el-input v-model="form.bankName" placeholder="请输入开户银行" />
      </el-form-item>
      <el-form-item label="银行账号" prop="bankAccount">
        <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
      </el-form-item>
      <el-form-item label="接收短信手机号" prop="receiverPhone">
        <el-input v-model="form.receiverPhone" placeholder="请输入接收短信手机号" />
      </el-form-item>
      <el-form-item label="申请开票金额 (不含税)" prop="applyAmount">
        <el-input v-model="form.applyAmount" placeholder="请输入申请开票金额 (不含税)" />
      </el-form-item>
      <el-form-item label="申请税额" prop="applyTaxAmount">
        <el-input v-model="form.applyTaxAmount" placeholder="请输入申请税额" />
      </el-form-item>
      <el-form-item label="价税合计总金额" prop="totalAmount">
        <el-input v-model="form.totalAmount" placeholder="请输入价税合计总金额" />
      </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, reactive, toRefs, getCurrentInstance, ComponentInternalInstance, watch } from 'vue';
import { InvoiceApplicationForm } from '@/api/bill/invoiceApplication/types';
import { addInvoiceApplication, updateInvoiceApplication } from '@/api/bill/invoiceApplication';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_application_status, invoice_type } = toRefs<any>(proxy?.useDict('invoice_application_status', 'invoice_type'));

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

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: InvoiceApplicationForm = {
  id: undefined,
  applicationNo: undefined,
  customerId: undefined,
  customerName: undefined,
  invoiceType: undefined,
  invoiceTitle: undefined,
  taxNumber: undefined,
  regAddress: undefined,
  regPhone: undefined,
  bankName: undefined,
  bankAccount: undefined,
  receiverEmail: undefined,
  receiverPhone: undefined,
  applyAmount: undefined,
  applyTaxAmount: undefined,
  totalAmount: undefined,
  statementIds: undefined,
  remark: undefined,
  status: undefined,
  auditUserId: undefined,
  auditTime: undefined,
  auditRemark: undefined,
  finalInvoiceId: undefined,
  invoiceCode: undefined,
  invoiceNumber: undefined,
  invoiceDate: undefined
};

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

const rules = {
  invoiceType: [{ required: true, message: '发票类型不能为空', trigger: 'change' }]
};

// 监听modelValue变化
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 updateInvoiceApplication(form.value);
        } else {
          await addInvoiceApplication(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>
