<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="出库单号" prop="outNumber">
        <el-input
            v-model="queryParams.outNumber"
            placeholder="请输入出库单号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报修单号" prop="repairNumber">
        <el-input
          v-model="queryParams.repairNumber"
          placeholder="请输入报修单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="plateNumber">
        <el-input
          v-model="queryParams.plateNumber"
          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:materialPicking: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:materialPicking: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:materialPicking:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-finished"
          size="mini"
          :disabled="isTrue"
          @click="handleConfirm"
          v-hasPermi="['business:materialPicking:confirm']"
        >出库</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:materialPicking:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialPickingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单号" align="center" prop="outNumber" />
      <el-table-column label="报修单号" align="center" prop="repairNumber">
        <template slot-scope="scope">
          {{scope.row.repairNumber || '/'}}
        </template>
      </el-table-column>
<!--      <el-table-column label="退料单号" align="center" prop="returnNumber" />-->
      <el-table-column label="车牌号" align="center" prop="plateNumber">
        <template slot-scope="scope">
          {{scope.row.plateNumber || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="vendorName" width="200" show-overflow-tooltip/>
      <el-table-column label="出库金额" align="center" prop="outMoney" width="80">
        <template slot-scope="scope">
          {{scope.row.outMoney || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="领料人" align="center" prop="receiveUserName" width="100">
        <template slot-scope="scope">
          {{scope.row.receiveUserName || '/'}}
        </template>
      </el-table-column>
      <el-table-column label="领料时间" align="center" prop="receiveTime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.receiveTime ? parseTime(scope.row.receiveTime, '{y}-{m}-{d} {h}:{i}:{s}') : '/'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.picking_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.picking_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="出库时间" align="center" prop="outTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px" 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 || scope.row.state === 3"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:materialPicking:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.state === 2 || scope.row.state === 3"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:materialPicking:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            v-if="scope.row.state === 1"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['business:materialPicking:confirm']"
          >出库</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="110px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="出库时间" prop="outTime">
              <el-date-picker clearable
                              v-model="form.outTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width: 100%"
                              placeholder="请选择出库时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库单号" prop="outNumber">
              <el-input v-model="form.outNumber" disabled placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库金额" prop="outMoney">
              <el-input v-model="form.outMoney" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" disabled  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="报修单" prop="repairFormId">
              <el-select v-model="form.repairFormId" placeHolder="请选择报修单" @change="repairFormChange" style="width: 100%">
                <el-option v-for="item in repairFormOpt" :key="item.id" :value="item.id" :label="item.repairNumber" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车牌号" prop="plateNumber">
              <el-input v-model="form.plateNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="repairerDeptName">
              <el-input v-model="form.repairerDeptName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="班组" prop="repairerGroupName">
              <el-input v-model="form.repairerGroupName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="供应商" prop="vendorId">
              <el-select v-model="form.vendorId" placeHolder="请选择供应商" filterable @change="vendorIdChange" style="width: 100%">
                <el-option v-for="item in materialVendorOpt" :key="item.id" :value="item.id" :label="item.vendorName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入操作人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <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>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-loading="addLoading" type="primary" plain icon="el-icon-plus" size="mini" @click="openMaterialModel">新增</el-button>
        </el-col>
      </el-row>
      <el-table :data="form.pickingInfoList">
        <el-table-column label="仓库名称" align="center" prop="warehouseName" />
        <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="inventory" />
        <el-table-column label="领料数量" align="center" prop="collectNumber" width="120px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.collectNumber" @change="collectNumberChange" controls-position="right" size="mini" :min="0.01" :precision="2" :max="parseFloat(scope.row.inventory)"  style="width: 100%" placeholder="数量"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="销售单价" align="center" prop="price" width="120px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-input-number v-model="scope.row.price" disabled controls-position="right" size="mini" :min="1" :precision="2" style="width: 100%" placeholder="单价"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="领料金额" align="center" prop="money" width="120px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.money" 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">
          <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>
      <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="75%" append-to-body>
      <el-form :model="queryMaterialParams" ref="queryMaterialForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
<!--        <el-form-item label="仓库" prop="warehouseId">-->
<!--          <el-select v-model="queryMaterialParams.warehouseId" placeHolder="请选择仓库">-->
<!--            <el-option v-for="item in warehouseOpt" :key="item.id" :value="item.id" :label="item.name" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="供应商" prop="vendorId">
          <el-select v-model="queryMaterialParams.vendorId" filterable disabled placeholder="请选择供应商" style="width: 100%">
            <el-option v-for="item in materialVendorOpt" :key="item.id" :value="item.id" :label="item.vendorName" />
          </el-select>
        </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" @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="warehouseName" />
        <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" 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" />-->
        <el-table-column label="参考价" align="center" prop="referencePrice" width="100" />
        <el-table-column label="销售价" align="center" prop="sellingPrice" width="100" />
        <el-table-column label="库存" align="center" prop="inventory" width="80" />
        <el-table-column label="入库时间" align="center" prop="createTime" width="160" />
      </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="80%" append-to-body>
      <span style="font-weight: bold; font-size: 18px">出库信息</span>
      <el-divider />
      <el-descriptions border :column="3">
        <el-descriptions-item label="出库时间">{{form.outTime}}</el-descriptions-item>
        <el-descriptions-item label="出库单号">{{form.outNumber}}</el-descriptions-item>
        <el-descriptions-item label="出库金额">{{form.outMoney}}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{form.clientName}}</el-descriptions-item>
        <el-descriptions-item label="报修单">{{form.repairNumber}}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{form.plateNumber}}</el-descriptions-item>
        <el-descriptions-item label="部门">{{form.repairerDeptName}}</el-descriptions-item>
        <el-descriptions-item label="班组">{{form.repairerGroupName}}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{form.vendorName}}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.picking_state" :value="form.state" />
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <dict-tag :options="dict.type.picking_type" :value="form.type" />
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{form.createBy}}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{form.createTime}}</el-descriptions-item>
      </el-descriptions>
      <span style="font-weight: bold; font-size: 18px">出库明细</span>
      <el-divider />
      <el-table :data="form.pickingInfoList">
<!--        <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
<!--        <el-table-column label="货位类型" align="center" prop="warehouseLocationType" />-->
        <el-table-column label="仓库名称" align="center" prop="warehouseName" />
        <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="collectNumber" width="120px" />
<!--        <el-table-column label="销售单价" align="center" prop="price" width="120px" />-->
        <el-table-column label="领料金额" align="center" prop="money" width="120px" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterialPicking,
  getMaterialPicking,
  delMaterialPicking,
  addMaterialPicking,
  updateMaterialPicking,
  confirmMaterialPicking
} from '@/api/business/materialPicking'
import { getRepairForm, listRepairForm } from '@/api/business/repairForm'
import {customListMaterial, listMaterial} from '@/api/business/material'
import { formatDate } from '@/utils'
import {listSiteWarehouse, listWarehouseAll} from "@/api/business/siteWarehouse";
import {listMaterialVendor, listMaterialVendorAll} from "@/api/business/materialVendor";

export default {
  name: "MaterialPicking",
  dicts: ['sys_is_enable', 'picking_state', 'picking_type', 'material_unit'],
  data() {
    return {
      // 新增loading
      addLoading: false,
      // 按钮loading
      buttonLoading: false,
      materialLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非登记状态禁用
      isTrue: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料出库表格数据
      materialPickingList: [],
      repairFormOpt: [],
      warehouseOpt: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairFormId: undefined,
        repairNumber: undefined,
        outNumber: undefined,
        returnNumber: undefined,
        carId: undefined,
        plateNumber: undefined,
        outMoney: undefined,
        receiveUserId: undefined,
        receiveUserName: undefined,
        receiveTime: undefined,
        state: undefined,
        outTime: undefined,
      },
      // 表单参数
      form: {},
      open1: false,
      open2: false,
      tempSelection: [],
      // 物料列表
      materialList: [],
      materialVendorOpt: [],
      materialTotal: 0,
      // 查询参数
      queryMaterialParams: {
        pageNum: 1,
        pageSize: 10,
        vendorId: undefined,
        vendorName: undefined,
        warehouseId: undefined,
        warehouseIdList: [],
        materialCode: undefined,
        materialName: undefined,
        inventory: 0,
      },
      warehouseId: undefined,
      warehouseName: undefined,
      // 表单校验
      rules: {
        repairFormId: [
          { required: true, message: "报修单不能为空", trigger: "blur" }
        ],
        outTime: [
          { required: true, message: "出库时间不能为空", trigger: "blur" }
        ],
        vendorId: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料出库列表 */
    getList() {
      this.loading = true;
      listMaterialPicking(this.queryParams).then(response => {
        this.materialPickingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物资供应商列表 */
    getVendorList() {
      listMaterialVendorAll().then(response => {
        this.materialVendorOpt = response.data;
      });
    },
    /** 查询报修单列表 */
    getRepairList() {
      listRepairForm({pageNum: 1, pageSize: 1000, state: 1}).then(response => {
        this.repairFormOpt = response.rows;
      });
    },
    // 报修单更改
    repairFormChange(id) {
      this.addLoading = true;
      getRepairForm(id).then(res =>{
        this.form.clientName = res.data.clientName
        this.form.repairerDeptId = res.data.repairerDeptId
        this.form.repairerDeptName = res.data.repairerDeptName
        this.form.repairerGroupName = res.data.repairerGroupName
        this.form.plateNumber = res.data.car.plateNumber
        this.form.carId = res.data.carId
        this.form.pickingInfoList = []
        this.getWarehouseList(res.data.repairerDeptId)
      })
    },
    /** 查询仓库列表 */
    getWarehouseList(deptId) {
      listWarehouseAll({deptId}).then(response => {
        this.warehouseOpt = response.data;
        this.queryMaterialParams.warehouseIdList = response.data.map(item => item.id);
        this.addLoading = false;
      });
    },
    /** 打开物料列表 */
    openMaterialModel() {
      if (!this.form.repairerDeptId) {
        this.$modal.msgError("请先选择报修单");
        return
      }
      if (!this.form.vendorId) {
        this.$modal.msgError("请先选择供应商");
        return
      }
      this.open1 = true
      this.queryMaterialParams.vendorId = this.form.vendorId;
      this.getMaterialList()
    },
    /** 供应商改变 */
    vendorIdChange(vendorId) {
      this.form.pickingInfoList = []
    },
    /** 搜索按钮操作 */
    handleMaterialQuery() {
      this.queryMaterialParams.pageNum = 1;
      this.getMaterialList();
    },
    /** 重置按钮操作 */
    resetMaterialQuery() {
      this.queryMaterialParams.materialCode = undefined;
      this.queryMaterialParams.materialName = undefined;
      this.queryMaterialParams.pageNum = 1
      this.queryMaterialParams.pageSize = 10
      this.handleMaterialQuery();
    },
    /** 查询物资列表 */
    getMaterialList() {
      this.materialLoading = true;
      customListMaterial({ ...this.queryMaterialParams }).then(response => {
        this.materialList = response.rows;
        this.materialTotal = response.total;
        this.materialLoading = false;
      }).then(() =>{
        this.$nextTick(() => {
          // 清空临时勾选
          this.tempSelection = [];
          // 手动设置勾选（匹配外部已选数据）
          this.materialList.forEach(row => {
            const isSelected = this.form.pickingInfoList.some(item => item.recordId === row.recordId);
            this.$refs.selectionTable.toggleRowSelection(row, isSelected);
          });
        });
      })
    },
    // 入库明细删除
    handleRowDelete(row) {
      this.form.pickingInfoList = this.form.pickingInfoList.filter(item =>
        !(item.materialId === row.materialId && item.warehouseId === row.warehouseId)
      );
    },
    // 入库数量变动
    collectNumberChange() {
      this.form.outMoney = this.form.pickingInfoList.reduce((sum, item) => {
        item.money = item.collectNumber * item.sellingPrice
        return sum + (item.collectNumber * item.sellingPrice);
      }, 0)
    },
    // 多选框选中数据
    handleMaterialSelectionChange(selection) {
      this.tempSelection = selection
    },
    // 将选中物料添加至入库明细列表
    confirmSelection() {
      // this.tempSelection.forEach(row => {
      //   // 关键判断：仅添加不存在的数据
      //   const isExist = this.form.pickingInfoList.some(item => item.id === row.id || item.materialId === row.id);
      //   if (!isExist) {
      //     this.form.pickingInfoList.push(row);
      //   }
      // });
      this.form.pickingInfoList = this.tempSelection.map(item =>{
          item.price = item.sellingPrice
          return item
      })
      this.open1 = false
    },
    // 取消按钮
    cancelMaterial() {
      this.open1 = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        repairFormId: undefined,
        repairNumber: undefined,
        outNumber: undefined,
        returnNumber: undefined,
        carId: undefined,
        plateNumber: undefined,
        vendorId: undefined,
        vendorName: undefined,
        outMoney: undefined,
        receiveUserId: undefined,
        receiveUserName: undefined,
        receiveTime: undefined,
        state: undefined,
        outTime: formatDate(new Date().getTime()),
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        pickingInfoList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let isTrue = false
      this.ids = selection.map(item => {
        if (item.state !== 1) {
          isTrue = true
        }
        return item.id
      })
      if (selection.length > 0) {
        this.isTrue = isTrue
      }else {
        this.isTrue = true
      }
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料出库";
      this.getRepairList()
      this.getVendorList()
    },
    // 详情按钮
    handleDetail(row) {
      getMaterialPicking(row.id).then(response => {
        this.title = "物料出库详情";
        this.form = response.data;
        if (response.data.repairFormId) {
          getRepairForm(response.data.repairFormId).then(res =>{
            this.form.clientName = res.data.clientName
            this.form.repairerDeptId = res.data.repairerDeptId
            this.form.repairerDeptName = res.data.repairerDeptName
            this.form.repairerGroupName = res.data.repairerGroupName
            this.form.plateNumber = res.data.car.plateNumber
            this.form.carId = res.data.carId
            this.open2 = true;
          })
        }else {
          this.open2 = true;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMaterialPicking(id).then(response => {
        this.form = response.data;
        getRepairForm(response.data.repairFormId).then(res =>{
          this.loading = false;
          this.form.clientName = res.data.clientName
          this.form.repairerDeptId = res.data.repairerDeptId
          this.form.repairerDeptName = res.data.repairerDeptName
          this.form.repairerGroupName = res.data.repairerGroupName
          this.form.plateNumber = res.data.car.plateNumber
          this.form.carId = res.data.carId
          this.open = true;
          this.title = "修改物料出库";
          this.getRepairList()
          this.getWarehouseList(res.data.repairerDeptId)
          this.getVendorList()
        })
      });
    },
    /** 提交按钮 */
    submitForm(state) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pickingInfoList.length < 1) {
            this.$modal.msgError('出库物料列表不能为空')
            return
          }
          this.form.materialList = this.form.pickingInfoList.map(item =>{
            return {
              recordId: item.recordId,
              infoId: item.infoId,
              warehouseId: item.warehouseId,
              warehouseName: item.warehouseName,
              vendorId: item.vendorId,
              vendorName: item.vendorName,
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialSpecifications: item.materialSpecifications,
              materialUnit: item.materialUnit,
              materialWarrantyPeriod: item.materialWarrantyPeriod,
              referencePrice: item.referencePrice,
              sellingPrice: item.sellingPrice,
              collectNumber: item.collectNumber,
              price: item.price,
              money: item.money,
            }
          })
          this.buttonLoading = true;
          this.form.state = state
          if (this.form.id != null) {
            updateMaterialPicking(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialPicking(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 出库按钮操作 */
    handleConfirm(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认物料出库？').then(() => {
        this.loading = true;
        return confirmMaterialPicking(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("出库成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料出库编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialPicking(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/materialPicking/export', {
        ...this.queryParams
      }, `物料出库单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
