<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :title="$t(key('import_exception_ng_data'))"
    :width="width"
    :close-on-click-modal="false"
    @close="onClose"
  >
    <div>
      <el-alert
        :title="$t(key('import_file_format_tip'))"
        :closable="false"
        type="warning"
      />

      <el-form ref="form" label-width="100px" style="margin-top:10px">
        <el-form-item :label="$t(key('import_table'))">
          <el-upload
            action=""
            :multiple="false"
            :show-file-list="true"
            :file-list="importFileList"
            accept=".xls,.xlsx"
            :http-request="onUpload"
          >
            <el-button size="mini" type="success">
              {{ $t(key('select_file')) }}
            </el-button>
            <el-button
              style="margin-left:10px"
              size="mini"
              type="primary"
              :loading="downloadLoading"
              @click="onDownloadTemplate"
            >
              {{ $t(key('download_template')) }}
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t(key('preview'))">
          <el-table
            v-loading="previewLoading"
            :data="previewList"
            height="350"
            border
            size="mini"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column :label="$t(key('device_category'))" prop="device_category_name" min-width="100" />
            <el-table-column :label="$t(key('exception_ng_category'))" prop="type" min-width="100" />
            <el-table-column :label="$t(key('ng_code'))" prop="number" min-width="100" />
            <el-table-column :label="$t(key('ng_name'))" prop="explain" min-width="120" />
            <el-table-column :label="$t(key('remark'))" prop="note" min-width="120" />
          </el-table>
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="visibleProxy = false">
        {{ $t(key('cancel')) }}
      </el-button>
      <el-button type="primary" size="mini" :loading="submitting" @click="onSubmit">
        {{ $t(key('confirm')) }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'
import { getImportTemplate, productNgInfoImport } from '@/api/production-master-data/product-ng-info'
import { downloadRename, readExcel } from '@/utils/file'

const EXPECTED_COLUMNS = ['设备类别', '异常不良类别', '异常不良编码', '异常不良名称', '备注']

export default {
  name: 'ProductNgInfoImportDialog',
  mixins: [i18nMixin('page.production_master_data.product_model.product_ng_info')],
  props: {
    visible: Boolean,
    width: { type: String, default: '50%' }
  },
  data () {
    return {
      submitting: false,
      downloadLoading: false,
      previewLoading: false,
      importFileList: [],
      previewList: []
    }
  },
  computed: {
    visibleProxy: {
      get () { return this.visible },
      set (val) { this.$emit('update:visible', val) }
    }
  },
  watch: {
    visible (val) {
      if (val) this.reset()
    }
  },
  methods: {
    reset () {
      this.importFileList = []
      this.previewList = []
      this.submitting = false
      this.previewLoading = false
    },
    onDownloadTemplate () {
      this.downloadLoading = true
      getImportTemplate({})
        .then(res => { downloadRename(res, 'xlsx', this.key('import_template_name')) })
        .finally(() => { this.downloadLoading = false })
    },
    onUpload (e) {
      const file = e.file
      if (!file) {
        this.$message.error(this.$t(this.key('file_not_exist')))
        return
      }
      const lower = file.name.toLowerCase()
      if (!/\.(xls|xlsx)$/.test(lower)) {
        this.$message.error(this.$t(this.key('upload_format_error')))
        return
      }
      this.importFileList = [file]
      this.previewLoading = true
      readExcel(file)
        .then(res => {
          if (!res || !res.length) return
          const firstRow = res[0]
          for (const col of EXPECTED_COLUMNS) {
            if (!Object.prototype.hasOwnProperty.call(firstRow, col)) {
              this.$message.error(this.$t(this.key('file_column_missing'), { title: col }))
              return
            }
          }
          this.previewList = res.map(row => ({
            device_category_name: row['设备类别'],
            type: row['异常不良类别'],
            number: row['异常不良编码'],
            explain: row['异常不良名称'],
            note: row['备注']
          }))
        })
        .catch(err => {
          this.$message.error(err.message || this.$t(this.key('upload_format_error')))
        })
        .finally(() => { this.previewLoading = false })
    },
    onSubmit () {
      if (!this.previewList.length) {
        this.$message.error(this.$t(this.key('please_import_data')))
        return
      }
      this.submitting = true
      productNgInfoImport({
        import_data: JSON.stringify(this.previewList)
      })
        .then(() => {
          this.$message.success(this.$t(this.key('operation_success')))
          this.visibleProxy = false
          this.$emit('saved')
        })
        .finally(() => { this.submitting = false })
    },
    onClose () {
      this.reset()
    }
  }
}
</script>
