<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:inbound:export']"
        >导出</el-button>
      </template>
    </PageTitle>

    <!-- 搜索区域 -->
    <div class="page-container">
      <page-wrapper-search
        :model="queryParams"
        ref="queryForm"
        size="small"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="物料SAPNO" prop="sapNo">
          <el-input
            v-model="queryParams.sapNo"
            placeholder="请输入物料SAPNO"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          height="100%"
          :data="inboundList"
          @selection-change="handleSelectionChange"
          border
          :row-key="(row) => row.materialId"
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column label="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
          <el-table-column label="SAP物料号" align="center" prop="sapNo" width="120" />
          <el-table-column label="TS Code" align="center" prop="tsCode" width="120" />
          <el-table-column label="危险类别" align="center" prop="hazardId" width="120">
            <template slot-scope="scope">
              <el-tag
                :type="getDictTagType('danger_type', scope.row.hazardId)"
                size="small"
              >
                {{ getDictLabel('danger_type', scope.row.hazardId) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" align="center" prop="specification" width="120" />
          <el-table-column label="计量单位" align="center" prop="materialUnit" width="120" />
          <el-table-column label="单位重量" align="center" prop="unitWeight" width="120" >
            <template slot-scope="scope">
              {{ formatNumber(scope.row.unitWeight) }}
            </template>
          </el-table-column>
          <el-table-column label="计划数量" align="center" prop="plannedQuantity" width="100" />
          <el-table-column label="实际数量" align="center" prop="actualQuantity" width="100" />
          <el-table-column label="总额" align="center" prop="totalPrice" width="100" >
            <template slot-scope="scope">
              {{ formatNumber(scope.row.totalPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleViewDetail(scope.row)"
              >详细</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 详情弹窗 -->
      <el-dialog
        title="出库物料详情"
        v-model="detailDialogVisible"
        :visible.sync="detailDialogVisible"
        width="1400px"
        append-to-body
        :close-on-click-modal="false"
      > 
        <el-form 
          :model="detailQueryParams" 
          ref="detailQueryForm" 
          size="small" 
          inline 
          label-width="100px" 
          class="detail-search-form"
        >
          <el-form-item label="入库日期" prop="inboundDateRange">
            <el-date-picker
              v-model="detailDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              clearable
            />
          </el-form-item>
          <el-form-item label="关联入库单号" prop="orderId">
            <el-input
              v-model="detailQueryParams.orderId"
              placeholder="请输入入库单号"
              clearable
            />
          </el-form-item>
          <el-form-item label="批次" prop="batchId">
            <el-input
              v-model="detailQueryParams.batchId"
              placeholder="请输入批次"
              clearable
            />
          </el-form-item>
          <el-form-item label="仓库" prop="warehouseId">
            <el-input
              v-model="detailWarehouseName"
              placeholder="请选择仓库"
              readonly
              @focus="openDetailWarehouseSelector"
              :suffix-icon="''"
            >
              <template v-if="detailWarehouseName" #suffix>
                <i
                  class="el-icon-circle-close el-input__icon"
                  style="cursor: pointer;"
                  @click.stop="clearDetailWarehouse"
                ></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="库位" prop="locationId">
            <el-input
              v-model="detailLocationName"
              placeholder="请选择库位"
              readonly
              @focus="openDetailLocationSelector"
              :suffix-icon="''"
            >
              <template v-if="detailLocationName" #suffix>
                <i
                  class="el-icon-circle-close el-input__icon"
                  style="cursor: pointer;"
                  @click.stop="clearDetailLocation"
                ></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDetailQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetDetailQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <div class="detail-table-container">
          <el-table
            v-loading="detailLoading"
            :data="detailList"
            border
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
            <el-table-column label="关联入库单号" align="center" prop="orderId" width="180" />
            <el-table-column label="批次" align="center" prop="batchId" width="120" />
            <el-table-column label="仓库" align="center" prop="warehousesName" width="120" />
            <el-table-column label="库位" align="center" prop="locationName" width="120" />
            <el-table-column label="计划数量" align="center" prop="plannedQuantity" width="100" />
            <el-table-column label="实际数量" align="center" prop="actualQuantity" width="100" />
            <el-table-column label="入库日期" align="center" prop="inboundDate" width="120">
              <template slot-scope="scope">
                {{ parseTime(scope.row.inboundDate, '{y}-{m}-{d}') }}
              </template>
            </el-table-column>
            <el-table-column label="单价" align="center" prop="unitPrice" width="100">
              <template slot-scope="scope">
                {{ formatNumber(scope.row.unitPrice) }}
              </template>
            </el-table-column>
            <el-table-column label="金额" align="center" prop="totalPrice" width="120">
              <template slot-scope="scope">
                {{ formatNumber((scope.row.actualQuantity || 0) * (scope.row.unitPrice || 0)) }}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip />
          </el-table>
        </div>
        
        <pagination
          v-show="detailTotal > 0"
          :total="detailTotal"
          :page.sync="detailQueryParams.pageNum"
          :limit.sync="detailQueryParams.pageSize"
          @pagination="getDetailList"
          class="detail-pagination"
        />
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关 闭</el-button>
        </div>
      </el-dialog>

      <!-- 分页组件 -->
      <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"
        @selected="handleLocationSelected"
      />
      <WarehouseSelector
        v-model="detailWarehouseSelectorVisible"
        @selected="handleDetailWarehouseSelected"
      />
      <LocationSelector
        v-model="detailLocationSelectorVisible"
        @selected="handleDetailLocationSelected"
      />
    </div>
  </div>
</template>

<script>
import { inbound_details, details_information } from "@/api/inventory/inbound_items"
import PageTitle from "@/components/PageTitle"
import PageWrapperSearch from "@/components/Search/PageWrapperSearch"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "InboundDetails",
  dicts: ['label_color', 'danger_type'],
  components: {
    PageTitle,
    PageWrapperSearch,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 主页面状态
      loading: true,
      total: 0,
      inboundList: [],
      warehouseSelectorVisible: false,
      locationSelectorVisible: false,
      queryWarehouseName: '',
      queryLocationName: '',
      
      // 详情弹窗状态
      detailDialogVisible: false,
      detailLoading: true,
      detailTotal: 0,
      detailList: [],
      detailWarehouseSelectorVisible: false,
      detailLocationSelectorVisible: false,
      detailWarehouseName: '',
      detailLocationName: '',
      detailDateRange: null, // 独立的详情日期范围，避免和主页面冲突
      
      // 查询参数（规范化命名 + 初始值统一）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sapNo: '',
        materialName: '',
        warehouseId: '',
        locationId: '',
        labelColor: '',
        inboundDateStart: '',
        inboundDateEnd: ''
      },
      detailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        materialId: '',
        orderId: '',
        batchId: '',
        warehouseId: '',
        locationId: '',
        inboundDateStart: '',
        inboundDateEnd: ''
      },

      // 多选相关（仅声明必要变量）
      ids: [],
      single: true,
      multiple: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 获取字典标签（通用方法）
     * @param {string} dictType 字典类型
     * @param {*} value 字典值
     * @returns {string} 字典标签
     */
    getDictLabel(dictType, value) {
      if (!value || !this.dict?.type?.[dictType]) return '-';
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.label || '-';
    },

    /**
     * 获取字典标签样式（语义化命名）
     * @param {string} dictType 字典类型
     * @param {*} value 字典值
     * @returns {string} 样式类名
     */
    getDictTagType(dictType, value) {
      if (!value || !this.dict?.type?.[dictType]) return '';
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.raw?.listClass || '';
    },

    /**
     * 数字格式化（通用方法，替代原formatAmount）
     * @param {number} num 待格式化数字
     * @returns {string} 保留两位小数的字符串
     */
    formatNumber(num) {
      const number = Number(num);
      return isNaN(number) ? '0.00' : number.toFixed(2);
    },

    /**
     * 查询主列表数据
     */
    async getList() {
      try {
        this.loading = true;
        const response = await inbound_details(this.queryParams);
        this.inboundList = response.rows || [];
        this.total = response.total || 0;
      } catch (error) {
        this.$message.error('查询入库列表失败：' + error.message);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 主页面搜索
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 处理日期范围（原代码错误绑定到全局inboundDateRange，已修正）
      if (Array.isArray(this.detailDateRange) && this.detailDateRange.length === 2) {
        this.queryParams.inboundDateStart = this.detailDateRange[0];
        this.queryParams.inboundDateEnd = this.detailDateRange[1];
      } else {
        this.queryParams.inboundDateStart = '';
        this.queryParams.inboundDateEnd = '';
      }
      this.getList();
    },

    /**
     * 重置主页面查询条件
     */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sapNo: '',
        materialName: '',
        warehouseId: '',
        locationId: '',
        labelColor: '',
        inboundDateStart: '',
        inboundDateEnd: ''
      };
      this.queryWarehouseName = '';
      this.queryLocationName = '';
      this.detailDateRange = null;
      this.getList();
    },

    /**
     * 打开详情弹窗
     * @param {object} row 选中的行数据
     */
    handleViewDetail(row) {
      this.detailDialogVisible = true;
      // 初始化详情查询参数
      this.detailQueryParams = {
        pageNum: 1,
        materialId: row.materialId,
        orderId: '',
        batchId: '',
        warehouseId: this.queryParams.warehouseId, // 继承主页面仓库筛选
        locationId: this.queryParams.locationId, // 继承主页面库位筛选
        inboundDateStart: '',
        inboundDateEnd: ''
      };
      this.detailWarehouseName = this.queryWarehouseName;
      this.detailLocationName = this.queryLocationName;
      this.detailDateRange = null;
      this.getDetailList();
    },

    /**
     * 查询详情列表数据
     */
    async getDetailList() {
      try {
        this.detailLoading = true;
        // 处理详情日期范围
        if (Array.isArray(this.detailDateRange) && this.detailDateRange.length === 2) {
          this.detailQueryParams.inboundDateStart = this.detailDateRange[0];
          this.detailQueryParams.inboundDateEnd = this.detailDateRange[1];
        }
        const response = await details_information(this.detailQueryParams);
        this.detailList = response.rows || [];
        this.detailTotal = response.total || 0;
      } catch (error) {
        this.$message.error('查询物料详情失败：' + error.message);
      } finally {
        this.detailLoading = false;
      }
    },

    /**
     * 详情弹窗搜索
     */
    handleDetailQuery() {
      this.detailQueryParams.pageNum = 1;
      this.getDetailList();
    },

    /**
     * 重置详情弹窗查询条件
     */
    resetDetailQuery() {
      const materialId = this.detailQueryParams.materialId; // 保留物料ID
      this.detailQueryParams = {
        pageNum: 1,
        pageSize: 10,
        materialId,
        orderId: '',
        batchId: '',
        warehouseId: '',
        locationId: '',
        inboundDateStart: '',
        inboundDateEnd: ''
      };
      this.detailDateRange = null;
      this.detailWarehouseName = '';
      this.detailLocationName = '';
      this.getDetailList();
    },

    /**
     * 多选框选中事件
     * @param {array} selection 选中的行
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // ========== 仓库/库位选择器相关方法（通用封装） ==========
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true;
    },

    handleWarehouseSelected(warehouse) {
      if (!warehouse) return;
      this.queryParams.warehouseId = warehouse.warehouseId;
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode;
      this.handleQuery();
    },

    clearQueryWarehouse() {
      this.queryWarehouseName = '';
      this.queryParams.warehouseId = '';
      this.handleQuery();
    },

    openLocationSelector() {
      this.locationSelectorVisible = true;
    },

    handleLocationSelected(location) {
      if (!location) return;
      this.queryParams.locationId = location.locationId || location.id;
      this.queryLocationName = location.locationName || location.locationCode;
      this.handleQuery();
    },

    clearQueryLocation() {
      this.queryLocationName = '';
      this.queryParams.locationId = '';
      this.handleQuery();
    },

    openDetailWarehouseSelector() {
      this.detailWarehouseSelectorVisible = true;
    },

    handleDetailWarehouseSelected(warehouse) {
      if (!warehouse) return;
      this.detailQueryParams.warehouseId = warehouse.warehouseId;
      this.detailWarehouseName = warehouse.warehousesName || warehouse.warehousesCode;
      this.detailLocationName = '';
      this.detailQueryParams.locationId = '';
    },

    clearDetailWarehouse() {
      this.detailWarehouseName = '';
      this.detailQueryParams.warehouseId = '';
      this.detailLocationName = '';
      this.detailQueryParams.locationId = '';
    },

    openDetailLocationSelector() {
      this.detailLocationSelectorVisible = true;
    },

    handleDetailLocationSelected(location) {
      if (!location) return;
      this.detailQueryParams.locationId = location.locationId || location.id;
      this.detailLocationName = location.locationName || location.locationCode;
    },

    clearDetailLocation() {
      this.detailLocationName = '';
      this.detailQueryParams.locationId = '';
    },

    /**
     * 导出数据
     */
    handleExport() {
      this.download(
        '/inventory/inbound_items/exportDetails',
        { ...this.queryParams },
        `inbound_details_${new Date().getTime()}.xlsx`
      );
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-container {
  margin-top: 16px;
}

/* 详情弹窗样式优化 */
.detail-search-form {
  margin-bottom: 16px;
}

.detail-table-container {
  max-height: 600px;
  overflow: auto;
  margin-bottom: 16px;
}

.detail-pagination {
  margin-top: 10px;
  text-align: right;
}

/* 修复弹窗内分页样式 */
:deep(.el-pagination) {
  margin-top: 10px;
}
</style>