<template>
  <div class="app-container" >
    <!-- 子表搜索栏 -->
    <div class="page-container">
      <page-wrapper-search
        v-model="searchParams"
        ref="queryForm"
        size="small"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="物料" prop="materialId">
          <common-dict-select
              v-model="searchParams.materialId"
              dict-url="/inventory/materials/getMapList"
              value-key="sap_no"
              label-key="material_name"
              placeholder="请选择物料"
              @change="handleQuery"
              @loaded="handleDictLoaded('material', $event)"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-input
              v-model="queryWarehouseName"
              placeholder="请选择仓库"
              readonly
              @focus="openWarehouseSelector"
              :suffix-icon="''"
          >
            <template v-if="queryWarehouseName" #suffix>
              <i
                  class="el-icon-circle-close el-input__icon"
                  style="cursor: pointer;"
                  @click.stop="clearQueryWarehouse"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="库位" prop="locationId">
          <el-input
              v-model="queryLocationName"
              placeholder="请选择库位"
              readonly
              @focus="openLocationSelector"
              :suffix-icon="''"
              :disabled="!searchParams.warehousesCode"
          >
            <template v-if="queryLocationName" #suffix>
              <i
                  class="el-icon-circle-close el-input__icon"
                  style="cursor: pointer;"
                  @click.stop="clearQueryLocation"
              ></i>
            </template>
          </el-input>
        </el-form-item>
      </page-wrapper-search>

      <!-- 仓库选择组件 -->
      <WarehouseSelector
          v-model="warehouseSelectorVisible"
          @selected="handleWarehouseSelected"
      />
      <!-- 库位选择组件 -->
      <LocationSelector
          v-model="locationSelectorVisible"
          :warehousesId="currentWarehouseId"
          @selected="handleLocationSelected"
      />

      <!-- 表格 -->
      <div class="table-container">
        <el-table :data="filteredItemsList"
                  :row-class-name="setRowIndex"
                  @selection-change="handleSelectionChange"
                  border
                  size="small">
          <el-table-column label="子表ID" align="center" width="150px" prop="id"  v-if="false" />
          <el-table-column label="物料" align="center" prop="materialId" width="150px" fixed>
            <template slot-scope="scope">
              <div class="el-input__inner disabled-input" style="padding: 0 15px; height: 32px; line-height: 32px;">
                {{ getDictLabel(materialDict, scope.row.materialId, 'sap_no', 'material_name') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="批次编号" align="center" prop="batchCode" width="150px" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchCode" placeholder="请输入批次编号" disabled />
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" prop="warehouseName" width="150px" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.warehouseName" placeholder="请输入仓库" disabled />
<!--              <div class="el-input__inner disabled-input" style="padding: 0 15px; height: 32px; line-height: 32px;">-->
<!--                {{ scope.row.warehouse_name || scope.row.warehouseId || '未知仓库' }}-->
<!--              </div>-->
            </template>
          </el-table-column>
          <el-table-column label="库位" align="center" prop="locationName" width="150px" >
            <template slot-scope="scope">
<!--              <div class="el-input__inner disabled-input" style="padding: 0 15px; height: 32px; line-height: 32px;">-->
<!--                {{ scope.row.location_name || scope.row.locationId || '未知库位' }}-->
<!--              </div>-->
              <el-input v-model="scope.row.locationName" placeholder="请输入库位" disabled />
            </template>
          </el-table-column>
          <el-table-column label="系统数量" align="center" prop="systemQuantity" width="150px" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.systemQuantity" placeholder="请输入系统数量" disabled />
            </template>
          </el-table-column>
          <el-table-column label="实际数量" align="center" prop="actualQuantity" width="150px" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.actualQuantity"
                        placeholder="请输入实际数量"
                        type="number"
                        :disabled="isConfirm"
                        @input="handleItemChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="差异数量" align="center" prop="varianceQuantity" width="150px" >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.varianceQuantity" placeholder="请输入差异数量" disabled />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="unitPrice" width="150px" >
            <template slot-scope="scope">
              <div class="el-input__inner disabled-input" style="padding: 0 15px; height: 32px; line-height: 32px;">
                {{ formatAmount(scope.row.unitPrice) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="差异金额" align="center" prop="varianceAmount" width="150px" >
            <template slot-scope="scope">
              <div class="el-input__inner disabled-input" style="padding: 0 15px; height: 32px; line-height: 32px;">
                {{ formatAmount(scope.row.varianceAmount) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="是否已调整" align="center" prop="adjusted"  v-if="isConfirm" width="150px" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.adjusted" placeholder="请输入是否已调整0否1是" disabled />
            </template>
          </el-table-column>
          <el-table-column label="调整原因" align="center" prop="adjustmentReason" width="150px" >
            <template slot-scope="scope">
              <el-input
                  v-model="scope.row.adjustmentReason"
                  placeholder="请输入调整原因"
                  type="text"
                  :disabled="isConfirm"
                  :style="(Number(scope.row.varianceQuantity)||0)!==0 && !scope.row.adjustmentReason ? {border:'1px solid #f56c6c',boxShadow:'0 0 0 2px rgba(245,108,108,0.2)'} : {}"
                  @input="handleItemChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="调整人" align="center" prop="adjustedBy" v-if="isConfirm" width="150px" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.adjustedBy" placeholder="请输入调整人" disabled />
            </template>
          </el-table-column>
          <el-table-column label="调整时间" align="center" prop="adjustedAt"v-if="isConfirm" width="150px" >
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.adjustedAt" type="date" value-format="yyyy-MM-dd" placeholder="请选择调整时间" disabled />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="searchParams.pageNum"
        :limit.sync="searchParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { getDictLabel } from '@/utils/dictUtil'
import CommonDictSelect from '@/components/CommonDictSelect.vue'

import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"
export default {
  name: "stocktakeItemsTable",
  components: { CommonDictSelect,WarehouseSelector,LocationSelector }, // 注册通用字典组件
  props: {
    // 接收父组件传递的子表原始数据（双向绑定）
    itemsList: {
      type: Array,
      default: () => []
    },
    isConfirm: { // true=盘点确认（全部只读+显示所有字段），false=盘点（部分可编辑+隐藏部分字段）
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchParams: { // 子表搜索参数
        pageNum: 1,    // 当前页
        pageSize: 10,  // 每页条数
        materialId: "",
        batchCode: "",
        warehouseId: "",
        warehousesCode: null,
        locationId: ""
      },
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      currentWarehouseId: "", // 存仓库原始ID（0eb22b11...），供库位联动
      checkedRows: [], // 子表选中的行
      materialDict: [],  // 物料字典数组（存储sap_no和name）
      warehouseDict: [], // 仓库数组
      locationDict: [], // 库位数组
      // 分页总数
      total: 0,
      // 表格加载状态
      tableLoading: false
    }
  },
  computed: {
    // 筛选+分页后的表格数据
    filteredItemsList() {
      if (!this.itemsList || this.itemsList.length === 0) {
        this.total = 0
        return []
      }

      // 统一类型：所有值转字符串+去空格，避免匹配问题
      const normalizedItems = this.itemsList.map(item => ({
        ...item,
        materialId: String(item.materialId || '').trim(),
        warehouseId: String(item.warehouseId || item.warehouses_code || '').trim(),
        locationId: String(item.locationId || item.location_code || '').trim()
      }))

      // 精准筛选
      const filtered = normalizedItems.filter(item => {
        const matchMaterial = this.searchParams.materialId
          ? item.materialId === String(this.searchParams.materialId).trim()
          : true
        const matchWarehouse = this.searchParams.warehouseId
          ? item.warehouseId === String(this.searchParams.warehouseId).trim()
          : true
        const matchLocation = this.searchParams.locationId
          ? item.locationId === String(this.searchParams.locationId).trim()
          : true
        return matchMaterial && matchWarehouse && matchLocation
      })

      // 更新总数+分页
      this.total = filtered.length
      const start = (this.searchParams.pageNum - 1) * this.searchParams.pageSize
      const end = start + this.searchParams.pageSize
      return filtered.slice(start, end)
    }
  },
  methods: {
    // 挂载全局字典工具方法（模板中可直接调用）
    getDictLabel,
    // 手动加载字典（按你的字典接口规则来）
    loadDict(type) {
      // 字典接口地址（和你注释里的common-dict-select一致）
      const dictConfig = {
        // material: { url: '/inventory/materials/getMapList' },
        warehouse: { url: '/inventory/warehouses/getMapList' },
        // 库位字典需要传仓库编码（warehousesCode），
        location: { url: '/inventory/locations/getMapList', params: { warehousesCode: this.searchParams.warehousesCode } }
      }
      const config = dictConfig[type]
      if (!config) return

      this.$http.get(config.url, { params: config.params }).then(res => {
        this.handleDictLoaded(type, res.data || [])
      })
    },
    // 仓库选择变化时触发
    handleWarehouseChange(warehouseId) {
      // 1. 清空库位选择
      this.searchParams.locationId = ''
      // 2. 执行搜索
      this.searchParams.warehouseId = warehouseId
      this.handleQuery()
    },
    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },
    // 仓库清空时触发
    handleWarehouseClear() {
      this.searchParams.locationId = ''
      this.searchParams.warehouseId = ''
      this.currentWarehouseId = ''
      this.handleQuery()
    },
    /** 库位选择回调 */
    handleLocationSelected(location) {
      if (!location) return
      this.searchParams.locationId = location.locationCode
      this.queryLocationName = location.locationName || location.locationCode
      // console.log('selected LocationName', location);
      this.handleQuery()
    },
    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      // 供库位联动：存仓库原始ID（0eb22b11...）
      this.currentWarehouseId = warehouse.warehouseId
      // 供列表筛选：存仓库编码333（匹配列表里的warehouseId:333
      this.searchParams.warehouseId = warehouse.warehousesCode
      this.searchParams.warehousesCode = warehouse.warehousesCode
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // 仓库选择后，清空库位信息
      this.queryLocationName = null
      this.searchParams.locationId = null
      this.handleQuery()
      // console.log('selected warehouse', warehouse);
    },
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0.00'
      }
      return parseFloat(amount).toFixed(2)
    },
    // 搜索，补全逻辑（无后端请求，仅重置页码）
    handleQuery() {
      this.searchParams.pageNum = 1; // 搜索后重置页码
    },
    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.searchParams.warehouseId = null
      this.searchParams.warehousesCode = null
      this.currentWarehouseId = ""
      // 清空仓库时，同时清空库位
      this.queryLocationName = null
      this.searchParams.locationId = null
      this.handleQuery()
    },
    /** 打开库位选择器 */
    openLocationSelector() {
      if (!this.currentWarehouseId) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.locationSelectorVisible = true
    },
    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.searchParams.locationId = null
      this.handleQuery()
    },
    // 重置
    resetQuery() {
      this.queryWarehouseName = null
      this.queryLocationName = null
      this.currentWarehouseId = ''
      this.searchParams = {
        pageNum: 1,
        pageSize: 10,
        materialId: "",
        batchCode: "",
        warehouseId: "",
        locationId: ""
      };
      // 重置库位选择器
      this.handleWarehouseClear()

    },
    // （解决报错）
    getList() {},
    // 字典加载完成回调（缓存字典数据，供表格展示使用）
    handleDictLoaded(type, data) {
      switch (type) {
        case 'material':
          this.materialDict = data
          break
        case 'warehouse':
          this.warehouseDict = data
          break
        case 'location':
          this.locationDict = data
          break
      }
    },
    // 给子表设置序号
    setRowIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    // 选中行变化
    handleSelectionChange(selection) {
      this.checkedRows = selection;
    },
    // 校验调整原因必填项
    validateAdjustReason() {
      const invalidRows = this.filteredItemsList.filter(row => {
        // 1. 先处理空值：null/'' 转为 0
        const varianceQty = Number(row.varianceQuantity) || 0;
        // 2. 核心条件：只有差异数量≠0 时，才校验调整原因必填
        const isVarianceNonZero = varianceQty !== 0;
        // 3. 调整原因为空（处理null/''/全空格）
        const isReasonEmpty = !row.adjustmentReason || row.adjustmentReason.trim() === '';

        // 最终条件：差异非0 且 调整原因为空 → 才需要提示
        return isVarianceNonZero && isReasonEmpty;
      });

      if (invalidRows.length > 0) {
        this.$message.error(`第${invalidRows.map(r => r.index).join(',')}行差异数量非0，请填写调整原因`);
        return false;
      }
      return true;
    },
    // 父页面调用：获取子表完整数据
    getSubTableData() {
      return this.itemsList // 若需过滤已选行，可返回this.checkedRows
    },
    // 父页面调用：校验子表数据
    validateSubTable() {
      // 先校验调整原因
      if (!this.validateAdjustReason()) return false
      // 可扩展其他校验（如必填项、数值合法性等）
      return true
    },
    // 子表字段编辑时，同步给父组件（确保数据一致）
    handleItemChange(row) {
      if (!row.actualQuantity || row.actualQuantity === '') {
        row.varianceAmount = null;
        row.varianceQuantity = null;
        row.adjustmentReason = null;
      } else {
        // 处理空值/非数字情况，默认0
        const actualQty = Number(row.actualQuantity) || 0
        const systemQty = Number(row.systemQuantity) || 0
        // 计算差异：实际数量 - 系统数量
        row.varianceQuantity = actualQty - systemQty
        // 计算差异金额：差异数量*单价
        row.varianceAmount = (row.varianceQuantity * row.unitPrice).toFixed(2) * 1
      }
      // 实时校验调整原因，触发样式更新
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      // 同步通知父组件数据变化
      this.$emit("item-change", row);
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 16px;
}
.page-container {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
}
.table-container {
  margin-top: 16px;
}
.mb8 {
  margin-bottom: 8px;
}
:deep(.el-table) {
  --el-table-header-text-color: #606266;
  --el-table-row-hover-bg-color: #f5f7fa;
}
.disabled-input {
  background-color: #f5f7fa !important;
  border: 1px solid #e5e6eb !important;
  color: #909399 !important;
  cursor: not-allowed !important;
  border-radius: 4px !important;
}
</style>
