<template>
  <div class="inbound-items-container">
    <!-- 操作按钮区域 -->
    <div class="toolbar-container mb8">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddItemClick"
          >新增物料</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleBatchDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['inventory:inbound_items:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-upload"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="pagedDisplayData"
        @selection-change="handleSelectionChange"
        :row-key="getRowKey"
        ref="dataTable"
        border
        stripe
        size="medium"
        v-bind="$attrs"
        v-on="$listeners"
      >
        <!-- 选择列 -->
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        />

        <!-- 序号列 -->
        <el-table-column
          label="序号"
          align="center"
          width="60"
        >
          <template slot-scope="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>

        <!-- 数据列 -->
        <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :label="column.label"
          :prop="column.prop"
          :align="column.align || 'center'"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
        >
          <template slot-scope="scope">
            <!-- 可编辑模式 -->
            <template v-if="scope.row.editable && column.editable !== false">
              <template v-if="column.type === 'select'">
                <el-select
                  v-model="scope.row[column.prop]"
                  size="small"
                  style="width: 100%"
                  @change="handleColumnChange(scope.row, column.prop)"
                >
                  <el-option
                    v-for="option in column.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </template>
              <template v-else-if="column.type === 'number'">
                <el-input-number
                  v-model="scope.row[column.prop]"
                  :min="column.min || 0"
                  :step="column.step || 1"
                  size="small"
                  style="width: 100%"
                  controls-position="right"
                  @change="handleNumberChange(scope.row, column.prop)"
                />
              </template>
              <template v-else>
                <el-input
                  v-model="scope.row[column.prop]"
                  size="small"
                  :placeholder="column.placeholder || '请输入'"
                  @blur="handleInputBlur(scope.row, column.prop)"
                  @change="handleInputChange(scope.row, column.prop)"
                />
              </template>
            </template>

            <!-- 只读模式 -->
            <template v-else>
              <template v-if="column.prop === 'itemStatus'">
                <el-tag
                  :type="getStatusType(scope.row[column.prop])"
                  size="small"
                >
                  {{ getStatusText(scope.row[column.prop]) }}
                </el-tag>
              </template>
              <template v-else-if="column.type === 'number'">
                {{ formatNumber(scope.row[column.prop]) }}
              </template>
              <template v-else>
                {{ scope.row[column.prop] }}
              </template>
            </template>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleRowEdit(scope.row)"
              v-if="!scope.row.editable"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleRowSave(scope.row)"
              v-else
            >保存</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRowDelete(scope.row, scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handlePagination"
        @size-change="handleSizeChange"
      />
      <import-excel
          ref="import"
          title="导入"
          import-url="/inventory/inbound_items/import"
          template-url="/inventory/inbound_items/exportTemplate"
          template-name="入库明细模板"
          @success="handleImportSuccess"
        />
    </div>
  </div>
</template>

<script>
import { listInbound_items, delInbound_items } from "@/api/inventory/inbound_items"
import ImportExcel from "@/components/ImportExcel/index"

export default {
  name: "InboundItems",
  inheritAttrs: false,
  components: { ImportExcel },
  props: {
    // 数据源
    value: {
      type: Array,
      default: () => []
    },
    // 主表ID
    orderId: {
      type: [String, Number],
      default: null
    },
    // 表格列配置
    columns: {
      type: Array,
      default: () => [
        { prop: 'materialId', label: '货物ID', width: '120', editable: false},
        { prop: 'materialName', label: '货物名称', width: '120', editable: false},
        // { prop: 'batchId', label: '批次ID', width: '120', editable: true },
        { prop: 'warehouseId', label: '仓库ID', width: '120', editable: true,
          type: 'select', // 指定类型为select
          options: [     // 下拉选项列表
            { label: '仓库A', value: 'WH001' },
            { label: '仓库B', value: 'WH002' },
            { label: '仓库C', value: 'WH003' }
          ] 
        },
        { prop: 'locationId', label: '库位ID', width: '120', editable: true ,
          type: 'select', // 指定类型为select
          options: [     // 下拉选项列表
            { label: '库位A1', value: 'LOC001' },
            { label: '库位A2', value: 'LOC002' },
            { label: '库位B1', value: 'LOC003' }
          ] 
        },
        { prop: 'plannedQuantity', label: '计划数量', width: '100', type: 'number', editable: true },
        { prop: 'actualQuantity', label: '实际数量', width: '100', type: 'number', editable: true },
        { prop: 'plannedPackages', label: '计划件数', width: '100', type: 'number', editable: true },
        { prop: 'actualPackages', label: '实际件数', width: '100', type: 'number', editable: true },
        { prop: 'unitPrice', label: '单价', width: '100', type: 'number', editable: true },
        { prop: 'remark', label: '备注', minWidth: '150', editable: true },
      ]
    },
    // 每页条数
    pageSize: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      selectedMaterials: [],
      loading: false,
      selectedRows: [],
      total: 0,
      displayData: [],
      pagedDisplayData: [],
      queryParams: {
        pageNum: 1,
        pageSize: this.pageSize,
        orderId: this.orderId
      },
      cachedData: []
    }
  },
  computed: {
    multiple() {
      return this.selectedRows.length === 0
    },
    // 计算总数
    totals() {
      return this.displayData.reduce((acc, item) => {
        acc.plannedQuantity += parseFloat(item.plannedQuantity) || 0
        acc.actualQuantity += parseFloat(item.actualQuantity) || 0
        acc.totalAmount += (parseFloat(item.plannedQuantity) || 0) * (parseFloat(item.unitPrice) || 0)
        return acc
      }, { plannedQuantity: 0, actualQuantity: 0, totalAmount: 0 })
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        const stringifiedNewVal = JSON.stringify(newVal || [])
        const stringifiedDisplayData = JSON.stringify(this.displayData.map(item => {
          const { editable, tempId, ...rest } = item
          return rest
        }))

        if (stringifiedNewVal !== stringifiedDisplayData) {
          this.cachedData = JSON.parse(JSON.stringify(newVal || []))
          this.displayData = (newVal || []).map(item => ({
            ...item,
            editable: false,
            tempId: item.id || Date.now() + Math.random()
          }))
          this.total = this.displayData.length
          this.handlePagination()
          this.calculateTotals()
        }
      }
    },
    displayData: {
      deep: true,
      handler() {
        this.total = this.displayData.length
        this.handlePagination()
        this.calculateTotals()
        this.syncDataToParent()
      }
    },
    orderId: {
      immediate: true,
      handler(newVal) {
        this.queryParams.orderId = newVal
        this.loadRelatedData(newVal)
        this.displayData.forEach(item => {
          if (!item.orderId) item.orderId = newVal
        })
      }
    },
    pageSize: {
      handler(val) {
        this.queryParams.pageSize = val
        this.handlePagination()
      }
    }
  },
  created() {
    this.handlePagination()
  },
  methods: {
    // 加载关联数据
    loadRelatedData(orderId) {
      if (!orderId) return

      this.loading = true
      this.queryParams.orderId = orderId

      listInbound_items(this.queryParams).then(response => {
        this.displayData = response.rows.map(item => ({
          ...item,
          editable: false,
          tempId: item.id || Date.now() + Math.random()
        }))
        this.total = response.total
        this.handlePagination()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 分页处理
    handlePagination() {
      const totalItems = this.displayData.length
      const totalPages = Math.ceil(totalItems / this.queryParams.pageSize)

      // 页码越界处理
      if (this.queryParams.pageNum > totalPages && totalPages > 0) {
        this.queryParams.pageNum = totalPages
      }

      // 计算分页数据
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      const end = start + this.queryParams.pageSize
      this.pagedDisplayData = this.displayData.slice(start, end)
    },
    // 切换每页条数
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.queryParams.pageNum = 1
      this.handlePagination()
    },
    // 同步数据到父组件
    syncDataToParent() {
      const dataToEmit = this.displayData.map(item => {
        const { editable, tempId, ...rest } = item
        return rest
      })
      this.$emit('input', dataToEmit)
      this.$emit('data-change', dataToEmit)
    },
    // 获取行key
    getRowKey(row) {
      return row.id || row.tempId
    },
    // 新增物料
    handleAddItemClick() {
      this.$emit('show-materials',true)
    },
    handleAddItem(selectedMaterials){
      selectedMaterials.forEach(material => {
        const newItem = {
          id: null,
          orderId: this.orderId,
          materialId: material.materialId,
          materialName: material.materialName,
          batchId: null,
          warehouseId: null,
          locationId: null,
          plannedQuantity: 0,
          actualQuantity: 0,
          plannedPackages: 0,
          actualPackages: 0,
          unitPrice: 0,
          remark: null,
          editable: true,
          tempId: Date.now() + Math.random()
        }
        this.displayData.push(newItem)
        // 自动跳转到最后一页
        const totalPages = Math.ceil(this.displayData.length / this.queryParams.pageSize)
        if (totalPages > this.queryParams.pageNum) {
          this.queryParams.pageNum = totalPages
        }
        this.$emit('item-added', newItem)
      })
      console.log(this.displayData)
    },
    // 行编辑
    handleRowEdit(row) {
      const index = this.displayData.findIndex(item => item.tempId === row.tempId)
      if (index > -1) {
        this.$set(this.displayData[index], 'editable', true)
      }
    },
    // 行保存
    handleRowSave(row) {
      const index = this.displayData.findIndex(item => item.tempId === row.tempId)
      if (index > -1) {
        this.$set(this.displayData[index], 'editable', false)
        this.$emit('row-saved', row)
      }
    },
    // 行删除
    handleRowDelete(row, index) {
      this.$confirm('确定要删除该明细项吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.displayData.splice(index, 1)

        // 删除后页码处理
        const currentPageDataCount = this.pagedDisplayData.length
        if (currentPageDataCount === 0 && this.queryParams.pageNum > 1) {
          this.queryParams.pageNum -= 1
        }

        this.$emit('row-deleted', row)
      })
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的项')
        return
      }

      this.$confirm('确定要删除选中的明细项吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const idsToDelete = this.selectedRows.map(row => row.id || row.tempId)
        this.displayData = this.displayData.filter(item =>
          !idsToDelete.includes(item.id || item.tempId)
        )

        // 删除后页码处理
        const totalPages = Math.ceil(this.displayData.length / this.queryParams.pageSize)
        if (this.queryParams.pageNum > totalPages && totalPages > 0) {
          this.queryParams.pageNum = totalPages
        }

        this.selectedRows = []
        this.$emit('batch-delete', idsToDelete)
      })
    },
     /** 导入按钮操作 */
    handleImport() {
      this.$refs.import.show()
    },
    // 导入成功处理
    handleImportSuccess() {
      this.$message.success('导入成功')
      this.loading = true
      listInbound_items(this.queryParams).then(response => {
        this.displayData = response.rows.map(item => ({
          ...item,
          editable: false,
          tempId: item.id || Date.now() + Math.random()
        }))
        this.loading = false
      })
    },
    // 导出
    handleExport() {
      this.download('inventory/inbound_items/export', {
        ...this.queryParams
      }, `inbound_items_${new Date().getTime()}.xlsx`)
    },
    // 输入框变化
    handleInputChange(row, prop) {
      this.$emit('cell-change', { row, prop, value: row[prop] })
    },
    // 数字变化
    handleNumberChange(row, prop) {
      row[prop] = parseFloat(row[prop]) || 0
      this.$emit('cell-change', { row, prop, value: row[prop] })
    },
    // 选择框变化
    handleColumnChange(row, prop) {
      this.$emit('cell-change', { row, prop, value: row[prop] })
    },
    // 输入框失去焦点
    handleInputBlur(row, prop) {
      this.$emit('cell-blur', { row, prop, value: row[prop] })
    },
    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.$emit('selection-change', selection)
    },
    // 获取状态类型
    getStatusType(status) {
      const map = { '1': 'info', '2': 'success', '3': 'danger' }
      return map[status] || 'info'
    },
    // 获取状态文本
    getStatusText(status) {
      const map = { '1': '待入库', '2': '已入库', '3': '已取消' }
      return map[status] || status
    },
    // 格式化数字
    formatNumber(num) {
      if (num == null) return ''
      return parseFloat(num).toLocaleString()
    },
    // 计算总数并通知父组件
    calculateTotals() {
      this.$emit('totals-change', this.totals)
    },
    // 验证数据
    validate() {
      const errors = []
      this.displayData.forEach((item, index) => {
        if (!item.materialId) {
          errors.push(`第${index + 1}行：货物ID不能为空`)
        }
        if (parseFloat(item.plannedQuantity) <= 0) {
          errors.push(`第${index + 1}行：计划数量必须大于0`)
        }
      })
      return errors
    },
    // 获取所有数据
    getItems() {
      return this.displayData.map(item => {
        const { editable, tempId, ...rest } = item
        return rest
      })
    },
    // 重置数据
    resetEmbeddedData() {
      this.displayData = JSON.parse(JSON.stringify(this.cachedData)).map(item => ({
        ...item,
        editable: false,
        tempId: item.id || Date.now() + Math.random()
      }))
    }
  }
}
</script>

<style scoped>
.inbound-items-container {
  width: 100%;
}

.toolbar-container {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.table-container {
  margin-top: 10px;
}

/* 行内编辑样式 */
.el-table .cell .el-input,
.el-table .cell .el-input-number,
.el-table .cell .el-select {
  width: 100%;
}

.el-table .cell .el-input-number {
  line-height: 32px;
}

/* 调整表格内边距 */
.el-table--medium td {
  padding: 6px 0;
}
</style>
