<template>
  <el-dialog 
    :title="$t('doImportCreateFee.customCreateFee')" 
    :visible.sync="visible" 
    width="50%"
  >
    <el-form label-width="150px">
      <el-form-item :label="$t('doImportCreateFee.selectFile')">
        <el-upload
          class="upload-demo"
          :before-upload="beforeUpload"
          :show-file-list="false"
        >
          <el-button size="small" type="primary">
            <i class="el-icon-upload"></i>
            {{ $t('common.selectFile') }}
          </el-button>
          <div slot="tip" class="el-upload__tip" style="margin-top:10px">
            {{ fileName || $t('doImportCreateFee.requiredFile') }}
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('doImportCreateFee.cancel') }}</el-button>
      <el-button type="primary" @click="handleImport" :disabled="!file">
        {{ $t('doImportCreateFee.import') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { importCustomFee } from '@/api/fee/carCreateFeeApi'

export default {
  name: 'DoImportCreateFee',
  data() {
    return {
      visible: false,
      file: null,
      fileName: ''
    }
  },
  methods: {
    open() {
      this.visible = true
      this.file = null
      this.fileName = ''
    },
    beforeUpload(file) {
      const validTypes = ['xlsx', 'xls']
      const fileType = file.name.split('.').pop().toLowerCase()
      const isExcel = validTypes.includes(fileType)
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isExcel) {
        this.$message.error(this.$t('common.invalidExcelType'))
        return false
      }
      if (!isLt2M) {
        this.$message.error(this.$t('common.fileSizeExceed'))
        return false
      }
      
      this.file = file
      this.fileName = file.name
      return false // 阻止自动上传
    },
    async handleImport() {
      if (!this.file) {
        this.$message.warning(this.$t('doImportCreateFee.requiredFile'))
        return
      }
      
      try {
        const res = await importCustomFee({
          file: this.file
        })
        
        if (res.code === 0) {
          this.$message.success(this.$t('common.importSuccess'))
          this.visible = false
          this.$emit('success')
        } else {
          this.$message.error(res.msg || this.$t('common.importError'))
        }
      } catch (error) {
        this.$message.error(this.$t('common.importError'))
      }
    }
  }
}
</script>