<template>
  <!-- 新增发票对话框 -->
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :before-close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <!-- 发票信息 -->
      <el-divider content-position="left">
        <span style="color: #409eff; font-weight: 600">发票信息</span>
      </el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select v-model="form.invoiceType" placeholder="请选择发票类型" clearable style="width: 100%">
              <el-option v-for="dict in invoice_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票代码" prop="invoiceCode">
            <el-input v-model="form.invoiceCode" placeholder="请填写发票代码" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开票公司名称" prop="invoiceCompanyName">
            <el-input v-model="form.invoiceCompanyName" placeholder="请填写开票公司名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票金额" prop="invoiceAmount">
            <el-input-number v-model="form.invoiceAmount" :controls="false" clearable style="width: 100%"> </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开票日期" prop="invoiceDate">
            <el-date-picker v-model="form.invoiceDate" type="date" placeholder="请选择开票日期" style="width: 100%" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :min="2" placeholder="请填写备注" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="发票附件" prop="invoiceAttachment">
            <el-button type="primary" size="small" @click="handleOpenFileSelector">
              <el-icon><Upload /></el-icon>
              点击上传
            </el-button>
            <div style="color: #999; font-size: 12px; margin-top: 5px">支持jpg/png/xlsx等文件</div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 附件列表 -->
      <el-row :gutter="20" v-if="fileList.length > 0">
        <el-col :span="24">
          <el-table :data="fileList" border style="width: 100%; margin-top: 10px">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="name" label="附件名称" min-width="200" align="center" />
            <el-table-column label="操作" width="150" align="center">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="handlePreviewFile(scope.row)">预览</el-button>
                <el-button link type="danger" size="small" @click="handleRemoveFile(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 文件选择器 -->
  <FileSelector v-model="fileSelectorVisible" :multiple="true" :allowed-types="[1, 2, 3, 4, 5]" title="选择发票附件" @confirm="handleFileSelected" />
</template>

<script setup name="AddInvoiceDialog" lang="ts">
import { Upload } from '@element-plus/icons-vue';
import FileSelector from '@/components/FileSelector/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_type } = toRefs<any>(proxy?.useDict('invoice_type'));
interface InvoiceForm {
  invoiceType?: string;
  invoiceCode?: string;
  invoiceCompanyName?: string;
  invoiceAmount?: number;
  invoiceDate?: string;
  remark?: string;
  invoiceAttachment?: string;
}

const initFormData: InvoiceForm = {
  invoiceType: undefined,
  invoiceCode: undefined,
  invoiceCompanyName: undefined,
  invoiceAmount: undefined,
  remark: undefined,
  invoiceDate: undefined,
  invoiceAttachment: undefined
};

const formRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const form = ref<InvoiceForm>({ ...initFormData });
const fileList = ref<any[]>([]);
const fileSelectorVisible = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: '发票信息'
});

const rules = reactive({
  invoiceType: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
  invoiceCode: [{ required: true, message: '请填写发票代码', trigger: 'blur' }],
  invoiceCompanyName: [{ required: true, message: '请填写开票公司名称', trigger: 'blur' }],
  invoiceAmount: [
    { required: true, message: '请填写发票金额', trigger: 'blur' },
    {
      pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/ as RegExp,
      message: '请输入正确的金额格式，最多保留两位小数',
      trigger: 'blur'
    }
  ]
  // invoiceDate: [{ required: true, message: '请选择开票日期', trigger: 'change' }]
} as any);

/** 打开对话框 */
const open = (data?: InvoiceForm) => {
  reset();

  if (data) {
    // 编辑模式
    Object.assign(form.value, data);

    // 解析附件地址并回显附件列表
    if (data.invoiceAttachment) {
      const urls = data.invoiceAttachment.split(',').filter((url) => url.trim());
      fileList.value = urls.map((url, index) => {
        const fileName = url.split('/').pop() || `附件${index + 1}`;
        return {
          name: fileName,
          url: url.trim(),
          id: undefined
        };
      });
    }
  }

  dialog.visible = true;
};

/** 重置表单 */
const reset = () => {
  form.value = { ...initFormData };
  fileList.value = [];
  formRef.value?.clearValidate();
};

/** 打开文件选择器 */
const handleOpenFileSelector = () => {
  fileSelectorVisible.value = true;
};

/** 文件选择完成 */
const handleFileSelected = (files: any[]) => {
  if (files && files.length > 0) {
    files.forEach((file) => {
      fileList.value.push({
        name: file.fileName || file.name,
        url: file.fileUrl || file.url,
        id: file.id
      });
    });
    form.value.invoiceAttachment = fileList.value.map((f) => f.url || f.name).join(',');
  }
  fileSelectorVisible.value = false;
};

/** 删除文件 */
const handleRemoveFile = (index: number) => {
  fileList.value.splice(index, 1);
  form.value.invoiceAttachment = fileList.value.map((f) => f.url || f.name).join(',');
};

/** 预览文件 */
const handlePreviewFile = (file: any) => {
  if (!file.url) {
    proxy?.$modal.msgWarning('文件地址不存在');
    return;
  }
  window.open(file.url, '_blank');
};

/** 提交表单 */
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 返回发票数据给父组件
        emit('success', form.value);
        dialog.visible = false;
        proxy?.$modal.msgSuccess('添加成功');
      } catch (error) {
        console.error(error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 关闭对话框 */
const handleClose = () => {
  if (buttonLoading.value) {
    return;
  }
  dialog.visible = false;
  reset();
};

const emit = defineEmits(['success']);

defineExpose({
  open
});
</script>

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