<template>
  <a-modal
    title="数据导入"
    :visible="open"
    :zIndex="1001"
    :confirm-loading="uploading"
    @cancel="importExcelHandleCancel"
  >
    <a-spin tip="上传中..." :spinning="uploading">
      <a-upload-dragger
        name="file"
        accept=".xlsx, .xls"
        :file-list="fileList"
        :multiple="false"
        :remove="handleRemove"
        :before-upload="beforeUpload"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          请将文件拖拽到此处上传
        </p>
        <p class="ant-upload-hint">
          支持单个上传，也可以点击后选择文件上传
        </p>
      </a-upload-dragger>
      <a-divider v-if="$slots.importExcelSlot"/>
      <a-collapse :bordered="false" v-if="$slots.importExcelSlot">
        <a-collapse-panel key="0" header="查看导入说明">
          <slot name="importExcelSlot"></slot>
        </a-collapse-panel>
      </a-collapse>
    </a-spin>
    <template slot="footer">
      <a-row>
        <a-button type="link" icon="download" v-if="queryParamsName !== 'none'" @click="importTemplate">
          下载导入模板
        </a-button>
        <a-button key="back" @click="importExcelHandleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="uploading" @click="importExcelHandleChange">
          导入
        </a-button>
      </a-row>
    </template>
  </a-modal>
</template>

<script>

import { importData, downloadImportExcel, getConfigByName } from '@vue2-client/services/api/common'
import { excleParseArrays } from '@vue2-client/utils/excel/Export2Excel'
import { mapState } from 'vuex'

export default {
  name: 'XImportExcel',
  props: {
    serviceName: {
      type: String,
      default: undefined
    },
    importType: {
      type: String,
      default: undefined
    },
    env: {
      type: String,
      default: 'prod'
    },
    queryParamsName: {
      type: String,
      default: 'none'
    },
    // 业务名称
    title: {
      type: String,
      default: ''
    },
    extraData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  components: {
  },
  data () {
    return {
      open: false,
      uploadStatus: '',
      fileList: [],
      // 是否禁用上传
      uploading: false,
      excelImportTemplate: [],
    }
  },
  filters: {
  },
  created () {
  },
  computed: {
    ...mapState('account', { currUser: 'user' })
  },
  watch: {
  },
  methods: {
    /** 导入excel窗体关闭 */
    importExcelHandleCancel (e) {
      this.open = false
      this.fileList = []
      // 关闭后刷新列表
      this.$emit('ok')
    },
    /** 下载模板操作 */
    importTemplate () {
      const isProd = process.env.NODE_ENV === 'development'
      downloadImportExcel({
        queryParamsName: this.queryParamsName
      }, this.serviceName, isProd).then(res => {
        if (!res || !res.value) {
          this.$message.warn('导入模板不存在，请检查配置')
           return
        }
        window.open(res.value)
      })
    },
    /** 导入excel窗体开启 */
    importExcelHandleOpen (e) {
      this.open = true
      console.log(this.importType)
      if (this.importType == 'former') {
        this.readTemplateConfig()
      }
    },
    /** 读取Excel导入模板配置 */
    async readTemplateConfig () {
      try {
        // const isProd = process.env.NODE_ENV === 'production'
        await getConfigByName(
          this.queryParamsName,
          'af-his',
          (config) => {
            // 更严格的空值检查
            if (config?.tableAliasName && config?.excelImportTemplate?.[0]?.column) {
              const { tableAliasName } = config
              const columns = config.excelImportTemplate[0].column
              // 生成Excel导入模板列
              this.excelImportTemplate = columns.map(item =>
                `${tableAliasName}_${item}`
              )
              console.log('Excel模板列配置加载成功', this.excelImportTemplate)
              // 可以将中文字段名称也拿出来，解析数据的时候可以和表头对比
            } else {
              console.warn('配置信息不完整，无法生成Excel模板列')
              this.excelImportTemplate = []
            }
          }
        )
      } catch (error) {
        // 更完善的错误处理
        console.error('读取Excel模板配置失败：', error.message || error.msg || error)
        // 可以根据错误类型进行不同的处理
        if (error.code === 'CONFIG_NOT_FOUND') {
          // 处理配置不存在的情况
          this.excelImportTemplate = []
        } else if (error.code === 'NETWORK_ERROR') {
          // 处理网络错误
          console.error('网络连接失败，请检查网络设置')
        }
        // 可以选择抛出错误或返回默认值
        throw new Error(`读取Excel模板配置失败: ${error.message}`)
      }
    },
    beforeUpload (file) {
      this.fileList = [file]
      return false
    },
    /** 导入excel */
    importExcelHandleChange () {
      const { fileList } = this
      const formData = new FormData()
      if (!fileList[0]) {
        this.$message.warn('请选择需要上传的文件')
        return
      }
      this.uploading = true
      if (this.importType == 'former') {
        try {
          const parsedData = excleParseArrays(fileList[0], this.excelImportTemplate)
          this.$emit('frontImport', parsedData, () => {
          this.open = false
          this.uploading = false
        })
        } catch (error) {
          this.$message.error('Excel 解析失败，请检查文件格式')
        } finally {
          this.open = false
          this.uploading = false
        }
      } else if (this.importType == 'customization') {
       //  this.$emit('customization', fileList[0]) // 自定义处理方式
      } else {
        const userData = {
          currUserName: this.currUser.name,
          currUserId: this.currUser.id,
          orgId: this.currUser.orgid,
          orgName: this.currUser.orgs,
          depId: this.currUser.depids,
          depName: this.currUser.deps
        }
        formData.append('file', fileList[0])
        formData.append('queryParamsName', this.queryParamsName)
        formData.append('userData', JSON.stringify(userData))
        formData.append('otherParams', JSON.stringify(this.extraData))
        const isProd = process.env.NODE_ENV === 'production'
        importData(formData, this.serviceName, !isProd).then(res => {
          this.fileList = []
          const msg = res.msg || '导入成功'
          if (res?.successLen && !res?.msg) {
            this.$message.success(`${msg}，成功导入${res.successLen}条数据`)
          } else {
            this.$message.success(msg)
          }
          this.open = false
          this.$emit('ok', res)
        }).catch(e => {
          this.$message.error(e)
        }).finally(() => {
          this.uploading = false
        })
      }
    },
    handleRemove () {
      this.fileList = []
      this.uploading = false
    },
    excleParse () {
      return []
    }

  }
}
</script>
