<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="订单单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到货单号" prop="arrivalNumber">
        <el-input
          v-model="queryParams.arrivalNumber"
          placeholder="请输入到货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库单号" prop="putawayCode">
        <el-input
          v-model="queryParams.putawayCode"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--          <el-form-item label="供应商" prop="vendorName">-->
<!--            <el-input-->
<!--              v-model="queryParams.vendorName"-->
<!--              placeholder="请输入供应商名称"-->
<!--              clearable-->
<!--              @keyup.enter.native="handleQuery"-->
<!--            />-->
<!--          </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:materialPutaway:add']"
        >新增</el-button>
      </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="success"-->
<!--              plain-->
<!--              icon="el-icon-edit"-->
<!--              size="mini"-->
<!--              :disabled="single"-->
<!--              @click="handleUpdate"-->
<!--              v-hasPermi="['business:materialPutaway:edit']"-->
<!--            >修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="danger"-->
<!--              plain-->
<!--              icon="el-icon-delete"-->
<!--              size="mini"-->
<!--              :disabled="multiple"-->
<!--              @click="handleDelete"-->
<!--              v-hasPermi="['business:materialPutaway:remove']"-->
<!--            >删除</el-button>-->
<!--          </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:materialPutaway:export']"
        >导出明细</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialPutawayList" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="入库单号" align="center" prop="putawayCode" width="180px"/>
      <el-table-column label="订单单号" align="center" prop="orderNumber">
        <template slot-scope="scope">
          {{scope.row.orderNumber || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="到货单号" align="center" prop="arrivalNumber">
        <template slot-scope="scope">
          {{scope.row.arrivalNumber || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="入库类型" align="center" prop="putawayType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.putaway_type" :value="scope.row.putawayType"/>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" align="center" prop="putawayTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.putawayTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库金额" align="center" prop="putawayMoney">
        <template slot-scope="scope">
          {{scope.row.putawayMoney || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="仓库名称" align="center" prop="warehouseName">
        <template slot-scope="scope">
          {{scope.row.warehouseName || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.putaway_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="150px"/>
      <el-table-column label="操作" align="center" width="180px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.state === 2"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:materialPutaway:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.state === 2"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:materialPutaway:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            v-if="scope.row.state === 1"
            @click="handlePutaway(scope.row)"
            v-hasPermi="['business:materialPutaway:putaway']"
          >入库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改物料入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <span style="font-weight: bold; font-size: 18px">入库信息</span>
        <el-divider />
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单号" prop="putawayNumber">
              <el-input v-model="form.putawayNumber" disabled placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单单号" prop="orderNumber">
              <el-input v-model="form.orderNumber" placeholder="请输入订单单号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到货单号" prop="arrivalNumber">
              <el-input v-model="form.arrivalNumber" placeholder="请输入到货单号" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库时间" prop="putawayTime">
              <el-date-picker clearable
                              v-model="form.putawayTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择入库时间"
                              style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select clearable v-model="form.warehouseId" placeholder="请选择仓库" style="width:100%">
                <el-option v-for="(item,index) of warehouseList" :key="index" :label="item.name" :value="String(item.id)">{{item.name}}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="供应商" prop="vendorId">-->
<!--              <el-select clearable v-model="form.vendorId" placeholder="请选择供应商" style="width:100%">-->
<!--                <el-option v-for="(item,index) of materialVendorList" :key="index" :label="item.vendorName" :value="String(item.id)">{{item.vendorName}}</el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="入库金额" prop="putawayMoney">
              <el-input-number v-model="form.putawayMoney" :precision="2" disabled style="width: 100%" placeholder="请输入入库金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="操作人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入操作人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" style="width: 100%" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择操作时间" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <span style="font-weight: bold; font-size: 18px">物料信息</span>
        <el-divider />
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openMaterialModel">新增</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="form.putawayInfoList">
<!--          <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--          <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
          <el-table-column label="供应商" align="center" prop="vendorId" width="300">
            <template slot-scope="scope">
              <el-select clearable v-model="scope.row.vendorId" @change="(id) =>{vendorChange(id, scope.row)}" placeholder="请选择供应商" style="width:100%">
                <el-option v-for="(item,index) of materialVendorList" :key="index" :label="item.vendorName" :value="item.id">{{item.vendorName}}</el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物资编码" align="center" prop="materialCode" />
          <el-table-column label="物资名称" align="center" prop="materialName" />
          <el-table-column label="物资规格" align="center" prop="materialSpecifications" />
          <el-table-column label="物资单位" align="center" prop="materialUnit" width="50">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.material_unit" :value="scope.row.materialUnit" />
            </template>
          </el-table-column>
          <el-table-column label="质保期(月)" align="center" prop="materialWarrantyPeriod" width="80"/>
          <el-table-column label="参考价" align="center" prop="referencePrice" width="80"/>
          <el-table-column label="销售价" align="center" prop="sellingPrice" width="80"/>
          <el-table-column label="入库数量" align="center" prop="putawayNumber" width="140px">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.putawayNumber" @change="putawayChange" controls-position="right" size="mini" :min="0.01" :precision="2" style="width: 100%" placeholder="数量"/>
            </template>
          </el-table-column>
          <el-table-column label="入库单价" align="center" prop="putawayPrice" width="150px">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.putawayPrice" @change="putawayChange" controls-position="right" size="mini" :min="0.01" :precision="2" style="width: 100%" placeholder="单价"/>
            </template>
          </el-table-column>
          <el-table-column label="入库金额" align="center" prop="putawayMoney" width="150px">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.putawayMoney" disabled controls-position="right" size="mini" :precision="2" style="width: 100%" placeholder="金额"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="50">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRowDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm(1)">保 存</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm(2)">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料列表对话框 -->
    <el-dialog title="物料列表" :visible.sync="open1" width="65%" append-to-body>
      <el-form :model="queryMaterialParams" ref="queryMaterialForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="供应商" prop="vendorName">
          <el-input
            v-model="queryMaterialParams.vendorName"
            placeholder="请输入供应商名称"
            clearable
            @keyup.enter.native="handleMaterialQuery"
          />
        </el-form-item>
        <el-form-item label="物资编码" prop="materialCode">
          <el-input
            v-model="queryMaterialParams.materialCode"
            placeholder="请输入物资编码"
            clearable
            @keyup.enter.native="handleMaterialQuery"
          />
        </el-form-item>
        <el-form-item label="物资名称" prop="materialName">
          <el-input
            v-model="queryMaterialParams.materialName"
            placeholder="请输入物资名称"
            clearable
            @keyup.enter.native="handleMaterialQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaterialQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="materialLoading" :data="materialList" ref="selectionTable" max-height="450" row-key="id" @selection-change="handleMaterialSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="供应商" align="center" prop="vendorName" width="120px" show-overflow-tooltip />
        <el-table-column label="物资编码" align="center" prop="materialCode" width="110px" />
        <el-table-column label="物资名称" align="center" prop="materialName" width="180px" />
        <el-table-column label="物资规格" align="center" prop="materialSpecifications" />
        <el-table-column label="物资单位" align="center" prop="materialUnit">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_unit" :value="scope.row.materialUnit" />
          </template>
        </el-table-column>
        <el-table-column label="质保期(月)" align="center" prop="materialWarrantyPeriod" />
        <el-table-column label="参考价" align="center" prop="referencePrice" />
        <el-table-column label="销售价" align="center" prop="sellingPrice" />
<!--        <el-table-column label="库存" align="center" prop="inventory" />-->
        <el-table-column label="是否启用" align="center" prop="isEnable">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="materialTotal>0" :total="materialTotal" :page.sync="queryMaterialParams.pageNum" :limit.sync="queryMaterialParams.pageSize" @pagination="getMaterialList"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
        <el-button @click="cancelMaterial">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 入库单详情 -->
    <el-dialog title="入库单详情" :visible.sync="open2" width="70%" append-to-body>
      <el-descriptions class="margin-top" title="入库信息" :column="3" border>
        <el-descriptions-item label="入库单号">{{form.putawayCode}}</el-descriptions-item>
        <el-descriptions-item label="订单单号">{{form.orderNumber}}</el-descriptions-item>
        <el-descriptions-item label="到货单号">{{form.arrivalNumber}}</el-descriptions-item>
        <el-descriptions-item label="入库类型">
            <dict-tag :options="dict.type.putaway_type" :value="form.putawayType"/>
        </el-descriptions-item>
        <el-descriptions-item label="入库时间">{{form.putawayTime}}</el-descriptions-item>
        <el-descriptions-item label="入库金额">{{form.putawayMoney}}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{form.warehouseName}}</el-descriptions-item>
        <el-descriptions-item label="状态">
            <dict-tag :options="dict.type.putaway_state" :value="form.state"/>
        </el-descriptions-item>
      </el-descriptions>
      <span style="font-size: 16px; font-weight: bold; margin-top: 20px">物料信息</span>
      <el-table :data="form.putawayInfoList" style="margin-top: 15px">
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="供应商" align="center" prop="vendorName" />
        <el-table-column label="物资编码" align="center" prop="materialCode" />
        <el-table-column label="物资名称" align="center" prop="materialName" />
        <el-table-column label="物资规格" align="center" prop="materialSpecifications" />
        <el-table-column label="物资单位" align="center" prop="materialUnit">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_unit" :value="scope.row.materialUnit" />
          </template>
        </el-table-column>
        <el-table-column label="质保期(月)" align="center" prop="materialWarrantyPeriod" />
        <el-table-column label="参考价" align="center" prop="referencePrice" />
        <el-table-column label="销售价" align="center" prop="sellingPrice" />
        <el-table-column label="入库数量" align="center" prop="putawayNumber" />
        <el-table-column label="入库单价" align="center" prop="putawayPrice"  />
        <el-table-column label="入库金额" align="center" prop="putawayMoney"  />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMaterialPutaway,
  delMaterialPutaway,
  getMaterialPutaway,
  listMaterialPutaway,
  putMaterialPutaway,
  updateMaterialPutaway
} from '@/api/business/materialPutaway'
import { typeTree } from '@/api/business/materialType'
import {listSiteWarehouse, listWarehouseAll} from '@/api/business/siteWarehouse'
import {listMaterialVendor, listMaterialVendorAll} from '@/api/business/materialVendor'
import { listMaterial } from '@/api/business/material'
import { formatDate } from '@/utils'

export default {
  name: "MaterialPutaway",
  dicts:['putaway_type','putaway_state','sys_is_enable', 'material_unit'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料入库表格数据
      materialPutawayList: [],
      selectedMaterialMap: new Map(),
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      // 分类名称
      typeName: undefined,
      // 分类树
      typeOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 仓库列表
      warehouseList: [],
      // 供应商列表
      materialVendorList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: undefined,
        arrivalNumber: undefined,
        putawayCode: undefined,
        putawayType: undefined,
        putawayTime: undefined,
        warehouseName: undefined,
        vendorName: undefined,
      },
      materialLoading: false,
      tempSelection: [],
      // 物料列表
      materialList: [],
      materialTotal: 0,
      // 查询参数
      queryMaterialParams: {
        pageNum: 1,
        pageSize: 10,
        vendorName: undefined,
        materialCode: undefined,
        materialName: undefined,
      },
      // 表单参数
      form: {
        putawayInfoList: []
      },
      // 表单校验
      rules: {
        orderNumber: [
          { required: true, message: "订单单号不能为空", trigger: "blur" }
        ],
        arrivalNumber: [
          { required: true, message: "到货单号不能为空", trigger: "blur" }
        ],
        putawayType: [
          { required: true, message: "入库类型不能为空", trigger: "change" }
        ],
        putawayTime: [
          { required: true, message: "入库时间不能为空", trigger: "blur" }
        ],
        putawayMoney: [
          { required: true, message: "入库金额不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        vendorId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    // this.getTreeTree();
  },
  watch: {
    // 根据名称筛选部门树
    typeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 查询物料入库列表 */
    getList() {
      this.loading = true;
      listMaterialPutaway(this.queryParams).then(response => {
        this.materialPutawayList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /* 供应商改变 */
    vendorChange(id, item) {
      let vendor = this.materialVendorList.find(v => v.id === id);
      item.vendorName = vendor.vendorName;
    },
    /** 查询仓库列表 */
    getWarehouseList() {
      listWarehouseAll().then(response => {
        this.warehouseList = response.data;
      });
    },
    /** 查询物资供应商列表 */
    getVendorList() {
      listMaterialVendorAll().then(response => {
        this.materialVendorList = response.data;
      });
    },
    /** 打开物料列表 */
    openMaterialModel() {
      this.open1 = true
      // 打开对话框时初始化已选数据
      this.initializeSelectedMaterials()
      this.getMaterialList()
    },
    /** 初始化已选物料数据 */
    initializeSelectedMaterials() {
      // 将当前入库明细列表中的物料添加到已选Map中
      this.selectedMaterialMap.clear()
      this.form.putawayInfoList.forEach(item => {
        const materialId = item.materialId || item.id
        console.log('item' , item)
        if (materialId) {
          this.selectedMaterialMap.set(materialId, item)
        }
      })
    },

    /** 查询物资列表 */
    getMaterialList() {
      this.materialLoading = true;
      listMaterial(this.queryMaterialParams).then(response => {
        this.materialList = response.rows;
        this.materialTotal = response.total;
        this.materialLoading = false;
      }).then(() => {
        this.$nextTick(() => {
          // 清空临时勾选
          this.tempSelection = [];
          // 恢复选择状态
          this.restoreMaterialSelection();
        });
      })
    },

    /** 恢复物料选择状态 */
    restoreMaterialSelection() {
      if (!this.$refs.selectionTable || !this.materialList.length) return;

      // 先清空所有选择
      this.$refs.selectionTable.clearSelection();

      // 获取所有需要选择的物料ID
      const selectedIds = new Set();
      this.form.putawayInfoList.forEach(item => {
        const materialId = item.materialId || item.id;
        if (materialId) {
          selectedIds.add(materialId);
        }
      });

      // 批量设置选择状态
      this.$nextTick(() => {
        this.materialList.forEach(row => {
          if (selectedIds.has(row.id)) {
            this.$refs.selectionTable.toggleRowSelection(row, true);
          }
        });
      });
    },

    // 多选框选中数据
    handleMaterialSelectionChange(selection) {
      this.tempSelection = selection;
      // 更新已选数据的Map
      const currentPageIds = new Set(this.materialList.map(row => row.id));
      // 移除当前页中取消选择的行
      console.log('currentPageIds--------->',currentPageIds);
      console.log('this.selectedMaterialMap--------->',this.selectedMaterialMap);
      console.log('selection--------->',selection);
      for (let id of this.selectedMaterialMap.keys()) {
        if (currentPageIds.has(id) && !selection.some(row => row.id === id)) {
          console.log('delete-------->', id)
          this.selectedMaterialMap.delete(id);
        }
      }
      // 添加当前页中新选择的行
      selection.forEach(row => {
        // 如果物料已经在入库明细中，保留原有数据
        if (this.selectedMaterialMap.has(row.id)) {
          const existingItem = this.selectedMaterialMap.get(row.id);
          // 保留入库数量、单价等编辑过的数据
          this.selectedMaterialMap.set(row.id, {
            ...row,
            putawayNumber: existingItem.putawayNumber || 0.01,
            putawayPrice: existingItem.putawayPrice || 0.01,
            putawayMoney: existingItem.putawayMoney || 0.01,
            vendorId: existingItem.vendorId,
            vendorName: existingItem.vendorName
          });
        } else {
          // 新选择的物料，设置默认值
          this.selectedMaterialMap.set(row.id, {
            ...row,
            materialId: row.id,
            putawayNumber: 0.01,
            putawayPrice: 0.01,
            putawayMoney: 0.01,
            vendorId: row.vendorId,
            vendorName: row.vendorName
          });
        }
      });
    },
    // 将选中物料添加至入库明细列表
    confirmSelection() {
      // 使用Map中的数据更新入库明细列表
      this.form.putawayInfoList = Array.from(this.selectedMaterialMap.values());
      this.open1 = false;
      this.resetMaterialQuery()
      // 重新计算总金额
      this.putawayChange();
    },
    /** 搜索按钮操作 */
    handleMaterialQuery() {
      this.queryMaterialParams.pageNum = 1;
      this.getMaterialList();
    },
    /** 重置按钮操作 */
    resetMaterialQuery() {
      this.resetForm("queryMaterialForm");
      this.handleMaterialQuery();
    },
    // 入库明细删除
    handleRowDelete(row) {
      const materialId = row.materialId || row.id;
      // 从Map中移除
      this.selectedMaterialMap.delete(materialId);
      // 更新入库明细列表
      this.form.putawayInfoList = this.form.putawayInfoList.filter(item => {
        const itemMaterialId = item.materialId || item.id;
        return itemMaterialId !== materialId;
      });
      this.putawayChange();
    },
    // 取消物料选择
    cancelMaterial() {
      this.open1 = false;
      // 可选：清空临时选择，但保留已确认的选择
      this.tempSelection = [];
      this.resetMaterialQuery()
    },
    // 入库数量变动
    putawayChange() {
      this.form.putawayMoney = this.form.putawayInfoList.reduce((sum, item) => {
        item.putawayMoney = item.putawayNumber * item.putawayPrice
        return sum + (item.putawayNumber * item.putawayPrice);
      }, 0)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        orderNumber: undefined,
        arrivalNumber: undefined,
        putawayNumber: undefined,
        putawayType: undefined,
        putawayTime: formatDate(new Date().getTime()),
        putawayMoney: undefined,
        returnNumber: undefined,
        returnTime: undefined,
        returnMoney: undefined,
        warehouseId: undefined,
        warehouseName: undefined,
        vendorId: undefined,
        vendorName: undefined,
        updateBy: undefined,
        updateTime: undefined,
        createDeptId: undefined,
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        putawayInfoList: []
      };
      this.selectedMaterialMap.clear();
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      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 = "添加物料入库";
      this.getWarehouseList()
      this.getVendorList()
      console.log('this.selectedMaterialMap', this.selectedMaterialMap)
      console.log('this.form.putawayInfoList', this.form.putawayInfoList)
      console.log('this.this.tempSelection', this.tempSelection)
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const id = row.id
      getMaterialPutaway(id).then(response => {
        this.form = response.data;
        this.open2 = true;
        this.title = "物料入库详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMaterialPutaway(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改物料入库";
        this.getWarehouseList()
        this.getVendorList()
        // 初始化已选物料数据
        this.initializeSelectedMaterials();
      });
    },
    /** 提交按钮 */
    submitForm(state) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.state = state
          if (this.form.putawayInfoList.length < 1) {
            this.$modal.msgError('入库明细列表不能为空')
            this.buttonLoading = false;
            return
          }

          let vendorIsNull = false
          this.form.putawayInfoList.forEach(item =>{
            if (!item.vendorId) {
              vendorIsNull = true
            }
          })
          if (vendorIsNull) {
            this.$modal.msgError('入库明细列表物料供应商不能为空')
            this.buttonLoading = false;
            return
          }

          this.form.putawayInfoList.forEach(item =>{
            item.materialId = item.materialId || item.id
          })
          if (this.form.id != null) {
            updateMaterialPutaway(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialPutaway(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料入库单？').then(() => {
        this.loading = true;
        return delMaterialPutaway(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 入库按钮操作 */
    handlePutaway(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认入库物料？').then(() => {
        this.loading = true;
        return putMaterialPutaway(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("入库成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/materialPutawayInfo/export', {
        ...this.queryParams
      }, `入库单明细_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
