<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:inbound:add']"
        >新增</el-button>

        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:inbound:edit']"
        >修改</el-button>

        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:inbound:remove']"
        >删除</el-button>

        <el-button
          type="success"
          plain
          icon="el-icon-upload"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:inbound:import']"
        >导入</el-button>

        <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="入库日期" prop="inboundDateRange">
          <el-date-picker
            v-model="inboundDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入库单号" prop="orderId">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入入库单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="系统编号" prop="systemNo">
          <el-input
            v-model="queryParams.systemNo"
            placeholder="请输入系统编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="批次号" prop="batchId">
          <el-input
            v-model="queryParams.batchId"
            placeholder="请输入批次号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入库类型" prop="orderTypeId">
          <el-select v-model="queryParams.orderTypeId" placeholder="请选择入库类型" clearable>
            <el-option
              v-for="dict in dict.type.inbound_outbound_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货主" prop="ownerId">
          <el-input
            v-model="queryOwnerName"
            placeholder="请选择货主"
            readonly
            @focus="openOwnerSelector('query')"
            @click="openOwnerSelector('query')"
            :suffix-icon="''"
          >
            <template v-if="queryOwnerName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearQueryOwner"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="入库单状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择入库单状态" clearable>
            <el-option
              v-for="dict in dict.type.inbound_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable>
            <el-option
              v-for="dict in dict.type.order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </page-wrapper-search>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          height="100%"
          :data="inboundList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column label="入库单号" align="center" prop="orderId" min-width="200"/>
          <el-table-column label="批次号" align="center" prop="batchId" min-width="200"/>
          <el-table-column label="系统编号" align="center" prop="systemNo" min-width="200"/>
          <el-table-column label="货主" align="center" prop="ownerName" min-width="200"/>
          <el-table-column label="入库类型" align="center" prop="orderTypeId" show-overflow-tooltip min-width="200">
            <template slot-scope="scope">
              <el-tag
                :type="getDictTagClass('inbound_outbound_type', scope.row.orderTypeId)"
                size="small"
              >
                {{ getDictLabel('inbound_outbound_type', scope.row.orderTypeId) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="订单类型" align="center" prop="orderType" show-overflow-tooltip min-width="200">
            <template slot-scope="scope">
              <el-tag
                :type="getDictTagClass('order_type', scope.row.orderType)"
                size="small"
              >
                {{ getDictLabel('order_type', scope.row.orderType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库单状态" align="center" prop="orderStatus" min-width="200">
            <template slot-scope="scope">
              <el-tag 
                :type="getDictTagClass('inbound_status', scope.row.orderStatus + '')" 
                size="small"
              >
                {{ getDictLabel('inbound_status', scope.row.orderStatus + "") }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库时间" align="center" prop="inboundDate" min-width="200">
            <template slot-scope="scope">
              {{ parseTime(scope.row.inboundDate, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="250"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-success"
                @click="handleConfirm(scope.row)"
                v-hasPermi="['inventory:inbound:confirm']"
                v-if="scope.row.orderStatus !== 2"
              >确认入库</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-more"
                @click="handleDetail(scope.row)"
                v-hasPermi="['inventory:inbound:view']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['inventory:inbound:edit']"
                v-if="scope.row.orderStatus !== 2"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['inventory:inbound:remove']"
                v-if="scope.row.orderStatus !== 2"
              >删除</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"
      />
    </div>

    <!-- 添加/修改入库对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open"
      :visible.sync="open"
      width="1200px" 
      append-to-body
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-divider content-position="center">入库单基础信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入入库单号" />
            </el-form-item>
            <el-form-item label="批次号" prop="batchId">
              <el-input v-model="form.batchId" placeholder="请输入批次号" />
            </el-form-item>
            <el-form-item label="入库类型" prop="orderTypeId">
              <el-select v-model="form.orderTypeId" placeholder="请选择入库类型" clearable>
                <el-option
                  v-for="dict in dict.type.inbound_outbound_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="入库日期" prop="inboundDate">
              <el-date-picker
                clearable
                v-model="form.inboundDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择入库日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统编号" prop="systemNo">
              <el-input v-model="form.systemNo" placeholder="请输入系统编号" />
            </el-form-item>
            <el-form-item label="货主" prop="ownerId">
              <el-input
                v-model="form.ownerName"
                placeholder="请选择货主"
                readonly
                @focus="openOwnerSelector('form')"
                @click="openOwnerSelector('form')"
                :suffix-icon="''"
              >
                <template v-if="form.ownerName" #suffix>
                  <i
                    class="el-icon-circle-close el-input__icon"
                    style="cursor: pointer;"
                    @click.stop="clearFormOwner"
                  ></i>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="form.orderType" placeholder="请选择订单类型" clearable>
                <el-option
                  v-for="dict in dict.type.order_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-divider content-position="center">入库单明细信息</el-divider>
        <InboundItems
          ref="inboundItemsRef"
          v-model="form.inboundOrderItemsList"
          :embedded="true"
          :inboundOrderId="inboundOrderId"
          :show-search-form="false"
          :show-pagination="false"
          :show-toolbar="true"
          :show-action-column="true"
          :show-selection="true"
          :show-add-button="true"
          :show-edit-button="true"
          :show-delete-button="true"
          @selection-change="handleItemsSelectionChange"
          @data-change="handleItemsDataChange"
          @totals-change="handleTotalsChange"
          @item-added="handleItemAdded"
          @row-saved="handleRowSaved"
          @row-deleted="handleRowDeleted"
          @batch-delete="handleBatchDelete"
          @cell-change="handleCellChange"
          @show-materials="showMaterials"
          @open-warehouse-selector="openWarehouseSelector"
          @open-location-selector="openLocationSelector"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 入库单详情弹窗 -->
    <el-dialog
      title="入库单详细信息"
      v-model="detailOpen"
      :visible.sync="detailOpen"
      width="1200px"
      append-to-body
      class="scrollable-dialog"
    >
      <div class="detail-container">
        <el-descriptions :column="2" class="mb20" border>
          <el-descriptions-item label="入库单号">{{ detailForm.orderId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="系统编号">{{ detailForm.systemNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="批次号">{{ detailForm.batchId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="货主">{{ detailForm.ownerName || detailForm.ownerId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="入库类型">
            {{ getDictLabel('inbound_outbound_type', detailForm.orderTypeId) }}
          </el-descriptions-item>
          <el-descriptions-item label="订单类型">
            {{ getDictLabel('order_type', detailForm.orderType) }}
          </el-descriptions-item>
          <el-descriptions-item label="入库日期">{{ detailForm.inboundDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            <div class="remark-text">{{ detailForm.remark || '-' }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="center">入库单明细信息</el-divider>
        <InboundItems
          ref="detailItemsRef"
          v-model="detailForm.inboundOrderItemsList"
          :embedded="true"
          :inboundOrderId="detailForm.inboundOrderId"
          :isEditable="false"
          :show-search-form="false"
          :show-pagination="false"
          :show-toolbar="false"
          :show-action-column="false"
          :show-selection="false"
          :show-add-button="false"
          :show-edit-button="false"
          :show-delete-button="false"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 物料选择弹窗 -->
    <el-dialog 
      title="选择物料" 
      v-model="materialSelectOpen" 
      :visible.sync="materialSelectOpen"
      width="1200px" 
      append-to-body
      destroy-on-close
    >
      <MaterialSelector
        v-model="selectedMaterialIds"
        :multiple="true"
        @change="handleMaterialChange"
        ref="materialSelector"
      />
      <div slot="footer">
        <el-button type="primary" @click="confirmMaterialSelect">确定</el-button>
        <el-button @click="materialSelectOpen = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <import-excel
      ref="importRef"
      title="导入"
      import-url="/inventory/inbound/import"
      template-url="/inventory/inbound/importTemplate"
      :template-name="getTemplateName()"
      @success="getList"
      :show-trdc-checkbox="true"
      @orderTypeChange="handleOrderTypeChange"
      :orderTypeRequired="true"
    />

    <!-- 选择器组件 -->
    <OwnerSelector
      v-model="ownerSelectorVisible"
      @selected="handleOwnerSelected"
    />
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
    <LocationSelector
      v-model="locationSelectorVisible"
      @selected="handleLocationSelected"
    />
  </div>
</template>

<script>
import { 
  listInbound, 
  getInbound, 
  delInbound, 
  addInbound, 
  updateInbound 
} from "@/api/inventory/inbound"
import { listInbound_itemsAndMname } from "@/api/inventory/inbound_items"
import { batchAddInventory } from "@/api/inventory/inventory"
import InboundItems from "@/views/inventory/inbound_items/index.vue"
import PageTitle from "@/components/PageTitle"
import PageWrapperSearch from "@/components/Search/PageWrapperSearch"
import MaterialSelector from "@/views/inventory/materials/materialsSeletor.vue"
import ImportExcel from "@/components/ImportExcel/index"
import OwnerSelector from "@/views/compononents/OwnerSelector.vue"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "Inbound",
  dicts: ['inbound_outbound_type', 'order_type', 'inbound_status'],
  components: {
    InboundItems,
    PageTitle,
    PageWrapperSearch,
    MaterialSelector,
    ImportExcel,
    OwnerSelector,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 日期范围
      inboundDateRange: null,
      // 货主选择
      queryOwnerName: '',
      ownerSelectorVisible: false,
      ownerSelectTarget: 'form',
      // 仓库/库位选择
      warehouseSelectorVisible: false,
      locationSelectorVisible: false,
      currentEditRow: null,
      // 物料选择
      materialSelectOpen: false,
      selectedMaterialIds: [],
      selectedMaterials: [],
      // 详情弹窗
      detailOpen: false,
      detailForm: {},
      // 基础状态
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      inboundList: [],
      // 编辑弹窗
      title: "",
      open: false,
      inboundOrderId: null,
      // 查询参数（规范化初始值）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: '',
        orderTypeId: '',
        systemNo: '',
        batchId: '',
        warehouseId: '',
        ownerId: '',
        ownerName: '',
        ownerCode: '',
        orderStatus: '',
        orderType: '',
        inboundDateStart: '',
        inboundDateEnd: ''
      },
      // 表单参数（规范化初始值 + 合理默认）
      form: {
        id: '',
        orderId: '',
        orderTypeId: '',
        batchId: '',
        warehouseId: '',
        warehousesName: '',
        ownerId: '',
        ownerName: '',
        ownerCode: '',
        orderStatus: 1,
        referenceNo: '',
        plannedArrivalDate: '',
        actualArrivalDate: '',
        inboundDate: this.formatDate(new Date()),
        totalPlannedQuantity: 0,
        totalActualQuantity: 0,
        totalPackages: 0,
        remark: '',
        opUserName: '',
        isUsed: '',
        sortNo: '',
        createTime: '',
        createUserCode: '',
        updateTime: '',
        updateUserCode: '',
        inboundOrderItemsList: []
      },
      // 表单校验规则
      rules: {
        orderId: [{ required: true, message: "入库单号不能为空", trigger: "blur" }],
        orderTypeId: [{ required: true, message: "入库类型不能为空", trigger: "blur" }],
        systemNo: [{ required: true, message: "系统编号不能为空", trigger: "blur" }],
        batchId: [{ required: true, message: "批次号不能为空", trigger: "blur" }],
        ownerId: [{ required: true, message: "货主不能为空", trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 日期格式化（补零处理）
     * @param {Date} date 日期对象
     * @returns {string} 格式化后的日期字符串
     */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    /**
     * 查询入库列表（异步优化 + 错误捕获）
     */
    async getList() {
      try {
        this.loading = true;
        const res = await listInbound(this.queryParams);
        this.inboundList = res.rows || [];
        this.total = res.total || 0;
      } catch (error) {
        this.$message.error('查询入库列表失败：' + (error.message || '网络异常'));
        console.error('入库列表查询失败：', error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取字典标签（通用方法）
     * @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} 样式类名
     */
    getDictTagClass(dictType, value) {
      if (!value || !this.dict?.type?.[dictType]) return '';
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.raw?.listClass || '';
    },

    /**
     * 搜索按钮操作（日期范围处理优化）
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 处理日期范围
      if (Array.isArray(this.inboundDateRange) && this.inboundDateRange.length === 2) {
        this.queryParams.inboundDateStart = this.inboundDateRange[0];
        this.queryParams.inboundDateEnd = this.inboundDateRange[1];
      } else {
        this.queryParams.inboundDateStart = '';
        this.queryParams.inboundDateEnd = '';
      }
      this.getList();
    },

    /**
     * 重置查询条件（精简逻辑 + 响应式优化）
     */
    resetQuery() {
      this.queryOwnerName = '';
      this.inboundDateRange = null;
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderId: '',
        orderTypeId: '',
        systemNo: '',
        batchId: '',
        warehouseId: '',
        ownerId: '',
        ownerName: '',
        ownerCode: '',
        orderStatus: '',
        orderType: '',
        inboundDateStart: '',
        inboundDateEnd: ''
      };
      this.$nextTick(() => this.getList());
    },

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

    /**
     * 新增入库单
     */
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加入库";
    },

    /**
     * 修改入库单
     * @param {Object} row 选中行数据
     */
    async handleUpdate(row) {
      try {
        this.resetForm();
        const id = row?.id || this.ids[0];
        if (!id) return this.$message.warning('请选择要修改的入库单');

        const res = await getInbound(id);
        const data = res.data || {};
        
        // 禁用已提交的入库单修改
        if (data.orderStatus === 2) {
          return this.$modal.msgWarning("该入库单已提交，不能修改");
        }

        // 表单赋值 + 回显优化
        this.form = {
          ...data,
          ownerName: data.ownerName || data.ownerCode || data.ownerId,
          inboundOrderItemsList: (data.inboundOrderItemsList || []).map(item => ({
            ...item,
            warehousesName: item.warehousesName || item.warehouseId || '-',
            locationName: item.locationName || item.locationCode || item.locationId || '-',
            locationCode: item.locationCode || item.locationId || '-',
            orderTypeId: item.orderTypeId || 1
          }))
        };

        this.inboundOrderId = id;
        this.$nextTick(() => {
          this.$refs.inboundItemsRef?.handlePagination();
          this.$refs.inboundItemsRef?.calculateTotals();
        });
        this.open = true;
        this.title = "修改入库单";
      } catch (error) {
        this.$message.error('获取入库单详情失败：' + (error.message || '网络异常'));
        console.error('修改入库单失败：', error);
      }
    },

    /**
     * 查看入库单详情
     * @param {Object} row 选中行数据
     */
    async handleDetail(row) {
      try {
        const id = row?.id;
        if (!id) return this.$message.warning('请选择要查看的入库单');

        const res = await getInbound(id);
        this.detailForm = {
          ...res.data,
          ownerName: res.data.ownerName || res.data.ownerCode || res.data.ownerId,
          inboundOrderItemsList: (res.data.inboundOrderItemsList || []).map(item => ({
            ...item,
            orderTypeId: res.data.orderTypeId
          })),
          inboundOrderId: id
        };
        this.detailOpen = true;
      } catch (error) {
        this.$message.error('获取入库单详情失败：' + (error.message || '网络异常'));
        console.error('查看入库单详情失败：', error);
      }
    },

    /**
     * 打开货主选择器
     * @param {string} target 目标场景：query/form
     */
    openOwnerSelector(target = 'form') {
      this.ownerSelectTarget = target;
      this.ownerSelectorVisible = true;
    },

    /**
     * 货主选择回调
     * @param {Object} owner 选中的货主
     */
    handleOwnerSelected(owner) {
      if (!owner) return;
      
      if (this.ownerSelectTarget === 'query') {
        // 搜索页货主选择
        this.queryParams.ownerId = owner.ownerId;
        this.queryParams.ownerCode = owner.ownerCode;
        this.queryOwnerName = owner.ownerName || owner.ownerCode;
        this.getList();
      } else {
        // 表单页货主选择
        this.form.ownerId = owner.ownerId;
        this.form.ownerCode = owner.ownerCode;
        this.form.ownerName = owner.ownerName;
      }
      this.ownerSelectorVisible = false;
    },

    /**
     * 清空搜索页货主
     */
    clearQueryOwner() {
      this.queryOwnerName = '';
      this.queryParams.ownerId = '';
      this.queryParams.ownerCode = '';
      this.getList();
    },

    /**
     * 清空表单页货主
     */
    clearFormOwner() {
      this.form.ownerId = '';
      this.form.ownerCode = '';
      this.form.ownerName = '';
      this.$refs.formRef?.clearValidate('ownerId');
    },

    /**
     * 打开仓库选择器
     * @param {Object} row 编辑行
     */
    openWarehouseSelector(row) {
      this.currentEditRow = row;
      this.warehouseSelectorVisible = true;
    },

    /**
     * 仓库选择回调
     * @param {Object} warehouse 选中的仓库
     */
    handleWarehouseSelected(warehouse) {
      if (!warehouse || !this.currentEditRow) return;
      
      this.$set(this.currentEditRow, 'warehouseId', warehouse.warehouseId);
      this.$set(this.currentEditRow, 'warehousesName', warehouse.warehousesName);
      
      this.$refs.inboundItemsRef?.syncDataToParent();
      this.$refs.inboundItemsRef?.calculateTotals();
      this.warehouseSelectorVisible = false;
    },

    /**
     * 打开库位选择器
     * @param {Object} row 编辑行
     */
    openLocationSelector(row) {
      this.currentEditRow = row;
      this.locationSelectorVisible = true;
    },

    /**
     * 库位选择回调
     * @param {Object} location 选中的库位
     */
    handleLocationSelected(location) {
      if (!location || !this.currentEditRow) return;
      
      this.$set(this.currentEditRow, 'locationId', location.locationId);
      this.$set(this.currentEditRow, 'locationCode', location.locationCode);
      this.$set(this.currentEditRow, 'locationName', location.locationName);
      
      this.$refs.inboundItemsRef?.syncDataToParent();
      this.$refs.inboundItemsRef?.calculateTotals();
      this.locationSelectorVisible = false;
    },

    /**
     * 打开物料选择弹窗
     * @param {boolean} status 是否显示
     */
    showMaterials(status) {
      this.materialSelectOpen = status;
      if (status) {
        this.selectedMaterialIds = [];
        this.selectedMaterials = [];
        this.$nextTick(() => this.$refs.materialSelector?.clearSelection());
      }
    },

    /**
     * 物料选择变化回调
     * @param {Array} selectedRows 选中的物料行
     */
    handleMaterialChange(selectedRows) {
      this.selectedMaterials = selectedRows || [];
    },

    /**
     * 确认选择物料并添加到明细
     */
    confirmMaterialSelect() {
      if (this.selectedMaterials.length === 0) {
        return this.$message.warning("请选择物料");
      }

      // 过滤重复物料
      const newMaterials = this.selectedMaterials.filter(material => 
        !this.form.inboundOrderItemsList.some(item => item.materialId === material.id)
      );

      if (newMaterials.length === 0) {
        return this.$message.warning("所选物料已全部添加，无需重复添加");
      }

      // 添加新物料到明细
      newMaterials.forEach(material => {
        this.form.inboundOrderItemsList.push({
          materialId: material.id,
          sapNo: material.sapNo,
          materialName: material.materialName,
          batchCode: '',
          warehouseId: '',
          warehousesName: '',
          locationId: '',
          locationName: '',
          plannedQuantity: 0,
          actualQuantity: 0,
          unitPrice: 0,
          totalAmount: 0,
          actualPackages: 0,
          divisor: 0
        });
      });

      this.$refs.inboundItemsRef?.handleAddItem(newMaterials);
      this.materialSelectOpen = false;
      this.$message.success(`成功添加 ${newMaterials.length} 个物料`);
    },

    /**
     * 确认入库操作
     * @param {Object} row 选中行数据
     */
    async handleConfirm(row) {
      try {
        await this.$confirm('确认要入库吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 查询入库明细
        const queryForm = { pageNum: 1, pageSize: 9999, inboundOrderId: row.id };
        const res = await listInbound_itemsAndMname(queryForm);
        const items = res.rows || [];

        if (items.length === 0) {
          return this.$message.warning('暂无入库明细数据，无法确认入库');
        }

        // 组装库存数据
        const inventoryItems = items.map(item => ({
          ...item,
          inventoryType: row.orderTypeId,
          warehousesId: item.warehouseId,
          inventoryStatus: 1,
          ownerId: row.ownerId,
          quantity: item.actualQuantity,
          unitWeight: item.unitWeight,
          isUsed: 1,
          unitPrice: item.unitPrice
        }));

        // 批量添加库存
        await batchAddInventory(inventoryItems);
        
        // 更新入库单状态
        row.orderStatus = 2;
        await updateInbound(row);
        
        this.$message.success('确认入库成功');
        this.getList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('确认入库失败：' + (error.msg || error.message || '网络异常'));
          console.error('确认入库失败：', error);
        }
      }
    },

    /**
     * 删除入库单
     * @param {Object} row 选中行数据
     */
    async handleDelete(row) {
      try {
        const ids = row?.id || this.ids;
        if (!ids || ids.length === 0) {
          return this.$message.warning('请选择要删除的入库单');
        }

        const confirmText = row?.orderId 
          ? `是否确认删除入库单编号为"${row.orderId}"的数据项？`
          : `是否确认删除选中的${ids.length}条入库单`;

        await this.$confirm(confirmText, '提示', { type: 'warning' });
        await delInbound(ids);
        
        this.$message.success("删除成功");
        this.getList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + (error.message || '网络异常'));
          console.error('删除入库单失败：', error);
        }
      }
    },

    /**
     * 提交表单（新增/修改）
     */
    async submitForm() {
      try {
        // 表单校验
        const valid = await this.$refs.formRef.validate();
        if (!valid) return;

        // 明细校验
        const errors = this.$refs.inboundItemsRef?.validate() || [];
        if (errors.length > 0) {
          return this.$message.error(errors.join('；'));
        }

        // 验证明细数量
        if (this.form.inboundOrderItemsList.length === 0) {
          return this.$message.warning('请至少添加一条入库明细');
        }

        // 计算总数
        this.calculateTotals();

        // 组装提交数据
        const submitData = {
          ...this.form,
          inboundOrderItemsList: this.form.inboundOrderItemsList.map(item => ({
            ...item,
            orderId: this.form.orderId,
            batchId: this.form.batchId,
            inboundOrderId: this.form.id || ''
          }))
        };

        // 提交数据
        if (this.form.id) {
          await updateInbound(submitData);
          this.$message.success("修改成功");
        } else {
          await addInbound(submitData);
          this.$message.success("新增成功");
        }

        this.open = false;
        this.getList();
      } catch (error) {
        this.$message.error('提交失败：' + (error.message || '网络异常'));
        console.error('表单提交失败：', error);
      }
    },

    /**
     * 取消弹窗
     */
    cancel() {
      this.open = false;
      this.inboundOrderId = '';
      this.resetForm();
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.form = {
        id: '',
        orderId: '',
        orderTypeId: '',
        batchId: '',
        warehouseId: '',
        warehousesName: '',
        ownerId: '',
        ownerName: '',
        ownerCode: '',
        orderStatus: 1,
        referenceNo: '',
        plannedArrivalDate: '',
        actualArrivalDate: '',
        inboundDate: this.formatDate(new Date()),
        totalPlannedQuantity: 0,
        totalActualQuantity: 0,
        totalPackages: 0,
        remark: '',
        opUserName: '',
        isUsed: '',
        sortNo: '',
        createTime: '',
        createUserCode: '',
        updateTime: '',
        updateUserCode: '',
        inboundOrderItemsList: []
      };
      this.$refs.inboundItemsRef?.resetEmbeddedData();
      this.$refs.formRef?.resetFields();
    },

    /**
     * 导入按钮操作
     */
    handleImport() {
      this.$refs.importRef?.show();
    },

    /**
     * 获取导入模板名称
     * @returns {string} 模板名称
     */
    getTemplateName() {
      const typeMap = {
        '1': "入库单导入模板",
        '2': "成品入库单导入模板",
        '3': "退料TRDC入库单导入模板"
      };
      return typeMap[this.form.orderTypeId] || "入库单导入模板";
    },

    /**
     * 处理订单类型变化
     * @param {*} selection 选中值
     */
    handleOrderTypeChange(selection) {
      this.form.orderTypeId = selection;
    },

    // ========== 明细项相关方法 ==========
    handleItemsSelectionChange(selection) {
      this.selectedItems = selection;
    },

    handleItemsDataChange(items) {
      this.form.inboundOrderItemsList = items;
      this.calculateTotals();
    },

    handleTotalsChange(totals) {
      this.form.totalPlannedQuantity = totals.plannedQuantity;
      this.form.totalActualQuantity = totals.actualQuantity;
      this.form.totalPackages = totals.packages;
    },

    handleItemAdded(item) {
      item.orderId = this.form.orderId;
    },

    handleRowSaved() {},

    handleRowDeleted() {
      this.$message.success('删除成功');
    },

    handleBatchDelete(ids) {
      this.$message.success(`成功删除 ${ids.length} 项`);
    },

    handleCellChange({ prop }) {
      if (['plannedQuantity', 'actualQuantity'].includes(prop)) {
        this.calculateTotals();
      }
    },

    /**
     * 计算明细总数
     */
    calculateTotals() {
      if (!this.form.inboundOrderItemsList || this.form.inboundOrderItemsList.length === 0) {
        this.form.totalPlannedQuantity = 0;
        this.form.totalActualQuantity = 0;
        this.form.totalPackages = 0;
        return;
      }

      const totals = this.form.inboundOrderItemsList.reduce((acc, item) => {
        acc.plannedQuantity += parseFloat(item.plannedQuantity) || 0;
        acc.actualQuantity += parseFloat(item.actualQuantity) || 0;
        acc.packages += parseFloat(item.plannedPackages) || 0;
        return acc;
      }, { plannedQuantity: 0, actualQuantity: 0, packages: 0 });

      this.form.totalPlannedQuantity = totals.plannedQuantity;
      this.form.totalActualQuantity = totals.actualQuantity;
      this.form.totalPackages = totals.packages;
    },

    /**
     * 导出按钮操作
     */
    handleExport() {
      const params = { ...this.queryParams };
      delete params.pageNum;
      delete params.pageSize;
      this.download('inventory/inbound/export', params, `inbound_${new Date().getTime()}.xlsx`);
    }
  }
}
</script>

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

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

.scrollable-dialog .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px;
}

.detail-container {
  padding: 10px;
}

.remark-text {
  line-height: 1.5;
  min-height: 40px;
  white-space: pre-wrap;
}

.mb20 {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 优化表格边框和交互 */
:deep(.el-table) {
  --el-table-row-hover-bg-color: #f8f9fa;
}

/* 优化弹窗内描述列表样式 */
:deep(.el-descriptions) {
  --el-descriptions-item-label-color: #606266;
}
</style>