<template>
  <div class="inbound-items-container">
    <!-- 查询表单-->
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="货物ID" prop="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入货物ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库ID" prop="warehouseId">
        <el-input
          v-model="queryParams.warehouseId"
          placeholder="请输入仓库ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位ID" prop="locationId">
        <el-input
          v-model="queryParams.locationId"
          placeholder="请输入库位ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签颜色" prop="labelColor">
        <el-select v-model="queryParams.labelColor" placeholder="请选择标签颜色" clearable style="width: 200px;">
          <el-option
            v-for="item in dict.type.label_color"
            :key="item.value"
            :value="item.value"
          >
            <template #label>
              <el-tag
                :type="getDictListClass('label_color', item.value)"
                size="small"
                style="margin-right: 8px;"
              >
                {{ item.label }}
              </el-tag>
              <span>{{ item.label }}</span>
            </template>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="凭证号" prop="voucherNumber">
        <el-input
          v-model="queryParams.voucherNumber"
          placeholder="请输入凭证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <!-- 操作按钮区域 -->
    <div class="toolbar-container mb8">
      <el-row :gutter="10">
        <el-col :span="1.5" v-if="isEditable">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddItemClick"
          >新增物料</el-button>
        </el-col>
        <el-col :span="1.5" v-if="isEditable">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleBatchDelete"
          >删除</el-button>
        </el-col>
        <!-- <el-col :span="1.5" v-if="isEditable">
          <el-button
            type="success"
            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-download"
            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 && isEditable !==false">
              <!-- 仓库选择 -->
              <template v-if="column.prop === 'warehousesName'">
                <el-input
                  v-model="scope.row.warehousesName"
                  size="small"
                  readonly
                  placeholder="请选择源仓库"
                  @focus="$emit('open-warehouse-selector', scope.row)"
                  :suffix-icon="''"
                >
                  <template v-if="scope.row.warehousesName" #suffix>
                    <i
                      class="el-icon-circle-close el-input__icon"
                      style="cursor: pointer;"
                      @click.stop="clearWarehouse(scope.row)"
                    ></i>
                  </template>
                </el-input>
              </template>
              <!-- 库位选择 -->
              <template v-else-if="column.prop === 'locationName'">
                <el-input
                  v-model="scope.row.locationName"
                  size="small"
                  readonly
                  placeholder="请选择库位"
                  @focus="$emit('open-location-selector', scope.row)"
                  :suffix-icon="''"
                >
                  <template v-if="scope.row.locationName" #suffix>
                    <i
                      class="el-icon-circle-close el-input__icon"
                      style="cursor: pointer;"
                      @click.stop="clearLocation(scope.row)"
                    ></i>
                  </template>
                </el-input>
              </template>
              <!-- 其他选择框 -->
              <template v-else-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 === 'labelColor'">
                <el-tag
                  :type="getDictListClass('label_color', scope.row.labelColor)"
                  size="small"
                >
                  {{ getDictLabel('label_color', scope.row.labelColor) }}
                </el-tag>
              </template>
              <template v-else-if="column.type === 'number'">
                {{ formatNumber(scope.row[column.prop]) }}
              </template>
              <!-- 仓库/库位兜底显示 -->
              <template v-else-if="column.prop === 'warehousesName'">
                {{ scope.row.warehousesName || scope.row.warehouseId || '-' }}
              </template>
              <template v-else-if="column.prop === 'locationName'">
                {{ scope.row.locationName || scope.row.locationCode || scope.row.locationId || '-' }}
              </template>
              <template v-else>
                {{ scope.row[column.prop] || '-' }}
              </template>
            </template>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          v-if="isEditable"
        >
          <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_itemsAndMname } from "@/api/inventory/inbound_items"
import ImportExcel from "@/components/ImportExcel/index"

export default {
  name: "InboundItems",
  inheritAttrs: false,
  dicts: ['label_color'],
  components: { ImportExcel },
  props: {
    // 数据源
    value: {
      type: Array,
      default: () => []
    },
    isEditable: {
      type: Boolean,
      default: true
    },
    // 主表ID
    inboundOrderId: {
      type: [String, Number],
      default: null
    },
    // 表格列配置
    columns: {
      type: Array,
      default: () => [
        { prop: 'sapNo', label: 'SapNo', width: '150', editable: false },
        { prop: 'materialName', label: '货物名称', width: '150', editable: false },
        {
          prop: 'warehousesName',
          label: '源仓库',
          width: '150',
          editable: true,
          idProp: 'warehouseId'
        },
        {
          prop: 'locationName',
          label: '库位',
          width: '150',
          editable: true,
          idProp: 'locationId',
          codeProp: 'locationCode'
        },
        { 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: 'divisor', label: '约数', width: '100', type: 'number', editable: true },
        { prop: 'labelColor', label: '标签颜色', width: '100', type: 'select', editable: true },
        { prop: 'voucherNumber', label: '凭证号', width: '150', editable: true },
        { prop: 'unitPrice', label: '单价', width: '100', type: 'number', editable: true },
        { prop: 'receivedBy', label: '收货人', width: '150', editable: true },
        { prop: 'labelQuantity', label: '贴标数量', width: '150',type: 'number', editable: true },
        { prop: 'remark', label: '备注', minWidth: '150', editable: true },
      ]
    },
    // 每页条数
    pageSize: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      showSearch: true,
      loading: false,
      selectedRows: [],
      total: 0,
      displayData: [],
      pagedDisplayData: [],
      queryParams: {
        pageNum: 1,
        materialId: null,
        inboundOrderId: null,
        warehouseId: null,
        locationId: null,
        labelColor: null,
        voucherNumber: null,
        receivedBy: null,
        pageSize: this.pageSize
      },
      cachedData: []
    }
  },
  computed: {
    // columns() {
    //   return [
    //    { prop: 'sapNo', label: 'SapNo', width: '150', editable: false },
    //     { prop: 'materialName', label: '货物名称', width: '150', editable: false },
    //     {
    //       prop: 'warehousesName',
    //       label: '源仓库',
    //       width: '150',
    //       editable: true,
    //       idProp: 'warehouseId'
    //     },
    //     {
    //       prop: 'locationName',
    //       label: '库位',
    //       width: '150',
    //       editable: true,
    //       idProp: 'locationId',
    //       codeProp: 'locationCode'
    //     },
    //     { 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: 'divisor', label: '约数', width: '100', type: 'number', editable: true },
    //     { prop: 'labelColor', label: '标签颜色', width: '100', type: 'select', editable: true,
    //         options: labelColorOptions.map(item => ({
    //         value: item.value,
    //         label: item.label,
    //         raw: item.raw // 如果需要保持 raw 数据
    //       }))
    //     },
    //     { prop: 'voucherNumber', label: '凭证号', width: '150', editable: true },
    //     { prop: 'unitPrice', label: '单价', width: '100', type: 'number', editable: true },
    //     { prop: 'receivedBy', label: '收货人', width: '150', editable: true },
    //     { prop: 'labelQuantity', label: '贴标数量', width: '150',type: 'number', editable: true },
    //     { prop: 'remark', label: this.getRemarkLabel(), minWidth: '150', editable: true },
    //   ]
    // },
    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,
            sapNo: item.sapNo, // 确保sapNo字段被保存
            materialName: item.materialName, // 确保materialName字段被保存
            editable: true,
            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()
      }
    },
    inboundOrderId: {
      immediate: true,
      handler(newVal) {
        // 核心：过滤 null/空值，只在有效时执行逻辑
        if (!newVal) return
        this.loadRelatedData(newVal)
        this.displayData.forEach(item => {
          if (!item.inboundOrderId) item.inboundOrderId = newVal
        })
      }
    },
    pageSize: {
      handler(val) {
        this.queryParams.pageSize = val
        this.handlePagination()
      }
    }
  },
  created() {
    this.initLabelColorOptions()
    this.handlePagination()
  },
  methods: {
    getRemarkLabel(){
       if (!this.displayData || !this.displayData.orderTypeId) {
        return '备注'
      }
      if(this.displayData.orderTypeId === 1 || this.displayData.orderTypeId === '1'){
        return '收获库位'
      }else if(this.displayData.orderTypeId === 2 || this.displayData.orderTypeId === '2'){
        return '库位'
      }else{
        return '备注'
      }
    },
    // 根据字典类型和值，获取对应的listClass（标签样式）
    getDictListClass(dictType, value) {
      const dictList = this.dict.type[dictType] || []
      if (!value) return ''
      const dictItem = dictList.find(item => item.value === value+"")

      // 兼容raw和直接属性两种写法
      return dictItem?.raw?.listClass
    },

    // 根据字典类型和值，获取对应的显示标签
    getDictLabel(dictType, value) {
      const dictList = this.dict.type[dictType] || []
      if (!value) return ''
      const dictItem = dictList.find(item => item.value === value+"")
      return dictItem?.label || value
    },

    // 初始化标签颜色下拉选项
    initLabelColorOptions() {
      const labelColorCol = this.columns.find(col => col.prop === 'labelColor')
      if (labelColorCol) {
        labelColorCol.options = this.dict.type.label_color || []
      }
    },

    // 加载关联数据
    loadRelatedData(inboundOrderId) {
      if (!inboundOrderId) return
      this.loading = true
      this.queryParams.inboundOrderId = inboundOrderId
      listInbound_itemsAndMname(this.queryParams).then(response => {
        this.displayData = response.rows.map(item => ({
          ...item,
          sapNo: item.sapNo,
          materialName: item.materialName,
          editable: true,
          tempId: item.id || Date.now() + Math.random()
        }))
        this.total = response.total
        this.handlePagination()
        this.loading = false
      }).catch(() => {
        this.loading = false
      }).finally(() => {

      })
    },

    // 分页处理
    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
    },

    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置按钮操作
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },

    // 获取列表数据
    getList() {
      this.loading = true
      listInbound_itemsAndMname(this.queryParams).then(response => {
        this.displayData = response.rows.map(item => ({
          ...item,
          editable: true,
          tempId: item.id || Date.now() + Math.random()
        }))
        this.total = response.total
        this.handlePagination()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 新增物料
    handleAddItemClick() {
      this.$emit('show-materials', true)
    },

    handleAddItem(selectedMaterials) {
      selectedMaterials.forEach(material => {
        const newItem = {
          id: null,
          orderId: this.orderId,
          materialId: material.id,
          sapNo: material.sapNo,
          materialName: material.materialName,
          batchId: null,
          warehouseId: null,
          locationId: null,
          plannedQuantity: 0,
          actualQuantity: 0,
          plannedPackages: 0,
          actualPackages: 0,
          divisor: 0,
          unitPrice: 0,
          remark: null,
          editable: true,
          inboundOrderId: null,
          labelQuantity: 0,
          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)
      })
    },

    // // 行编辑
    // 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)
          if (this.pagedDisplayData.length === 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_itemsAndMname(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/export', {
        ...this.queryParams,
        id: this.inboundOrderId
      }, `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] })
    },

    // 清除仓库选择
    clearWarehouse(row) {
      this.$set(row, 'warehouseId', null);
      this.$set(row, 'warehousesName', null);
      // // 同时清除库位选择
      // this.clearLocation(row);
      // this.$emit('cell-change', { row, prop: 'warehouseId', value: null });
    },

    // 清除库位选择
    clearLocation(row) {
      this.$set(row, 'locationId', null);
      this.$set(row, 'locationCode', null);
      this.$set(row, 'locationName', null);
      this.$emit('cell-change', { row, prop: 'locationId', value: null });
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.$emit('selection-change', selection)
    },

    // 格式化数字
    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}行：货物不能为空`)
        }
        if (parseFloat(item.actualQuantity) <= 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;
}

/* 下拉选项tag样式适配 */
:deep(.el-select-dropdown__item .el-tag) {
  vertical-align: middle;
}

:deep(.el-select .el-tag) {
  margin: 0;
}
</style>
