<template>
  <div class="app-container" id="devicesWarehousing">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" @submit.native.prevent>
      <el-form-item label="关键字" label-width="auto" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable maxlength="50"
          style="width: 240px"
          @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-button type="success" icon="el-icon-plus" size="mini" @click="handleNumberAdd">数量盘点</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" @click="handleCodeAdd">编码盘点</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="入库来源" align="center" prop="putInType" />
      <el-table-column label="工程名称" align="center" prop="projectName" :show-overflow-tooltip="true" />
      <el-table-column label="退料单位" align="center" prop="unitName" :show-overflow-tooltip="true" />
      <el-table-column label="单号" align="center" prop="kindName"  :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="设备/物资名称" align="center" prop="typeName"  :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="入库人" align="center" prop="modelName"  :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="入库日期" align="center" prop="createDate" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <!-- <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-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']"
          >审核</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="codeOpen" 
      width="90%" 
      append-to-body 
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form :model="codeForm" :rules="codeFormRules" ref="codeForm" size="small" :inline="true" v-show="showSearch">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="入库来源" label-width="130px" prop="putInType">
              <el-select
                v-model="codeForm.putInType"
                placeholder="请选择入库来源"
                filterable
                style="width: 220px"
                @change="changePutInType"
              >
                <el-option
                  v-for="item in codeInStoreOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备/物资类型" label-width="130px" prop="typeId">
              <el-cascader
                placeholder="请选择物品类型"
                :options="deviceTypeTree"
                :props="deviceTypeTreeProps"
                v-model="codeForm.typeId"
                @change="deviceTypeChange"
                ref="deviceTypeCascader"
                style="width: 400px;"
                clearable filterable
                :disabled="cascaderDisabled"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="待入库总数" label-width="130px" prop="num" v-if="!isNumCheck">
              <el-input-number
                v-model="codeForm.num"
                placeholder="请输入待入库总数"
                clearable
                :min="1"
                :max="99"
                :controls="false"
                style="width: 13vw;"
              />
            </el-form-item>
            
          </el-col>
          <el-col :span="7">
            <el-form-item label="备注" label-width="130px" prop="remarks" v-if="isNumCheck">
              <el-input
                v-model="codeForm.remarks"
                type="textarea"
                placeholder="请输入备注"
                maxlength="200"
                rows="3"
                show-word-limit
                style="width: 13vw;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="前缀" label-width="130px" prop="codePrefix" v-if="!isNumCheck">
              <el-input
                v-model="codeForm.codePrefix"
                placeholder="请输入前缀"
                clearable
                style="width: 220px"
              />
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="后缀范围" label-width="130px" prop="codeSuffixStart" v-if="!isNumCheck">
              <el-input
                v-model="codeForm.codeSuffixStart"
                clearable
                placeholder="请输入后缀范围起始值"
                style="width: 185px"
                @change="changeSuffixStart(codeForm.codeSuffixStart)"
              />
            </el-form-item>
            <el-form-item label="~" label-width="auto" prop="codeSuffixEnd" v-if="!isNumCheck">
              <el-input
                v-model="codeForm.codeSuffixEnd"
                clearable
                placeholder="请输入后缀范围结束值"
                style="width: 185px"
                @change="changeSuffixEnd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="单价" label-width="130px" prop="buyPrice" v-if="!isNumCheck">
              <el-input-number
                v-model="codeForm.buyPrice"
                :precision="2"
                placeholder="请输入单价"
                clearable
                :min="0"
                :controls="false"
                style="width: 13vw;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="选择厂家" label-width="130px" prop="codeFactory" v-if="!isNumCheck">
              <el-select
                v-model="codeForm.codeFactory"
                placeholder="请选择厂家"
                clearable filterable
                style="width: 220px"
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.supplierId"
                  :label="item.supplier"
                  :value="item.supplierId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="检验时间" label-width="130px" prop="thisCheckTime" v-if="!isNumCheck">
              <el-date-picker
                v-model="codeForm.thisCheckTime"
                type="date"
                placeholder="请输入检验时间"
                style="width: 400px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="下次检验时间" label-width="130px" prop="nextCheckTime" v-if="!isNumCheck">
              <el-date-picker
                v-model="codeForm.nextCheckTime"
                type="date"
                placeholder="请输入检验时间"
                style="width: 13vw;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="领料单位" label-width="130px" prop="unitId" v-show="isPutInType"
            :rules="{ required: isPutInType, message: '领料单位不能为空', trigger: 'change' }">
              <el-select v-model="codeForm.unitId" placeholder="请选择领料单位" style="width: 220px;" 
              @change="changeUnitData" clearable filterable>
                <el-option
                  v-for="item in unitList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="领料工程" label-width="130px" prop="proId" v-show="isPutInType"
            :rules="{ required: isPutInType, message: '领料工程不能为空', trigger: 'change' }">
              <el-select v-model="codeForm.proId" placeholder="请选择领料工程" style="width: 400px;" 
              @change="changeProList" clearable filterable>
                <el-option
                  v-for="item in proList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label=" " label-width="130px" v-show="isPutInType">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="fillCodeForm">点击填充</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="检验人" label-width="130px" prop="checkMan" v-if="!isNumCheck">
              <el-input v-model="codeForm.checkMan"  placeholder="请输入检验人" clearable style="width: 220px;" />
            </el-form-item>
          </el-col>
          
          <el-col :span="10">
            <el-form-item label="备注" label-width="130px" prop="remarks" v-if="!isNumCheck">
              <el-input
                v-model="codeForm.remarks"
                type="textarea"
                placeholder="请输入备注"
                maxlength="200"
                rows="4"
                show-word-limit
                style="width: 400px;"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="7">
            <el-form-item label=" " label-width="130px" v-show="!isPutInType">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="fillCodeForm">点击填充</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="multiple" 
          >批量通过</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="multiple" 
          >批量不通过</el-button>
        </el-col>
       <el-col :span="1.5">
         <el-button
           type="warning"
           plain
           icon="el-icon-download"
           size="mini"
           @click="handleExport"
           v-hasPermi="['system:dict:export']"
         >导出</el-button>
       </el-col>
      </el-row> -->
      <el-table v-loading="loading" :data="codeTableList" v-if="!isNumCheck" 
      @selection-change="handleSelectionChange" :stripe="true" :border="true">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true">
          <template v-slot:default="{ row }" v-if="!isNumCheck">
            <el-input v-model="row.maCode" placeholder="请输入设备编码"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="出厂编码" align="center" prop="outFacCode" :show-overflow-tooltip="true">
          <template v-slot:default="{ row }" v-if="!isNumCheck">
            <el-input v-model="row.outFacCode" placeholder="请输入出厂编码"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="生产厂家" align="center" prop="maVender" :show-overflow-tooltip="true">
          <template v-slot:default="{ row }" v-if="!isNumCheck">
            <el-select v-model="row.maVender" placeholder="请选择生产厂家" clearable filterable>
              <el-option
                v-for="item in supplierList"
                :key="item.supplierId"
                :label="item.supplier"
                :value="item.supplierId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="检验日期" align="center" prop="thisCheckTime" :show-overflow-tooltip="true">
          <template v-slot:default="{ row }" v-if="!isNumCheck">
            <el-date-picker
              v-model="row.thisCheckTime"
              type="date"
              placeholder="请输入检验时间"
              style="width: 170px"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="下次检验日期" align="center" prop="nextCheckTime" :show-overflow-tooltip="true">
          <template v-slot:default="{ row }" v-if="!isNumCheck">
            <el-date-picker
              v-model="row.nextCheckTime"
              type="date"
              placeholder="请输入下次检验时间"
              style="width: 170px"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="buyPrice" :show-overflow-tooltip="true">
          <template v-slot:default="{ row }" v-if="!isNumCheck">
            <el-input-number
              v-model="row.buyPrice"
              :precision="2"
              placeholder="请输入单价"
              :min="0"
              :controls="false"
              clearable
              style="width: 160px"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column> -->

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot:default="{ row }">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleResetRow(row)"
            >重置</el-button>
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)" 
            >不通过</el-button> -->
            <!--          <el-button-->
            <!--            size="mini"-->
            <!--            type="text"-->
            <!--            icon="el-icon-delete"-->
            <!--            @click="handleDelete(scope.row)"-->
            <!--            v-hasPermi="['system:dict:remove']"-->
            <!--          >删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <!-- 数量入库 -->
      <el-table v-loading="loading" :data="numTableList" border stripe v-if="isNumCheck">
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column prop="typeCn" label="设备名称" align="center" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="guigeCn" label="规格型号" align="center" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="num" label="当前库存" align="center" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="num" label="入库数量" align="center" :show-overflow-tooltip="true">
            <template v-slot:default="{ row }">
              <el-input-number v-model="row.putInStoreNum" placeholder="请输入入库数量" @blur="handlePutBlur(row)" 
              clearable :controls="false" :min="1" style="width: 10vw;" />
            </template>
          </el-table-column>
          <el-table-column prop="unitCn" label="计量单位" align="center" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true">
            <template v-slot:default="{ row }">
              <el-input v-model="row.remark" placeholder="请输入备注" align="center" :show-overflow-tooltip="true" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot:default="{ $index }">
              <el-popconfirm
                title="确定删除吗？"
                icon="el-icon-info"
                placement="top"
                @confirm="handleDeleteRow($index)"
                @cancel="cancelPop"
              >
                <el-button slot="reference" size="mini" type="text" icon="el-icon-delete">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelCode">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, refreshCache } from "@/api/system/dict/type";
import { 
  getReturnOfMaterialsInfoAll,
  getTypeList,
  getDeviceTypeTree,
  inputByCode
} from "@/api/store/putInStore";
import { getInfo } from '@/api/login'
import { supplierInfoList } from "@/api/store/tools";
import { getUnitData, getProData } from "@/api/claimAndRefund/receive";

export default {
  name: "DevicesWarehousing",
  // dicts: ['sys_normal_disable'],
  data() {
    return {
      // 用户信息
      user: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      typeList: [],
      modelList: [],
      // 表格数据
      returnList: [],
      // 编码盘点表格数据
      codeTableList: [],
      // 编码盘点表格数据
      numTableList: [],
      numTable: {},
      // 弹出层标题
      title: "",
      // 入库来源选项
      codeInStoreOptions: [
        { label: "库存盘点入库", value: "库存盘点入库" },
        { label: "退料入库", value: "退料入库" },
      ],
      // 是否显示弹出层
      numberOpen: false,
      codeOpen: false,
      // 日期范围
      dateRange: [],
      isNumCheck: false,
      isAdd: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: "",
      },
      // 级联框禁用
      cascaderDisabled: false,
      //机具厂家（供应商管理）
      supplierList: [],
      deviceTypeTree: [], // 设备 树结构数据
      // 设备 树显示 配置
      deviceTypeTreeProps: {
        multiple:false,
        value:'id'
      },
      // 选中的设备类型
      deviceType: null,
      // 领料集合
      leaseApplyDetails: [],
      //领料详情单条模板
      leaseApplyDetailsItem:{
        parentId:null,
        createBy: null,
        companyId: null,
        status: 0,
        typeId: null, //  树结构第4级   规格id
        typeCn:'', //显示的设备类型
        guigeCn:'', //显示的设备规格
        unitCn:'', //显示的设备 单位
        remark: '', //单条备注
        preNum: 1, //预领数量
      },
      // 领料单位
      unitList: [],
      // 领料工程
      proList: [],
      isPutInType: false,
      // 表单参数：编号表单 / 数量表单
      numberForm: {},
      codeForm: {
        checkMan: undefined,
        putInType: undefined,
        remarks: undefined,
        typeId: undefined,
        num: undefined,
        codePrefix: undefined,
        codeSuffixStart: undefined,
        codeSuffixEnd: undefined,
        buyPrice: undefined,
        codeFactory: undefined,
        thisCheckTime: undefined,
        nextCheckTime: undefined,
        unitId: null,
        proId: null,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单校验
      rules: {
        dictName: [
          { required: true, message: "字典名称不能为空", trigger: "blur" }
        ],
        dictType: [
          { required: true, message: "字典类型不能为空", trigger: "blur" }
        ]
      },
      codeFormRules: {
        putInType: [
          { required: true, message: "入库来源不能为空", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "设备/物资类型不能为空", trigger: "change" }
        ],
        num: [
          { required: true, message: "待入库总数不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTypeList();
    this.GetDeviceTypeTree();
    this.supplierInfoList();
  },
  methods: {//
    // 获取用户信息
    async GetUserInfo(){
      const res = await getInfo()
      console.log(res, '用户信息')
      this.user = res.user
    },
    /** 查询字典类型列表 */
    getTypeList() {
      getTypeList({level:'3'}).then(response => {
          this.typeList = response.data;
        }
      );
      getTypeList({level:'4'}).then(response => {
          this.modelList = response.data;
        }
      );
    },


    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getReturnOfMaterialsInfoAll(this.queryParams).then(response => {
          this.returnList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消编码盘点按钮
    cancelCode() {
      this.cascaderDisabled = false
      this.resetCodeForm();
      this.deviceType = {}
      this.reset();
      this.codeTableList = []
      this.numTableList = []
      this.$refs['codeForm'].clearValidate()
      this.codeOpen = false;
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    // 编码表单重置
    resetCodeForm() {
      this.codeForm = {
        checkMan: undefined,
        putInType: null,
        remarks: undefined,
        typeId: null,
        num: undefined,
        codePrefix: undefined,
        codeSuffixStart: undefined,
        codeSuffixEnd: undefined,
        buyPrice: undefined,
        codeFactory: undefined,
        thisCheckTime: undefined,
        nextCheckTime: undefined,
        pageNum: 1,
        pageSize: 10,
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 填充编码盘点表单 */
    fillCodeForm() {
      console.log('🚀 ~ fillCodeForm ~ this.isNumCheck:', this.isNumCheck);
      // 校验表单
      this.$refs['codeForm'].validate(valid => {
        if (!valid) return
        console.log('🚀 ~ fillCodeForm ~ this.codeForm:', this.codeForm);
        // 清空this.codeTableList
        this.codeTableList = []
        if (this.isNumCheck) {
          // 判断 this.numTableList 中是否有 this.numTable 的数据, 如果有, 则不添加
          if (this.numTableList.some(item => item.typeId == this.codeForm.typeId)) {
            this.$message.warning('请勿重复添加')
            return
          }
          console.log('🚀 ~ fillCodeForm ~ this.numTable:', this.numTable);
          this.numTableList.push(this.numTable)
        } else {
          // 根据this.codeForm.num的数量, 往this.codeTableList中添加this.codeForm的数据
          for (let i = 0; i < this.codeForm.num; i++) {
            // 设备编码: 前缀 拼接 后缀
            let suffix = parseInt(this.codeForm.codeSuffixStart) + i
            if (suffix > parseInt(this.codeForm.codeSuffixEnd)) {
              suffix = parseInt(this.codeForm.codeSuffixEnd)
            }
            suffix = suffix.toString().padStart(this.codeForm.codeSuffixStart?.length, '0')
            // console.log('🚀 ~ fillCodeForm ~ suffix:', suffix);
            suffix = isNaN(suffix) ? '' : suffix
            const maCode = `${this.codeForm.codePrefix || ''}${suffix}`
            // 出厂编码
            const outFacCode = ''
            // 生产厂家
            const maVender = this.supplierList.find(item => item.supplierId == this.codeForm.codeFactory)?.supplier || ''
            // 检验日期: codeForm.thisCheckTime
            const thisCheckTime = this.codeForm.thisCheckTime
            // 下次检验日期: codeForm.nextCheckTime
            const nextCheckTime = this.codeForm.nextCheckTime
            // 单价: codeForm.buyPrice
            const buyPrice = this.codeForm.buyPrice || 0
            this.codeTableList.push({
              maCode,
              outFacCode,
              maVender,
              thisCheckTime,
              nextCheckTime,
              buyPrice
            })
          }
        }
      })
    },
    /** 输入框改变 */
    changeSuffixStart(num) {
      if (isNaN(num)) {
        this.$message.error('后缀范围请输入数字类型')
        this.codeForm.codeSuffixStart = this.codeForm.codeSuffixStart.replace(/[^\d]/g, '')
      }
      if (!this.codeForm.codeSuffixStart) {
        this.codeForm.codeSuffixEnd = ''
      }
    },
    changeSuffixEnd() {
      if (!this.codeForm.codeSuffixStart) {
        this.$message.error('请输入后缀范围起始值')
        this.codeForm.codeSuffixEnd = ''
      } else if (isNaN(this.codeForm.codeSuffixEnd)) {
        this.$message.error('后缀范围请输入数字类型')
        this.codeForm.codeSuffixEnd = this.codeForm.codeSuffixStart.replace(/[^\d]/g, '')
      } else {
        if (parseInt(this.codeForm.codeSuffixStart) > parseInt(this.codeForm.codeSuffixEnd)) {
          this.$message.error('后缀结束值不能小于起始值')
          this.codeForm.codeSuffixEnd = +this.codeForm.codeSuffixStart + 1
        }
      }
    },

    handleResetRow(row) {
      // 重置当前行所有数据为空
      row.maCode = ''
      row.outFacCode = ''
      row.maVender = ''
      row.thisCheckTime = ''
      row.nextCheckTime = ''
      row.buyPrice = 0

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增数量盘点按钮操作 */
    handleNumberAdd() {
      this.isNumCheck = true;
      this.isPutInType = false;
      this.reset();
      this.codeOpen = true;
      this.title = "数量盘点入库";
      this.resetCodeForm()
      this.getUnitData();
      this.$nextTick(() => {
        this.$refs['codeForm'].clearValidate()
      })
    },
    /** 新增编号盘点按钮操作 */
    handleCodeAdd() {
      this.isNumCheck = false;
      this.isPutInType = false;
      this.reset();
      this.codeOpen = true;
      this.title = "编码盘点入库";
      this.resetCodeForm()
      this.getUnitData();
      this.$nextTick(() => {
        this.$refs['codeForm'].clearValidate()
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dictId = row.dictId || this.ids
      getType(dictId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改字典类型";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['codeForm'].validate(valid => {
        if (valid) {
          let SavePutInfoDto = {}
          // console.log('🚀 ~ this.codeForm:', this.codeForm);
          // console.log('🚀 ~ this.numTableList:', this.numTableList);
          // console.log('🚀 ~ this.codeTableList:', this.codeTableList);
          if (this.isNumCheck) {
            // 提交数据
            SavePutInfoDto = {
              isCode: false,
              putInType: this.codeForm.putInType,
              remarks: this.codeForm.remarks || '',
              machIneDtoList: this.numTableList,
              unitId: this.codeForm.unitId,
              proId: this.codeForm.proId,
            }
            console.log('🚀 ~ submitForm: ~ SavePutInfoDto-isNum', SavePutInfoDto)
            // 发送请求
            inputByCode(SavePutInfoDto).then(response => {
              this.$message.success('入库成功')
              this.resetCodeForm()
              this.numTableList = []
              this.codeOpen = false
              this.reset()
              this.getList()
            })
          } else {
            // 统一处理时间格式为 yyyy-MM-dd
            this.codeTableList.forEach(item => {
              if (item.thisCheckTime) {
                item.thisCheckTime = new Date(item.thisCheckTime).toLocaleDateString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'}).replace(/\//g, '-')
              } else {
                item.thisCheckTime = ''
              }
              if (item.nextCheckTime) {
                item.nextCheckTime = new Date(item.nextCheckTime).toLocaleDateString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'}).replace(/\//g, '-')
              } else {
                item.nextCheckTime = ''
              }
            })
            // 提交数据
            SavePutInfoDto = {
              isCode: true, // 是否编码盘点
              putInType: this.codeForm.putInType,
              typeId: this.codeForm.typeId,
              num: this.codeForm.num,
              remarks: this.codeForm.remarks || '',
              machIneDtoList: this.codeTableList,
              checkMan: this.codeForm.checkMan || '',
              unitId: this.codeForm.unitId,
              proId: this.codeForm.proId,
            }
            console.log('🚀 ~ submitForm: ~ SavePutInfoDto', SavePutInfoDto)
            
            if (this.codeTableList.length == 0) {
              this.$message.error('请点击填充按钮, 填充数据')
              return
            }
            
            // 发送请求
            inputByCode(SavePutInfoDto).then(response => {
              this.$message.success('入库成功')
              this.resetCodeForm()
              this.codeTableList = []
              this.codeOpen = false
              this.reset()
              this.getList()
            })
          }
        }
      })
      /* this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dictId != undefined) {
            updateType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      }); */
    },
    // 入库数量输入框失去焦点
    handlePutBlur(row) {
      if (!row.putInStoreNum) {
        this.$message.warning('入库数量不能为空')
        row.putInStoreNum = 1
      }
    },
    // 删除行
    handleDeleteRow(index) {
      this.numTableList.splice(index, 1)
      setTimeout(() => {
        this.$message.success('删除成功')
      }, 50)
    },
    cancelPop() {
      this.$message.info('取消删除')
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.dictId || this.ids;
      this.$modal.confirm('是否确认删除字典编号为"' + dictIds + '"的数据项？').then(function() {
        return delType(dictIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material/returnOfMaterialsInfo/export', {
        ...this.queryParams
      }, `机具退料入库_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
        this.$store.dispatch('dict/cleanDict');
      });
    },
    // 获取 设备树结构数据
    async GetDeviceTypeTree(){
      const params = {
        level:4
      }
      const res = await getDeviceTypeTree(params)
      console.log(res)
      this.deviceTypeTree = res.data
    },
    /////// 设备类型树  切换
    deviceTypeChange(val){
      console.log('🚀 ~ deviceTypeChange ~ val:', val);
      // this.cascaderDisabled = true
      let nodes = null;
      nodes = this.$refs.deviceTypeCascader.getCheckedNodes().length > 0 ? this.$refs.deviceTypeCascader.getCheckedNodes() : [this.$refs.deviceTypeCascader.panel.getNodeByValue(val)]
      if(nodes[0].level != 4){
        return
      }
      console.log('🚀 ~ deviceTypeChange ~ nodes[0]:', nodes[0]);
      for(let i = 0; i < this.leaseApplyDetails.length; i++) {
            if (this.leaseApplyDetails[i].typeId == nodes[0].data.id) {
                this.leaseApplyDetails.splice(i,1)
                break;
            }
      }
      this.leaseApplyDetails.push(
        this.handelTableItemData(nodes[0])
      )
      console.log('🚀 ~ deviceTypeChange ~ this.leaseApplyDetails:', this.leaseApplyDetails);
      // this.deviceType = {} 

      this.numTable = this.handelTableItemData(nodes[0])
    },
    //// 将数据处理成 表格中需要的数据
    handelTableItemData(node){
      const template = JSON.parse(JSON.stringify(this.leaseApplyDetailsItem))
      // template.createBy = this.user.name
      console.log('🚀 ~ handelTableItemData ~ node.data, node.data.id:', node.data, node.data.id, node);
      this.codeForm.typeId = node.data.id
      template.num = node.data.num
      template.companyId = node.data.companyId
      template.typeId = node.data.id
      template.unitCn = node.data.unitName
      template.typeCn = node.pathLabels[2]
      template.guigeCn = node.pathLabels[3]
      template.putInStoreNum = 1

      if(this.taskId){
        const index = this.leaseApplyInfoList.find(key => key.companyId == node.data.companyId)
        template.parentId = index ? index.id : ''
      }
      console.log('🚀 ~ handelTableItemData ~ template:', template);

      return template
    },
    /** 机具厂家 */
    supplierInfoList() {
      supplierInfoList().then(response => {
        this.supplierList = response.rows;
        }
      );
    },
    changePutInType(val) {
      if (val == '退料入库') {
        this.isPutInType = true
      } else {
        this.isPutInType = false
        this.$nextTick(() => {
          this.$set(this.codeForm, 'unitId', null)
          this.$set(this.codeForm, 'proId', null)
        })
      }
    },
    // 领料单位
    async getUnitData() {
      try {
        const res = await getUnitData()
        this.unitList = res.data
      } catch (error) {
        console.log('🚀 ~ getUnitData ~ error:', error)
      }
    },
    changeUnitData(val) {
      // console.log('🚀 ~ changeUnitData ~ val:', val);
      this.codeForm.unitId = val
      this.proList = []
      this.$set(this.codeForm, 'proId', null)
      if(val) {
        this.getProList()
      }
    },
    async getProList() {
      const unitId = this.codeForm.unitId
      // 领料工程
      try {
        const res = await getProData({id: unitId})
        // console.log('🚀 ~ changeUnitData ~ data:', res.data);
        this.proList = res.data
        if (res.data.length == 0) {
          this.proList = []
          this.codeForm.proId = null
        } else {
          this.proList = res.data
        }
        // console.log('🚀 ~ changeUnitData ~ this.proList:', this.proList);
      } catch (error) {
        console.log('🚀 ~ changeUnitData ~ error:', error)
      }
    },
    changeProList(val) {
      this.codeForm.proId = val
      // console.log('🚀 ~ changeProList ~ this.codeForm:', this.codeForm.proId);
    }
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}
::v-deep.el-form-item__label {
  padding: 0 20px !important;
}
</style>