<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="warning"
          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>

    <!-- 搜索区域（对齐字典页面的page-wrapper-search组件） -->
    <div class="page-container">
      <page-wrapper-search
        :model="queryParams"
        ref="queryForm"
        size="small"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <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>
        <!-- ========== 新增：入库日期范围选择器 ========== -->
        <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>
      </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" width="200"/>
          <el-table-column label="批次号" align="center" prop="batchId" width="200"/>
          <el-table-column label="系统编号" align="center" prop="systemNo" width="200"/>
          <!-- 新增：表格显示货主名称 -->
          <el-table-column label="货主" align="center" prop="ownerName" width="200"/>
          <el-table-column label="入库类型" align="center" prop="orderTypeId" :show-overflow-tooltip="true" width="200">
            <template slot-scope="scope">
              <el-tag
              :type="getDictListClass('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="true" width="200">
            <template slot-scope="scope">
              <el-tag
              :type="getDictListClass('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" width="200">
            <!-- 状态显示 -->
            <template slot-scope="scope">
              <el-tag :type="getDictListClass('inbound_status',scope.row.orderStatus+'')" size="small" width="200">
                {{ getDictLabel('inbound_status',scope.row.orderStatus+"") }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库时间" align="center" prop="inboundDate" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.inboundDate,'{y}-{m}-{d}') }}</span>
            </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-show="!(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-show="!(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-show="!(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" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :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-date-picker>
            </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-divider content-position="center">入库其他信息</el-divider> -->
        <!-- <el-row :gutter="24">
          <el-col :span="12">
            <div class="form-col">
              <el-form-item label="计划量" prop="totalPlannedQuantity">
                <el-input v-model="form.totalPlannedQuantity" placeholder="请输入计划量" />
              </el-form-item>
              <el-form-item label="总件数" prop="totalPackages">
                <el-input v-model="form.totalPackages" placeholder="请输入总件数" />
              </el-form-item>
              <el-form-item label="仓库" prop="warehouseId">
                <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <el-form-item label="实际量" prop="totalActualQuantity">
              <el-input v-model="form.totalActualQuantity" placeholder="请输入实际量" />
            </el-form-item>
            <el-form-item label="负责人" prop="opUserName">
              <el-input v-model="form.opUserName" placeholder="请输入负责人" />
            </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="入库单详细信息"
      :visible.sync="detailOpen"
      width="1200px"
      append-to-body
      class="scrollable-dialog"
    >
      <div class="detail-container">
        <!-- 基础信息展示 -->
        <el-descriptions :column="2" border class="mb20">
          <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="负责人">{{ detailForm.opUserName || '-' }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="计划量">{{ detailForm.totalPlannedQuantity || '-' }}</el-descriptions-item>
          <el-descriptions-item label="实际量">{{ detailForm.totalActualQuantity || '-' }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="总件数">{{ detailForm.totalPackages || '-' }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="仓库">{{ detailForm.warehouseId || '-' }}</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="isEditable"
          :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="选择物料" :visible.sync="materialSelectOpen" width="1200px" append-to-body>
      <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="import"
          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: null,
      ownerSelectorVisible: false,
      ownerSelectTarget: 'form', // 标记当前货主选择的目标：query-搜索页，form-表单页
      // 仓库和库位选择相关
      warehouseSelectorVisible: false,
      locationSelectorVisible: false,
      currentEditRow: null,
      currentEditRowWarehousesId: null,
      // 可编辑状态
      isEditable: true,
      // 物料组件显示
      materialSelectOpen: false,
      selectedMaterialIds: [],
      inboundItemsUpdateStatus: false,
      // 组件带来的选中的物料详情（code、name）
      selectedMaterials: [],
      detailOpen: false,
      detailForm: {}, // 新增详情表单数据
      // 组件监听修改时的orderId变化
      inboundOrderId: null,
      // 选中的明细项
      selectedItems: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库表格数据
      inboundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        orderTypeId: null,
        systemNo: null,
        batchId: null,
        warehouseId: null,
        ownerId: null, // 货主ID（搜索用）
        ownerName: null, // 货主名称（搜索用）
        ownerCode: null, // 货主编码（搜索用）
        orderStatus: null,
        orderType: null,
        inboundDateStart: null,// 开始日期（搜索用）
        inboundDateEnd: null   // 结束日期（搜索用）
      },
      // 表单参数（对齐退库组件的货主字段）
      form: {
        id: null,
        orderId: null,
        orderTypeId: null,
        batchId: null,
        warehouseId: null,
        warehousesName: null,
        ownerId: null, // 货主ID
        ownerName: null, // 货主名称
        ownerCode: null, // 货主编码
        orderStatus: 1,
        referenceNo: null,
        plannedArrivalDate: undefined,
        actualArrivalDate: undefined,
        inboundDate: null, // 入库日期
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        remark: null,
        opUserName: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null,
        // 明细列表
        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" }
        ]
      }
    }
  },
  mounted() {

  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询入库列表 */
    getList() {
      this.loading = true
      listInbound(this.queryParams).then(response => {
        this.inboundList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleOrderTypeChange(selection) {
      this.form.orderTypeId = selection
    },
    /** 获取状态样式类型 */
    getStatusType(status) {
      const item = this.inBoundStatusOptions.find(item => item.orderStatus === status)
      return item ? item.type : 'info'
    },
    /** 获取状态类型名称 */
    getStatusName(status) {
      const item = this.inBoundStatusOptions.find(item => item.orderStatus === status)
      return item ? item.orderStatusName : status
    },
    getDictLabel(dictType, value) {
      // 1. 空值/字典不存在时返回默认值
      if (!value || !this.dict?.type?.[dictType]) return '-';
      // 2. 从字典数组中匹配 value 对应的 label
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.label || '-';
    },
    getDictListClass(dictType, value){
      // 1. 空值/字典不存在时返回默认值
      if (!value || !this.dict?.type?.[dictType]) return '-';
      // 2. 从字典数组中匹配 value 对应的 label
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.raw?.listClass || '';
    },
    getOrderTypeName(type) {
      if (!type) return '未知类型'
      const item = this.orderTypeOptions.find(item => item.orderType === type)
      return item ? item.orderTypeName : '未知类型'
    },
    /** 搜索按钮操作 */
    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.$refs.queryForm?.resetFields()
      this.queryOwnerName = null
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        orderTypeId: null,
        systemNo: null,
        batchId: null,
        warehouseId: null,
        ownerId: null, 
        ownerName: null,
        ownerCode: null, 
        orderStatus: null,
        orderType: null,
        inboundDateStart: null,
        inboundDateEnd: null
      }
      this.inboundDateRange = null;
       this.$nextTick(() => {
        // 重新触发查询，加载默认数据
        this.handleQuery()
      })
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加入库"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      let id = row.id;
      if(id === undefined){
        id = this.ids[0]
      }
      getInbound(id).then(response => {
        if(response.data.orderStatus === 2){
          this.$modal.msgWarning("该入库单已提交，不能修改");
          return;
        }
        this.form = response.data || {};
        // 货主回显
        this.form.ownerName = response.data.ownerName || response.data.ownerCode || response.data.ownerId;
        // 仓库回显
        this.form.warehousesName = response.data.warehousesName || response.data.warehouseId || '-';

        // 明细行回显（核心：同步仓库/库位名称）
        if (this.form.inboundOrderItemsList && this.form.inboundOrderItemsList.length) {
          this.form.inboundOrderItemsList = this.form.inboundOrderItemsList.map(item => ({
            ...item,
            // 仓库名称兜底
            warehousesName: item.warehousesName || item.warehouseId || '-',
            // 库位名称/编码兜底
            locationName: item.locationName || item.locationCode || item.locationId || '-',
            locationCode: item.locationCode || item.locationId || '-'
          }));
        }

        this.inboundOrderId = id;
        // 强制触发子组件的 value 监听（关键）
        this.$nextTick(() => {
          this.$refs.inboundItemsRef?.handlePagination();
          this.$refs.inboundItemsRef?.calculateTotals();
        });
        this.open = true;
        this.title = "修改入库单";
      });
    },
    /** 查看详情 */
    handleDetail(row) {
      this.reset()
      const id = row.id
      this.isEditable = false
      getInbound(id).then(response => {
        // 加载明细数据到详情
        this.detailForm = response.data
        // 适配货主回显
        this.detailForm.ownerName = response.data.ownerName || response.data.ownerCode || response.data.ownerId
        this.detailForm.inboundOrderId = id
        this.detailOpen = true
      })
    },
    // 打开货主选择器（区分搜索/表单场景）
    openOwnerSelector(target = 'form') {
      this.ownerSelectTarget = target
      this.ownerSelectorVisible = true
    },
    // 货主选择回调（对齐退库组件逻辑）
    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.handleQuery() // 选择后立即搜索
      } else {
        // 表单页选择货主
        this.form.ownerId =  owner.ownerId
        this.form.ownerCode = owner.ownerCode
        this.form.ownerName = owner.ownerName
      }
      this.ownerSelectorVisible = false
    },
    // 清空搜索页货主
    clearQueryOwner() {
      this.queryOwnerName = null
      this.queryParams.ownerId = null
      this.queryParams.ownerCode = null
      this.queryParams.ownerName = null
      this.handleQuery() // 清空后重新搜索
    },
    // 清空表单页货主
    clearFormOwner() {
      this.form.ownerId = null
      this.form.ownerCode = null
      this.form.ownerName = null
      // 清除货主字段校验
      this.$refs.form?.clearValidate('ownerId')
    },
    // 打开仓库选择器
    openWarehouseSelector(row) {
      this.currentEditRow = row
      this.warehouseSelectorVisible = true
    },
    // 仓库选择回调
    handleWarehouseSelected(warehouse) {
      if (this.currentEditRow) {
        // 1. 用 $set 赋值，确保响应式
        this.$set(this.currentEditRow, 'warehouseId', warehouse.warehouseId);
        this.$set(this.currentEditRow, 'warehousesName', warehouse.warehousesName);

        // 2. 通知子组件刷新（关键：触发 displayData 的响应式更新）
        this.$refs.inboundItemsRef?.syncDataToParent();
        this.$refs.inboundItemsRef?.calculateTotals();
      } else {
        this.form.warehouseId = warehouse.warehouseId;
        this.form.warehousesName = warehouse.warehousesName;
      }
      this.warehouseSelectorVisible = false;
    },
      // 打开库位选择器
    openLocationSelector(row) {
      this.currentEditRow = row
      // this.currentEditRowWarehousesId = row.warehouseId // 传递仓库ID给库位选择器
      this.locationSelectorVisible = true
    },
    // 库位选择回调
    handleLocationSelected(location) {
      if (this.currentEditRow) {
        // 1. 用 $set 赋值，确保响应式
        this.$set(this.currentEditRow, 'locationId', location.locationId);
        this.$set(this.currentEditRow, 'locationCode', location.locationCode);
        this.$set(this.currentEditRow, 'locationName', location.locationName);

        // 2. 通知子组件刷新
        this.$refs.inboundItemsRef?.syncDataToParent();
        this.$refs.inboundItemsRef?.calculateTotals();
      }
      this.locationSelectorVisible = false;
    },
    // 打开物料选择弹窗
    showMaterials(status) {
      this.materialSelectOpen = status
      if (status) { // 只有打开弹窗时才清空选择
        this.selectedMaterialIds = [] // 先清空父组件数据
        this.selectedMaterials = []
        this.$nextTick(() => {
          // 确保弹窗渲染完成后再调用子组件方法
          this.$refs.materialSelector?.clearSelection()
        })
      }
    },

    // 物料选择变化回调
    handleMaterialChange(selectedRows) {
      this.selectedMaterials = selectedRows
    },

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

      // 将选中的物料添加到入库明细
      this.selectedMaterials.forEach(material => {
        // 检查是否已存在该物料，避免重复添加
        // const exists = this.form.inboundOrderItemsList.some(
        //   item => item.materialId === material.materialId
        // )
        const exists = false
        if (!exists) {
          this.form.inboundOrderItemsList.push({
            materialId: material.id,
            sapNo: material.sapNo,
            materialName: material.materialName,  // 仅用于展示
            batchCode: null,
            warehouseId: null,
            warehousesName: null,
            locationId: null,
            locationName: null,
            plannedQuantity: 0,
            actualQuantity: 0,
            unitPrice: 0,
            totalAmount: 0,
            actualPackages: 0,
            divisor: 0
          })
        } else {
          // this.$message.warning(`物料 ${material.materialName} 已存在，跳过添加`)
        }
      })
      this.materialSelectOpen = false
      this.$refs.inboundItemsRef.handleAddItem(this.selectedMaterials)
      this.$message.success(`成功添加 ${this.selectedMaterials.length} 个物料`)
    },
    /** 确认入库操作 */
    async handleConfirm(row) { // 标记为 async 函数
      try {
        // 第一步：确认弹窗
        await this.$confirm('确认要入库吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 第二步：等待 listInbound_items 执行完成
        const queryForm = {
          pageNum: 1,
          pageSize: 9999,
          inboundOrderId: row.id
        }
        const response = await listInbound_itemsAndMname(queryForm)
        row.inboundOrderItemsList = response.rows.map(item => {
          return {
            ...item,
            inventoryType: row.orderTypeId,
            warehousesId: item.warehouseId,
            inventoryStatus: 1,
            ownerId: row.ownerId,
            quantity: item.actualQuantity,
            unitWeight: item.unitWeight,
            isUsed: 1,
            unitPrice: item.unitPrice
          };
        })
        // 第三步：确保数据存在后调用入库接口
        if (!row.inboundOrderItemsList || row.inboundOrderItemsList.length === 0) {
          this.$message.warning('暂无入库明细数据，无法确认入库')
          return
        }

        await batchAddInventory(row.inboundOrderItemsList)

        // 第四步：操作成功提示
        this.$modal.msgSuccess("确认成功")
        this.$message.success('确认入库成功')
        row.orderStatus = 2
        updateInbound(row).then(() => {
          this.getList()
        })
      } catch (error) {
        // 捕获取消确认/接口失败的异常
        if (error !== 'cancel') {
          this.$message.error('确认入库失败：' + (error.msg || '网络异常'))
          console.log(error)
        }
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm((row.orderId ? '是否确认删除入库单编号为"' + row.orderId + '"的数据项？' : '是否确认删除选中的' + ids.length + '条入库单'), '提示', {
        type: 'warning'
      }).then(() => {
        return delInbound(ids)
      }).then(() => {
        this.getList()
        this.$message.success("删除成功")
      }).catch(() => {})
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return

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

        // 确保明细项数量大于0
        if (!this.form.inboundOrderItemsList || this.form.inboundOrderItemsList.length === 0) {
          this.$message.warning('请至少添加一条入库明细')
          return
        }

        // 自动计算总数
        this.calculateTotals()

        // 提交数据
        const submitData = {
          ...this.form,
          inboundOrderItemsList: this.form.inboundOrderItemsList.map(item => ({
            ...item,
            orderId: this.form.orderId, // 确保明细项有主表ID
            batchId: this.form.batchId,
            inboundOrderId: this.form.id || null
          }))
        }
        if (this.form.id != null) {
          updateInbound(submitData).then(response => {
            this.$message.success("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addInbound(submitData).then(response => {
            this.$message.success("新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },

    /** 取消按钮 */
    cancel() {
      this.open = false
      this.inboundOrderId = null
      this.reset()
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        orderId: null,
        orderTypeId: null,
        batchId: null,
        warehouseId: null,
        warehousesName: null,
        ownerId: null,
        ownerName: null,
        ownerCode: null,
        orderStatus: 1,
        referenceNo: null,
        plannedArrivalDate: null,
        actualArrivalDate: null,
        inboundDate: null,
        totalPlannedQuantity: 0,
        totalActualQuantity: 0,
        totalPackages: 0,
        remark: null,
        opUserName: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null,
        inboundOrderItemsList: []
      }
      if (this.$refs.inboundItemsRef) {
        this.$refs.inboundItemsRef.resetEmbeddedData()
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.import.show()
    },
    getTemplateName(){
      if(this.form.orderTypeId === '1'){
        return "入库单导入模板"
      }else if(this.form.orderTypeId === '2'){
        return "成品入库单导入模板"
      }else if(this.form.orderTypeId === '3'){
        return "退料TRDC入库单导入模板"
      }
    },
    /** 处理明细项选择变化 */
    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) {
      // 为新项设置orderId
      item.orderId = this.form.orderId
    },

    /** 行保存回调 */
    handleRowSaved(row) {
      // 可以在这里添加保存后的逻辑
    },

    /** 行删除回调 */
    handleRowDeleted(row) {
      this.$message.success('删除成功')
    },

    /** 批量删除回调 */
    handleBatchDelete(ids) {
      this.$message.success(`成功删除 ${ids.length} 项`)
    },

    /** 单元格变化回调 */
    handleCellChange({ row, prop, value }) {
      // 可以在这里处理特定字段的变化
      if (prop === 'plannedQuantity' || prop === 'actualQuantity') {
        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;  /* 最大高度80%视口高度 */
  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;
}
</style>
