<template>
  <el-dialog title="批量添加" :visible.sync="dialogVisible" width="600px" @close="close">
    <el-form ref="form" label-width="80px">
      <el-form-item label="图片上传">
        <el-upload
          ref="upload"
          accept="image/*"
          :action="uploadUrl"
          drag
          :file-list="fileList"
          :headers="uploadHeaders"
          :multiple="true"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
        </el-upload>
        <el-dialog append-to-body :visible.sync="previewVisible">
          <img alt="" :src="previewImageUrl" width="100%" />
        </el-dialog>
      </el-form-item>
      <el-form-item v-if="hasType" label="类型">
        <el-select
          v-if="typeList && typeList.length > 0"
          v-model="type"
          allow-create
          default-first-option
          filterable
          placeholder="请选择类型"
          style="width: 100%"
        >
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-input v-else v-model.trim="type" placeholder="请输入类型" />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch v-model="isEnabled" active-text="启用" :active-value="true" inactive-text="禁用" :inactive-value="false" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getAccessToken } from '@/utils/accessToken'

  export default {
    name: 'BatchImageAdd',
    props: {
      doAdd: {
        type: Function,
        required: true,
      },
      hasType: {
        type: Boolean,
        default: false,
      },
      typeList: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        dialogVisible: false,
        isEnabled: true,
        type: '',
        loading: false,
        fileList: [],
        previewVisible: false,
        previewImageUrl: '',
      }
    },
    computed: {
      uploadUrl() {
        return `${process.env.VUE_APP_API_BASE_URL}/management/api/common/upload`
      },
      uploadHeaders() {
        return {
          Authorization: getAccessToken() || '',
          'x-user-id': this.$store.state.user.userId || '',
          'x-app-id': this.$store.state.user.appId || '',
        }
      },
    },
    methods: {
      show() {
        this.dialogVisible = true
        this.fileList = []
      },
      close() {
        this.isEnabled = true
        this.type = ''
        this.loading = false
        this.fileList = []
        this.dialogVisible = false
      },
      handleSuccess(response, file, fileList) {
        if (response.code !== 200) {
          this.$baseMessage(response.msg || '上传失败', 'error')
        }
        this.fileList = fileList
      },
      handleRemove(file, fileList) {
        this.fileList = fileList
      },
      handlePreview(file) {
        this.previewImageUrl = file.url || file.thumbUrl
        this.previewVisible = true
      },
      async save() {
        const urls = this.fileList
          .filter((f) => f.status === 'success' && f.response && f.response.code === 200)
          .map((f) => `https://file.lihailezzc.com/${f.response.data.key}`)

        if (urls.length === 0) {
          this.$baseMessage('请至少上传一张图片', 'warning')
          return
        }

        this.loading = true
        try {
          let successCount = 0
          for (const url of urls) {
            const data = { imageUrl: url, isEnabled: this.isEnabled }
            if (this.hasType) {
              data.type = this.type
            }
            await this.doAdd(data)
            successCount++
          }
          this.$emit('fetch-data')
          this.close()
        } catch (error) {
          console.error('批量添加失败:', error)
          this.$baseMessage('部分或全部添加失败', 'error')
        } finally {
          this.loading = false
        }
      },
    },
  }
</script>
