<template>
  <el-dialog
    title="添加装备/工具"
    :visible.sync="visible"
    width="80%"
    @close="onClose"
  >
    <!-- 搜索条件 -->
    <el-form ref="queryForm" size="small" label-width="auto" :model="queryParams">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择分类" clearable>
              <el-option label="装备" value="装备" />
              <el-option label="工具" value="工具" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button type="primary" size="small" @click="onHandleQuery">查询</el-button>
          <el-button size="small" @click="onHandleReset">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 在修装备/工具列表 -->
    <el-table
      ref="itemTable"
      :data="itemList"
      style="width: 100%"
      border
      stripe
      size="small"
      fit
      @selection-change="onSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column align="center" type="index" label="序号" width="100" />
      <el-table-column align="center" prop="type" label="分类" min-width="70" />
      <el-table-column align="center" prop="typeName" label="类目" min-width="80" />
      <el-table-column align="center" prop="typeModelName" label="规格型号" min-width="100" />
      <el-table-column align="center" prop="manageMode" label="管理模式" min-width="80" />
      <el-table-column align="center" prop="devCode" label="设备编码" min-width="100" />
      <el-table-column align="center" prop="inStockNum" label="在库数量" width="100" />
      <el-table-column align="center" prop="scrapQuantity" label="申请报废数量" width="150">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.scrapQuantity"
            :min="1"
            :max="scope.row.inStockNum"
            size="small"
            style="width: 100%"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="text-align: center; margin-top: 15px;">
      <el-pagination
        :current-page.sync="queryParams.pageNum"
        :page-size.sync="queryParams.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 操作按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="onHandleConfirm">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getScrapItemListAPI } from '@/api/EquipmentRetireApply/index.js'

export default {
  props: {
    existingItems: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      visible: false,
      queryParams: {
        name: '',
        type: '',
        pageNum: 1,
        pageSize: 10
      },
      itemList: [],
      total: 0,
      selectedItems: [],
      allSelectedItems: [] // 保存所有页面的选中项
    }
  },
  watch: {
    'queryParams.pageNum'() {
      this.getItemList()
    },
    'queryParams.pageSize'() {
      this.queryParams.pageNum = 1
      this.getItemList()
    }
  },
  methods: {
    open() {
      this.visible = true
      this.getItemList()
    },

    async getItemList() {
      try {
        const res = await getScrapItemListAPI(this.queryParams)
        this.itemList = (res.rows || []).map(item => ({
          ...item,
          scrapQuantity: item.scrapQuantity || 1
        }))
        this.total = res.total || 0
      } catch (error) {
        this.$message.error('获取列表失败')
      }
    },

    onHandleQuery() {
      this.queryParams.pageNum = 1
      this.getItemList()
    },

    onHandleReset() {
      this.queryParams = {
        name: '',
        type: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getItemList()
    },

    onSelectionChange(selection) {
      this.selectedItems = selection
      // 更新所有选中项：移除当前页未选中的，添加当前页新选中的
      const currentPageKeyIds = this.itemList.map(item => item.keyId)
      // 保留其他页面的选中项
      this.allSelectedItems = this.allSelectedItems.filter(item => !currentPageKeyIds.includes(item.keyId))
      // 添加当前页的选中项
      this.allSelectedItems.push(...selection)
    },

    onHandleConfirm() {
      if (this.allSelectedItems.length === 0) {
        this.$message.warning('请选择至少一项')
        return
      }

      // 检查申请报废数量是否有效
      const invalidItems = this.allSelectedItems.filter(item => !item.scrapQuantity || item.scrapQuantity < 1)
      if (invalidItems.length > 0) {
        const invalidNames = invalidItems.map(item => item.typeModelName).join('、')
        this.$message.warning(`以下项目的申请报废数量必须大于0：${invalidNames}`)
        return
      }

      // 检查是否有重复的keyId
      const existingKeyIds = this.existingItems.map(item => item.keyId)
      const duplicates = this.allSelectedItems.filter(item => existingKeyIds.includes(item.keyId))

      if (duplicates.length > 0) {
        const duplicateNames = duplicates.map(item => item.typeModelName).join('、')
        this.$message.warning(`以下项目已存在，不能重复添加：${duplicateNames}`)
        return
      }

      this.$emit('confirm', this.allSelectedItems)
      this.visible = false
      this.selectedItems = []
      this.allSelectedItems = []
    },

    onClose() {
      this.selectedItems = []
      this.allSelectedItems = []
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

