<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="任务编码" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务执行人" prop="taskUserName">
        <el-input
          v-model="queryParams.taskUserName"
          placeholder="请输入任务执行人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点状态" prop="checkState">
        <el-select clearable v-model="queryParams.checkState" placeholder="请选择盘点状态" style="width:100%">
          <el-option v-for="(item,index) of dict.type.check_state" :key="index" :value="item.value" :label="item.label" />
        </el-select>
      </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:materialCheck: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:materialCheck: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:materialCheck: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:materialCheck:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialCheckList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="任务编码" align="center" prop="taskCode" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务执行人" align="center" prop="taskUserName" />
      <el-table-column label="任务开始时间" align="center" prop="taskStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务结束时间" align="center" prop="taskEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="盘点状态" align="center" prop="checkState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.check_state" :value="scope.row.checkState"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <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 === 1"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:materialCheck:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.state === 1"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:materialCheck:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            :disabled="scope.row.state === 1"
            @click="handleCheck(scope.row)"
            v-hasPermi="['business:materialCheck:check']"
          >结束盘点</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>
      <span style="font-weight: bold; font-size: 18px">盘点信息</span>
      <el-divider />
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="任务编码" prop="taskCode">
              <el-input v-model="form.taskCode" disabled placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="deptId">
              <treeselect :clearable="false" v-model="form.deptId" :options="deptTreeData" placeholder="请选择部门" style="width: 100%;" :show-count="true" @select="handleDeptChange" :loadOptions="()=>{}" :normalizer="normalizer" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" @change="warehouseChange" style="width:100%">
                <el-option v-for="(item,index) of warehouseList" :key="index" :label="item.name" :value="item.id">{{item.name}}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="任务开始时间" prop="taskStartTime">
              <el-date-picker clearable
                              v-model="form.taskStartTime"
                              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="taskEndTime">
              <el-date-picker clearable
                              v-model="form.taskEndTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width: 100%"
                              disabled
                              placeholder="请选择任务结束时间">
              </el-date-picker>
            </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-row>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="出库方式" prop="putType">-->
<!--              <el-input v-model="form.putType" disabled placeholder="盘亏" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="出库类型" prop="putType">-->
<!--              <el-input v-model="form.putType" disabled placeholder="基本出库" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="入库方式" prop="putType">-->
<!--              <el-input v-model="form.putType" disabled placeholder="盘盈" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="入库类型" prop="checkType">-->
<!--              <el-select clearable v-model="form.checkType" placeholder="请选择入库类型" style="width:100%">-->
<!--                <el-option v-for="(item,index) in dict.type.check_type" :key="item.value" :value="item.value" :label="item.label" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-loading="infoLoading" type="primary" plain icon="el-icon-plus" size="mini" @click="openMaterialModel">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-loading="infoLoading" type="primary" plain icon="el-icon-plus" size="mini" @click="openMaterialInit">初始化</el-button>
        </el-col>
      </el-row>
      <el-divider />
      <el-table v-loading="infoLoading" :data="form.checkInfoList">
        <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="vendorName" />
        <el-table-column label="质保期" align="center" prop="materialWarrantyPeriod" />
        <el-table-column label="库存" align="center" prop="inventory" />
        <el-table-column label="实盘数量" align="center" prop="checkNum" width="140px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.checkNum" controls-position="right" size="mini" :min="0" :precision="2" @change="checkNumChange" style="width: 100%" placeholder="实盘数量"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="期间出库数量" align="center" prop="periodOutNum" width="140px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-input-number v-model="scope.row.periodOutNum" controls-position="right" size="mini" :min="0" precision="2" @change="periodOutNumChange" style="width: 100%" placeholder="期间出库数量"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="结果数量" align="center" prop="resultNum" width="120px" />-->
        <el-table-column label="盘点结果" align="center" prop="resultState">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.check_info_state" :value="scope.row.resultState"/>
          </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">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料列表对话框 -->
    <el-dialog title="选择盘点物料" :visible.sync="open2" 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="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 label="供应商" prop="vendorName">
          <el-input
            v-model="queryMaterialParams.vendorName"
            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="materialId" @selection-change="handleMaterialSelectionChange">
        <el-table-column type="selection" width="55" align="center" reserve-selection />
        <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="vendorName" />
        <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>
      <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="title" :visible.sync="open1" 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.taskCode}}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{form.taskName}}</el-descriptions-item>
        <el-descriptions-item label="部门">{{form.deptName}}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{form.warehouseName}}</el-descriptions-item>
        <el-descriptions-item label="任务开始时间">{{form.taskStartTime}}</el-descriptions-item>
        <el-descriptions-item label="任务结束时间">{{form.taskEndTime}}</el-descriptions-item>
        <el-descriptions-item label="任务执行人">{{form.taskUserName}}</el-descriptions-item>
        <el-descriptions-item label="盘点状态">
          <dict-tag :options="dict.type.check_state" :value="form.checkState" />
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{form.remark}}</el-descriptions-item>
      </el-descriptions>
      <span style="font-weight: bold; font-size: 18px">盘点明细</span>
      <el-divider />
      <el-tabs v-model="activeName">
        <el-tab-pane label="全部" name="all">
          <el-table :data="form.checkInfoList">
            <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="vendorName" />
            <el-table-column label="质保期" align="center" prop="materialWarrantyPeriod" />
            <el-table-column label="库存" align="center" prop="inventory" />
            <el-table-column label="实盘数量" align="center" prop="checkNum" width="140px" />
            <!--        <el-table-column label="期间出库数量" align="center" prop="periodOutNum" width="140px" />-->
            <!--        <el-table-column label="结果数量" align="center" prop="resultNum" width="120px" />-->
            <el-table-column label="盘点结果" align="center" prop="resultState">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.check_info_state" :value="scope.row.resultState"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="盘盈" name="just">
          <el-table :data="form.checkInfoJustList">
            <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="vendorName" />
            <el-table-column label="质保期" align="center" prop="materialWarrantyPeriod" />
            <el-table-column label="库存" align="center" prop="inventory" />
            <el-table-column label="实盘数量" align="center" prop="checkNum" width="140px" />
            <!--        <el-table-column label="期间出库数量" align="center" prop="periodOutNum" width="140px" />-->
            <!--        <el-table-column label="结果数量" align="center" prop="resultNum" width="120px" />-->
            <el-table-column label="盘点结果" align="center" prop="resultState">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.check_info_state" :value="scope.row.resultState"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="盘亏" name="lose">
          <el-table :data="form.checkInfoLoseList">
            <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="vendorName" />
            <el-table-column label="质保期" align="center" prop="materialWarrantyPeriod" />
            <el-table-column label="库存" align="center" prop="inventory" />
            <el-table-column label="实盘数量" align="center" prop="checkNum" width="140px" />
            <!--        <el-table-column label="期间出库数量" align="center" prop="periodOutNum" width="140px" />-->
            <!--        <el-table-column label="结果数量" align="center" prop="resultNum" width="120px" />-->
            <el-table-column label="盘点结果" align="center" prop="resultState">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.check_info_state" :value="scope.row.resultState"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
  </div>
</template>

<script>
import {
  addMaterialCheck,
  delMaterialCheck,
  getMaterialCheck,
  listMaterialCheck, materialCheck,
  updateMaterialCheck
} from '@/api/business/materialCheck'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getCurrentDeptTree } from '@/api/business/unit'
import {listSiteWarehouse, listWarehouseAll} from '@/api/business/siteWarehouse'
import {customListAll, customListAllByWarehouseId, listMaterial} from '@/api/business/material'
import { formatDate } from '@/utils'

export default {
  name: "MaterialCheck",
  components: { Treeselect },
  dicts: ['check_state', 'check_type', 'check_state', 'check_info_state', 'material_unit'],
  data() {
    return {
      activeName: 'all',
      // 按钮loading
      materialLoading: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      infoLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资盘点表格数据
      materialCheckList: [],
      deptTreeData: [],
      warehouseList: [],
      warehouseId: undefined,
      tempSelection: [],
      // 物料列表
      materialList: [],
      materialTotal: 0,
      queryMaterialParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: undefined,
        materialName: undefined,
        materialSpecifications: undefined,
        vendorName: undefined,
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: undefined,
        taskName: undefined,
        taskUserId: undefined,
        taskUserName: undefined,
        taskStartTime: undefined,
        taskEndTime: undefined,
        warehouseId: undefined,
        warehouseName: undefined,
        checkType: undefined,
        checkState: undefined,
        deptId: undefined,
        deptName: undefined,
        createDeptId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        taskUserId: [
          { required: true, message: "任务执行人不能为空", trigger: "blur" }
        ],
        taskStartTime: [
          { required: true, message: "任务开始时间不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        checkType: [
          { required: true, message: "盘点类型不能为空", trigger: "change" }
        ],
        deptId: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物资盘点列表 */
    getList() {
      this.loading = true;
      listMaterialCheck(this.queryParams).then(response => {
        this.materialCheckList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDeptTree(){
      getCurrentDeptTree().then(response => {
        this.deptTreeData = this.handleTree(response.data, "deptId")
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
        // isDisabled: node.level<4&&!node.children
      };
    },
    // 部门变更
    handleDeptChange(e){
      this.form.warehouseId = undefined
      this.warehouseList = []
      this.form.checkInfoList = []
      this.materialList = [];
      /** 查询仓库列表 */
      listWarehouseAll({ deptId: e.deptId }).then(response => {
        this.warehouseList = response.data;
      });
    },
    // 仓库变更
    warehouseChange(warehouseId) {
      this.infoLoading = true
      this.form.checkInfoList = []
      customListAll({ ...this.queryMaterialParams, warehouseId}).then(response => {
        this.materialList = response.rows;
        this.materialTotal = response.total;
        this.infoLoading = false
      });
    },
    // 盘点数量更改
    checkNumChange() {
      this.form.checkInfoList.forEach(item =>{
        // item.resultNum = item.checkNum - item.periodOutNum
        if (item.checkNum > item.inventory) {
          item.resultState = 1
        }else if (item.checkNum < item.inventory){
          item.resultState = 2
        }else {
          item.resultState = 3
        }
      })
    },
    // 期间出库数量更改
    periodOutNumChange() {
      this.form.checkInfoList.forEach(item =>{
        item.resultNum = item.checkNum - item.periodOutNum
        if (item.resultNum > 0) {
          item.resultState = 1
        }else if (item.resultNum < 0) {
          item.resultState = 2
        }else {
          item.resultState = 3
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        taskCode: undefined,
        taskName: undefined,
        taskUserId: undefined,
        taskUserName: undefined,
        taskStartTime: formatDate(new Date().getTime()),
        taskEndTime: undefined,
        warehouseId: undefined,
        warehouseName: undefined,
        checkType: undefined,
        checkState: undefined,
        deptId: undefined,
        deptName: undefined,
        remark: undefined,
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        updateBy: undefined,
        updateTime: undefined,
        createDeptId: undefined,
        checkInfoList: [],
        checkInfoJustList: [],
        checkInfoLoseList: []
      };
      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
    },

    /** 打开物料列表 */
    openMaterialModel() {
      if (!this.form.warehouseId) {
        this.$modal.msgError("请先选择要盘点的仓库");
        return
      }
      this.open2 = true
      this.getMaterialList()
    },
    /* 初始化 */
    openMaterialInit() {
      if (!this.form.warehouseId) {
        this.$modal.msgError("请先选择要盘点的仓库");
      }
      customListAllByWarehouseId({warehouseId: this.form.warehouseId}).then(response => {
        this.form.checkInfoList = response.data;
      })
    },
    /** 搜索按钮操作 */
    handleMaterialQuery() {
      this.queryMaterialParams.pageNum = 1;
      this.getMaterialList();
    },
    /** 重置按钮操作 */
    resetMaterialQuery() {
      this.resetForm("queryMaterialForm");
      this.handleMaterialQuery();
    },
    /** 查询物资列表 */
    getMaterialList() {
      this.materialLoading = true;
      customListAll({ ...this.queryMaterialParams, warehouseId: this.form.warehouseId }).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.checkInfoList.some(item => item.materialId === row.materialId);
            this.$refs.selectionTable.toggleRowSelection(row, isSelected);
          });
        });
      })
    },
    // 多选框选中数据
    handleMaterialSelectionChange(selection) {
      this.tempSelection = selection
      console.log('tempSelection', this.tempSelection)
    },
    /* 确定选中数据 */
    confirmSelection() {
      this.tempSelection.forEach(item => {
        if (!this.form.checkInfoList.some(existing => existing.materialId === item.materialId)) {
          this.form.checkInfoList.push(item);
        }
      });
      this.open2 = false;
    },
    /* 移除按钮操作 */
    handleRowDelete(row) {
      this.form.checkInfoList = this.form.checkInfoList.filter(item =>{
        return item.materialId !== row.materialId
      })
    },
    // 取消按钮
    cancelMaterial() {
      this.open2 = false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物资盘点";
      this.getDeptTree()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMaterialCheck(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改物资盘点";
        this.getDeptTree()
        /** 查询仓库列表 */
        listWarehouseAll({ deptId: this.form.deptId }).then(response => {
          this.warehouseList = response.data;
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let isTrue = false
          this.form.checkInfoList.forEach(item =>{
            if (!item.checkNum) {
              isTrue = true
            }
          })
          if (isTrue) {
            this.$modal.msgError("实盘数量不能为空");
            return
          }
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMaterialCheck(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialCheck(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      getMaterialCheck(row.id).then(response => {
        this.form = response.data;
        this.open1 = true;
        this.title = "物资盘点详情";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物资盘点编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialCheck(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 盘点结束按钮操作 */
    handleCheck(row) {
      this.$modal.confirm('是否确认结束物资盘点任务为"' + row.taskName + '"的数据项？').then(() => {
        this.loading = true;
        return materialCheck(row);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/materialCheck/export', {
        ...this.queryParams
      }, `盘点单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
