<template>
  <div class="app-container" >
    <!-- 子表搜索栏（按需求添加搜索字段） -->
    <div class="page-container">
      <page-wrapper-search
        :model="queryParams"
        ref="queryForm"
        size="small"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="计划日期">
          <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="物料" prop="materialId">
          <common-dict-select
            v-model="queryParams.materialId"
            dict-url="/inventory/materials/getMapList"
            value-key="sap_no"
            label-key="material_name"
            placeholder="请选择物料"
            @change="handleQuery"
            @loaded="handleDictLoaded('material', $event)"
            @input="queryParams.materialId = $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="!queryParams.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>

      <div class="table-container">
        <el-table v-loading="loading" height="300px" :data="stocktakesList" @selection-change="handleSelectionChange">
          <el-table-column label="计划日期" align="center" prop="plannedDates" width="180" />

          <el-table-column label="物料" align="center" prop="materialId" fixed>
            <template slot-scope="scope">
                {{ getDictLabel(materialDict, scope.row.materialId, 'sap_no', 'material_name') }}
            </template>
          </el-table-column>

          <el-table-column label="SAP物料号" align="center" prop="sapNo" />
          <el-table-column label="TS Code" align="center" prop="tsCode" />
          <el-table-column label="危险类别" align="center" prop="hazardName" />
<!--          <el-table-column label="批次编号" prop="batchCode">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.batchCode" placeholder="请输入批次编号" disabled />-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="仓库Id" align="center" prop="warehousesId" v-if="false" />
          <el-table-column label="库位Id" align="center" prop="locationId" v-if="false" />

          <el-table-column label="仓库" align="center" prop="warehousesName" />
          <el-table-column label="库位" align="center" prop="locationName" />
          <el-table-column label="差异总数" align="center" prop="countQuantity" />
<!--            <template slot-scope="scope">-->
<!--              <el-input type="number" v-model="scope.row.varianceQuantity" placeholder="请输入差异数量" disabled />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="单价" prop="unitPrice">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.unitPrice" placeholder="请输入单价" disabled />-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="差异总金额" prop="unitPrice">
            <template slot-scope="scope">
              {{ formatAmount(scope.row.countAmount) }}
            </template>
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.varianceAmount" placeholder="请输入差异金额" disabled />-->
<!--            </template>-->
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleCountViewInfo(scope.row)"
              >查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!-- 仓库选择组件 -->
      <WarehouseSelector
        v-model="warehouseSelectorVisible"
        @selected="handleWarehouseSelected"
      />
      <!-- 库位选择组件 -->
      <LocationSelector
        v-model="locationSelectorVisible"
        :warehousesId="currentWarehouseId"
        @selected="handleLocationSelected"
      />
    </div>
    <!-- 详情查看 -->
    <el-dialog title="统计详情查看" :visible.sync="viewOpen" width="800px" append-to-body>
      <el-table :data="detailList" border stripe size="small" style="width: 100%;">
        <el-table-column label="计划日期" prop="plannedDates" />
        <el-table-column label="物料" prop="materialId" fixed>
          <template slot-scope="scope">
            {{ getDictLabel(materialDict, scope.row.materialId, 'sap_no', 'material_name') || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="SAP物料号" align="center" prop="sapNo" />
        <el-table-column label="仓库" align="center" prop="warehousesName" />
        <el-table-column label="库位" align="center" prop="locationName" />
        <el-table-column label="危险类别" align="center" prop="hazardName" />
        <el-table-column label="差异数量" align="center" prop="varianceQuantity" />
        <el-table-column label="差异金额" align="center" prop="varianceAmount">
          <template slot-scope="scope">
            {{ formatAmount(scope.row.varianceAmount) }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStocktakesCount,getCountInfo } from "@/api/inventory/stocktakes"
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: "stocktakeCountTable",
  components: { CommonDictSelect,WarehouseSelector,LocationSelector }, // 注册通用字典组件
  props: {
    // 接收父组件传递的子表原始数据（双向绑定）
    itemsList: {
      type: Array,
      default: () => []
    },
    isConfirm: { // true=盘点确认（全部只读+显示所有字段），false=盘点（部分可编辑+隐藏部分字段）
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      viewOpen:false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        stocktakeStatus: null,
        plannedDates: null,
        materialId: "",
        locationId: ""
      },
      // 详情列表信息
      detailList: [],
      // 库存盘点表格数据
      stocktakesList: [],
      // 日期范围
      dateRange: [],
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      currentWarehouseId: "", // 存仓库原始ID（0eb22b11...），供库位联动
      checkedRows: [], // 子表选中的行
      materialDict: [],  // 物料字典数组（存储sap_no和name）
      warehouseDict: [], // 仓库数组
      locationDict: [], // 库位数组
      // 分页总数
      total: 0,
      // 表格加载状态
      tableLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 挂载全局字典工具方法（模板中可直接调用）
    getDictLabel,
    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },
// 取消按钮
    cancel() {
      this.viewOpen = false
      this.detailList = []
    },
    // 详情按钮：打开弹窗
    handleCountViewInfo(row) {
      this.detailList = []; // 清空旧数据
      // 接口请求添加try/catch和空值判断
      getCountInfo(row).then(response => {
        if (response && response.rows) {
          this.detailList = response.rows; // 直接赋值数组给detailList
          console.log('赋值后的detailList：', this.detailList); // 打印3
        } else {
        }
        this.viewOpen = true;
      }).catch(error => {
        console.error('获取详情失败：', error);
        this.$message.error('获取详情失败，请重试');
        this.viewOpen = false;
      })
    },
    // 仓库清空时触发
    handleWarehouseClear() {
      this.queryParams.locationId = ''
      this.queryParams.warehouseId = ''
      this.currentWarehouseId = ''
      this.handleQuery()
    },
    /** 库位选择回调 */
    handleLocationSelected(location) {
      if (!location) return
      this.queryParams.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.queryParams.warehouseId = warehouse.warehousesCode
      this.queryParams.warehousesCode = warehouse.warehousesCode
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // 仓库选择后，清空库位信息
      this.queryLocationName = null
      this.queryParams.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.queryParams.pageNum = 1 // 搜索后重置页码
      this.$nextTick(() => {
        this.getList();
      });
    },
    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.queryParams.warehouseId = null
      this.queryParams.warehousesCode = null
      this.currentWarehouseId = ""
      // 清空仓库时，同时清空库位
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 打开库位选择器 */
    openLocationSelector() {
      // console.log('this.currentWarehouseId========',this.currentWarehouseId)
      if (!this.currentWarehouseId) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.locationSelectorVisible = true
    },
    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    // 重置
    resetQuery() {
      this.queryWarehouseName = null
      this.queryLocationName = null
      this.currentWarehouseId = ''
      this.dateRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        materialId: "",
        batchCode: "",
        warehouseId: "",
        locationId: ""
      };
      // 重置库位选择器
      this.handleWarehouseClear()

    },
    // 关联查询列表
    getList() {
      this.loading = true
      listStocktakesCount(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.stocktakesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 字典加载完成回调（缓存字典数据，供表格展示使用）
    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;
    }
  }
}
</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; /* ElementUI disabled 背景色 */
  border: 1px solid #e5e6eb !important; /* ElementUI disabled 边框色 */
  color: #909399 !important; /* ElementUI disabled 文字色 */
  cursor: not-allowed !important;
  border-radius: 4px !important; /* 和输入框圆角一致 */
}
</style>
