<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="id"
            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="''"
          >
            <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="searchParams.warehouseId"
        @selected="handleLocationSelected"
      />

      <!-- 表格 -->
      <div class="table-container">
        <el-table height="300px" :data="filteredItemsList"
                  :row-class-name="setRowIndex"
                  @selection-change="handleSelectionChange"
                  border
                  size="small">
          <el-table-column label="子表" align="center" min-width="150px" prop="id"  v-if="false" />
          <el-table-column label="物料" align="center" prop="materialId" min-width="150px" fixed>
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ getDictLabel(materialDict, scope.row.materialId, 'id', 'material_name') }}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="批次编号" align="center" prop="batchCode" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.batchCode }}
              </div>
            </template>
          </el-table-column> -->
          <el-table-column label="仓库" align="center" prop="warehouseName" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.warehouseName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库位" align="center" prop="locationName" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.locationName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="系统数量" align="center" prop="systemQuantity" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.systemQuantity }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="实际数量" align="center" prop="actualQuantity" min-width="150px" >
            <template slot-scope="scope">
              <template v-if="isConfirm">
                <div class="disabled-input">
                  {{ scope.row.actualQuantity }}
                </div>
              </template>
              <template v-else>
                <el-input v-model="scope.row.actualQuantity"
                          placeholder="请输入实际数量"
                          type="number"
                          @input="handleItemChange(scope.row)"
                />
              </template>
            </template>
          </el-table-column>
          <el-table-column label="差异数量" align="center" prop="varianceQuantity" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.varianceQuantity }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="unitPrice" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ formatAmount(scope.row.unitPrice) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="差异金额" align="center" prop="varianceAmount" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ formatAmount(scope.row.varianceAmount) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="是否已调整" align="center" prop="adjusted"  v-if="isConfirm" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                <dict-tag :options="dict.type.is_adjusted" :value="scope.row.adjusted"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="adjustedType" align="center" label="调整原因类型" min-width="150px">
            <template slot-scope="scope">
              <template v-if="isConfirm">
                <div>
                  {{ getAdjustReasonName(scope.row.adjustedType) }}
                </div>
              </template>
              <template v-if="!isConfirm">
                <el-select
                  v-model="scope.row.adjustedType"
                  placeholder="请选择调整原因类型"
                  :style="getAdjustTypeErrorStyle(scope.row)"
                  @change="handleItemChange(scope.row)"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="item in dict.type.adjusted_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="调整原因" align="center" prop="adjustmentReason" min-width="150px" >
            <template slot-scope="scope">
              <template v-if="isConfirm">
                <div>
                  {{ scope.row.adjustmentReason }}
                </div>
              </template>
              <template v-if="!isConfirm">
                <el-input
                  v-model="scope.row.adjustmentReason"
                  placeholder="请输入调整原因"
                  type="text"
                  :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>
            </template>
          </el-table-column>
          <!-- <el-table-column label="调整人" align="center" prop="adjustedBy" v-if="isConfirm" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.adjustedBy }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="调整时间" align="center" prop="adjustedAt" v-if="isConfirm" min-width="150px" >
            <template slot-scope="scope">
              <div class="disabled-input">
                {{ scope.row.adjustedAt }}
              </div>
            </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",
  dicts: ['adjusted_type','is_adjusted'],
  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: "",
        locationId: ""
      },
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      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 || '').trim(),
        locationId: String(item.locationId || '').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
      })
console.log('itemlist', filtered)
console.log(this.isConfirm)
      // 更新总数+分页
      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,
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0.00'
      }
      return parseFloat(amount).toFixed(2)
    },
    // 搜索，补全逻辑（无后端请求，仅重置页码）
    handleQuery() {
      this.searchParams.pageNum = 1; // 搜索后重置页码
    },
    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },
    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      // 供列表筛选：存仓库编码333（匹配列表里的warehouseId:333
      this.searchParams.warehouseId = warehouse.warehouseId
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehouseId
      // // 仓库选择后，清空库位信息
      // this.queryLocationName = null
      // this.searchParams.locationId = null
      this.handleQuery()
    },

    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.searchParams.warehouseId = null
      // // 清空仓库时，同时清空库位
      // this.queryLocationName = null
      // this.searchParams.locationId = null
      this.handleQuery()
    },

    /** 打开库位选择器 */
    openLocationSelector() {
      // if (!this.searchParams.warehouseId) {
      //   this.$message.warning("请先选择仓库")
      //   return
      // }
      this.locationSelectorVisible = true
    },

    /** 库位选择回调 */
    handleLocationSelected(location) {
      if (!location) return
      this.searchParams.locationId = location.locationId
      this.queryLocationName = location.locationName || location.locationId
      this.handleQuery()
    },

    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.searchParams.locationId = null
      this.handleQuery()
    },

    // 重置
    resetQuery() {
      this.queryWarehouseName = null
      this.queryLocationName = null
      this.searchParams = {
        pageNum: 1,
        pageSize: 10,
        materialId: "",
        batchCode: "",
        warehouseId: "",
        locationId: ""
      };
      // 重置库位选择器
      this.handleWarehouseClear()

    },

    // 仓库清空时触发
    handleWarehouseClear() {
      this.searchParams.locationId = ''
      this.searchParams.warehouseId = ''
      this.handleQuery()
    },

    // 给子表设置序号
    setRowIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },

    // 选中行变化
    handleSelectionChange(selection) {
      this.checkedRows = selection;
    },

    // （解决报错）
    getList() {},
    // 字典加载完成回调（缓存字典数据，供表格展示使用）
    handleDictLoaded(type, data) {
      if (type === 'material') {
        this.materialDict = data
      }
    },
// 计算调整类型的错误样式
    getAdjustTypeErrorStyle(row) {
      // 1. 先统一转换差异数量为数字（避免字符串/空值问题）
      const varianceQty = Number(row.varianceQuantity) || 0;
      // 2. 统一转换调整类型为字符串（覆盖数字0/字符串0/空值）
      const adjustedType = String(row.adjustedType || '0').trim();

      // 3. 核心条件：差异数量≠0 且 调整类型是0/空/未选择
      if (varianceQty !== 0 && (adjustedType === '0' || adjustedType === '')) {
        return {
          border: '1px solid #f56c6c',
          boxShadow: '0 0 0 2px rgba(245,108,108,0.2)'
        };
      }
      // 无错误时返回空样式
      return {};
    },
    // 校验调整原因必填项
    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() === '';
        // 4.调整原因类型为0-未调整
        const isTypeZearo = !row.adjustedType || row.adjustedType.trim() === '0';
        // 最终条件：差异非0 且 调整原因为空 → 才需要提示
        return isVarianceNonZero && isReasonEmpty && isTypeZearo;
      });

      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;
        row.adjustedType = '0';
      } 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);
    },
    /** 获取调整原因名称 */
    getAdjustReasonName(status) {
      console.log('status', status)
      console.log('typelist', this.dict.type.adjusted_type)
      const item = this.dict.type.adjusted_type.find(item => item.value === status)
      return item ? item.label : '未知'
    }
  }
}
</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;
  padding: 0 15px; height: 32px; line-height: 32px;
} */
</style>
