<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="id"
            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, 'id', '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="仓库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" />
          <el-table-column label="差异总金额" prop="unitPrice">
            <template slot-scope="scope">
              {{ formatAmount(scope.row.countAmount) }}
            </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>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 仓库选择组件 -->
      <WarehouseSelector
        v-model="warehouseSelectorVisible"
        @selected="handleWarehouseSelected"
      />
      <!-- 库位选择组件 -->
      <LocationSelector
        v-model="locationSelectorVisible"
        :warehousesId="queryParams.warehouseId"
        @selected="handleLocationSelected"
      />
    </div>
    <!-- 详情查看 -->
    <el-dialog title="统计详情查看" :visible.sync="viewOpen" width="1500px" append-to-body>
      <el-table :data="detailList" border stripe size="small" style="width: 100%;">
        <el-table-column label="计划日期" align="center" prop="plannedDates" width="100px" />
        <el-table-column label="物料" align="center" prop="materialId" width="150px" fixed>
          <template slot-scope="scope">
            {{ getDictLabel(materialDict, scope.row.materialId, 'id', 'material_name') || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="SAP物料号" align="center" prop="sapNo" width="150px" />
        <el-table-column label="仓库" align="center" prop="warehousesName" width="150px" />
        <el-table-column label="库位" align="center" prop="locationName" width="150px" />
        <el-table-column label="危险类别" align="center" prop="hazardName" width="100px" />
        <el-table-column label="差异数量" align="center" prop="varianceQuantity" width="150px" />
        <el-table-column label="差异金额" align="center" prop="varianceAmount" width="150px" >
          <template slot-scope="scope">
            {{ formatAmount(scope.row.varianceAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="adjustedType" align="center" label="调整原因类型" width="150px">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.adjusted_type" :value="scope.row.adjustedType"/>
          </template>
        </el-table-column>
        <el-table-column label="调整原因" align="center" prop="adjustmentReason" width="210px" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
      <pagination
        v-show="totalDail>0"
        :total="totalDail"
        :page.sync="searchParams.pageNum"
        :limit.sync="searchParams.pageSize"
        @pagination="loadDetail"
      />
    </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",
  dicts: ['adjusted_type'],
  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: ""
      },
      searchParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 详情列表信息
      detailList: [],
      // 库存盘点表格数据
      stocktakesList: [],
      // 日期范围
      dateRange: [],
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      checkedRows: [], // 子表选中的行
      materialDict: [],  // 物料字典数组（存储sap_no和name）
      // 分页总数
      total: 0,
      currentRow: null,
      totalDail: 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 挂载全局字典工具方法（模板中可直接调用）
    getDictLabel,

// 取消按钮
    cancel() {
      this.viewOpen = false
      this.detailList = []
    },

    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      this.queryParams.warehouseId = warehouse.warehouseId
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehouseId
      // 仓库选择后，清空库位信息
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },

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


    /** 格式化金额，保留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.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 打开库位选择器 */
    openLocationSelector() {
      if (!this.queryParams.warehouseId) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.locationSelectorVisible = true
    },
    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },
    // 仓库清空时触发
    handleWarehouseClear() {
      this.queryParams.locationId = ''
      this.queryParams.warehouseId = ''
      this.currentWarehouseId = ''
      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
      })
    },
    // 详情按钮：打开弹窗
    handleCountViewInfo(row) {
      this.detailList = []; // 清空旧数据
      this.currentRow = row;
      console.log(row)
      this.searchParams.pageNum = 1; // 每次查看新行，从第1页开始
      this.loadDetail(); // 加载数据
    },
    // 加载详情数据（同时支持首次查看和分页）
    loadDetail() {
      // 合并参数：当前行数据 + 分页参数
      const params = {
        ...this.currentRow, // 携带当前行的筛选条件（如 id、日期等）
        ...this.searchParams // 携带分页参数（pageNum、pageSize）
      };
      console.log('最终传给详情接口的参数：', params);
      getCountInfo(params).then(response => {
        this.detailList = response.rows;
        this.totalDail = response.total;
        this.viewOpen = true;
      }).catch(error => {
        console.error('加载失败：', error);
      });
    },
    // 字典加载完成回调（缓存字典数据，供表格展示使用）
    handleDictLoaded(type, data) {
      if (type === 'material') {
        this.materialDict = data
      }
    },
    // 给子表设置序号
    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>
