<template>
    <div class="app-container" >
        <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"
            border
        >
            <el-table-column
                align="center"
                label="序号"
                type="index"
                :index="
                    indexContinuation(queryParams.pageNum, queryParams.pageSize)
                "
            />
            <el-table-column label="入库来源" align="center" prop="putInType" />
            <el-table-column
                label="单号"
                align="center"
                prop="code"
                :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
                label="机具名称"
                align="center"
                prop="kindName"
                :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">
                <template slot-scope="{ row }">
                    <el-button
                        type="text"
                        size="mini"
                        @click="queryDetails(row)"
                        >查看</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"

                            >
                                <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="100"
                                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
                                maxlength="20"
                                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="请输入后缀起始值"
                                maxlength="99999999"
                                style="width: 400px"
                            />
                        </el-form-item>
                        <!-- <el-form-item
                            label="~"
                            label-width="auto"
                            prop="codeSuffixEnd"
                            v-if="!isNumCheck"
                        >
                            <el-input
                                v-model="codeForm.codeSuffixEnd"
                                clearable
                                placeholder="请输入后缀范围结束值"
                                maxlength="10"
                                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"
                                :max="999999999"
                                :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"
                                @change="changeCheckTime"
                            />
                        </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"
                                :disabled="!codeForm.thisCheckTime"
                                :picker-options="{
                                    disabledDate(time) {
                                        if (codeForm.thisCheckTime) {
                                            let today = new Date()
                                            today.setHours(0, 0, 0, 0)
                                            return (
                                                time.getTime() <
                                                    today.getTime() ||
                                                time.getTime() <
                                                    new Date(
                                                        codeForm.thisCheckTime,
                                                    ).getTime()
                                            )
                                        }
                                        return false
                                    },
                                }"
                            />
                        </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
                                maxlength="20"
                                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="100"
                                rows="1"
                                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"
                height="400"
                :stripe="true"
            >
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column
                    label="序号"
                    align="center"
                    width="80"
                    type="index"
                /> -->
                <el-table-column
                    align="center"
                    prop="maCode"
                    :show-overflow-tooltip="true"
                >
                    <template v-slot:header>
                        <span style="color: red">* </span>设备编码
                    </template>
                    <template v-slot:default="{ row }" v-if="!isNumCheck">
                        <el-input
                            v-model="row.maCode"
                            placeholder="请输入设备编码"
                            maxlength="30"
                            @blur="handleMaCodeBlur(row)"
                        ></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="请输入出厂编码"
                            maxlength="30"
                        ></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"
                            @change="changeCheckTimeRow(row)"
                        ></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"
                            :disabled="!row.thisCheckTime"
                            :picker-options="{
                                disabledDate(time) {
                                    if (row.thisCheckTime) {
                                        let today = new Date()
                                        today.setHours(0, 0, 0, 0)
                                        return (
                                            time.getTime() < today.getTime() ||
                                            time.getTime() <
                                                new Date(
                                                    row.thisCheckTime,
                                                ).getTime()
                                        )
                                    }
                                    return false
                                },
                            }"
                        ></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"
                            :max="999999999"
                            :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"
                stripe
                v-if="isNumCheck"
            >
                <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"
                            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
                            maxlength="100"
                        ></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>


        <el-dialog :title="dialogTitle" :visible.sync="openRecord" width="1200px" append-to-body @close="closeDialog">
        <el-form :model="dialogQuery" ref="dialogQuery" size="small" :inline="true" label-width="80px">
          <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="dialogQuery.keyWord"
            placeholder="请输入关键字"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              icon="el-icon-search" size="mini"
              @click="handleDialogQuery"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
             <el-button
               icon="el-icon-refresh"
               size="mini"
               @click="resetDialogQuery"
             >重置</el-button>
           </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dialogList">
          <el-table-column label="序号" align="center" width="80" type="index" :index="indexContinuation(dialogQuery.pageNum, dialogQuery.pageSize)">
          </el-table-column>
          <el-table-column label="入库来源" align="center" prop="putInType" :show-overflow-tooltip="true"/>
          <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
          <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
          <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true"/>
          <el-table-column label="入库数量" align="center" prop="num" :show-overflow-tooltip="true"/>
          <el-table-column label="入库人" align="center" prop="modelName" :show-overflow-tooltip="true"/>
          <el-table-column label="入库日期" align="center" prop="createDate" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
        </el-table>
          <pagination
            v-show="dialogTotal > 0"
            :total="dialogTotal"
            :page.sync="dialogQuery.pageNum"
            :limit.sync="dialogQuery.pageSize"
            @pagination="getDetailsList"
          />
      </el-dialog>
    </div>
</template>

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

// import DialogModel from '@/components/DialogModel'
// import TableMode from '@/components/TableModel'
// import { dialogConfig } from './config'

export default {
    name: 'Inventory',
    // 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: 0 },
            ],
            // 是否显示弹出层
            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: 'PD-CODE',
                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: {
                codePrefix: [
                    { required: true, message: '请输入前缀', trigger: 'blur' },
                ],
                codeSuffixStart: [
                    {
                        required: true,
                        message: '请输入后缀起始值',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^[0-9]+[1-9][0-9]*$|^[1-9][0-9]*$|^0+[1-9][0-9]*$/,
                        message: '请输入有效的数字串（不能只输入0）',
                    },
                ],
                putInType: [
                    {
                        required: true,
                        message: '入库来源不能为空',
                        trigger: 'change',
                    },
                ],
                typeId: [
                    {
                        required: true,
                        message: '规格型号不能为空',
                        trigger: 'change',
                    },
                ],
                num: [
                    {
                        required: true,
                        message: '待入库总数不能为空',
                        trigger: 'blur',
                    },
                ],
            },

            sendParams: {},
            requiredMaCode: false,
            dialogQuery: {
                keyWord: '', //关键字
                pageNum: 1, //页码
                pageSize: 10, //每页显示条数
            },
            dialogList: [], //详情列表
            dialogTotal: 0, //详情列表总条数
            openRecord: false, //详情弹框
            dialogTitle: '查看详情', //详情弹框标题
        }
    },
    created() {
        this.getList()
        // this.getTypeList()
        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: 'PD-CODE',
                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++) {
                        // 保留原始格式的前缀长度
                        const prefixLength = this.codeForm.codeSuffixStart?.length || 1
                        // 计算当前序号，保留原始数字值
                        const originalNum = parseInt(this.codeForm.codeSuffixStart)
                        const currentNum = originalNum + i
                        
                        // 格式化序号，保持用户输入的位数
                        let suffix = currentNum.toString().padStart(prefixLength, '0')
                        
                        // 确保不超过结束值
                        if (this.codeForm.codeSuffixEnd) {
                            const endNum = parseInt(this.codeForm.codeSuffixEnd)
                            if (currentNum > endNum) {
                                suffix = endNum.toString().padStart(prefixLength, '0')
                            }
                        }
                        
                        // 生成设备编码
                        const maCode = `${this.codeForm.codePrefix || ''}${suffix}`
                        // 出厂编码
                        const outFacCode = ''
                        // 生产厂家
                        const maVender =
                            this.supplierList.find(
                                (item) =>
                                    item.supplierId ==
                                    this.codeForm.codeFactory,
                            )?.supplierId || ''
                        // 检验日期: 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: maCode,
                            outFacCode,
                            maVender,
                            thisCheckTime,
                            nextCheckTime,
                            buyPrice,
                        })
                    }
                }
            })
        },
        /** 输入框改变 */
        changeSuffixStart(num) {
            if (isNaN(num)) {
                this.$message.error('后缀范围请输入数字类型')
                this.codeForm.codeSuffixStart = ''
            }
            // 只保留数字字符，允许前导零
            if (num) {
                this.codeForm.codeSuffixStart = num.replace(/[^\d]/g, '')
            }
        },
        changeSuffixEnd() {
            if (!this.codeForm.codeSuffixStart) {
                this.$message.error('请输入后缀范围起始值')
                this.codeForm.codeSuffixEnd = ''
            } else if (
                isNaN(this.codeForm.codeSuffixEnd) ||
                this.codeForm.codeSuffixEnd.includes('.')
            ) {
                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.GetDeviceTypeTree(this.isNumCheck)
            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.GetDeviceTypeTree(this.isNumCheck)
            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,
                        }
                        console.log("xxxxxxxxxxx",SavePutInfoDto)
                        // 发送请求
                        inputByCode(SavePutInfoDto).then((response) => {
                            this.$message.success('入库成功')
                            this.resetCodeForm()
                            this.numTableList = []
                            this.codeOpen = false
                            this.reset()
                            this.getList()
                        })
                    } else {
                        // this.codeTableList 中只要有一个maCode为空, 则不允许提交
                        this.requiredMaCode = this.codeTableList.some(
                            (item) => !item.maCode,
                        )
                        // 过滤this.codeTableList中 如果有maCode是重复数据, 则不允许提交
                        const maCodeList = this.codeTableList.map(
                            (item) => item.maCode,
                        )
                        if (new Set(maCodeList).size !== maCodeList.length) {
                            this.$message.error('设备编码不能重复')
                            return
                        }
                        if (this.requiredMaCode) {
                            this.$message.error('设备编码不能为空')
                            return
                        }
                        // 统一处理时间格式为 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 || '',
                        }
                        console.log(
                            '🚀 ~ submitForm: ~ SavePutInfoDto',
                            SavePutInfoDto,
                        )

                        if (this.codeTableList.length == 0) {
                            this.$message.error('请点击填充按钮, 填充数据')
                            return
                        }
                        console.log("xxxxxxxxxxx",SavePutInfoDto)
                        // // 发送请求
                        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) {
            console.log('🚀 ~ handlePutBlur ~ rowxxxxxxxxxxxxxxxxx:', row)
            if (!row.putInStoreNum) {
                this.$message.warning('入库数量不能为空')
                row.putInStoreNum = 1
            }

            // 根据计量单位类型决定是否允许小数
            if (row.unitValue == 1) {
                console.log("yyyyyyyyyyyyyy")
                // 允许小数：移除非数字和小数点的字符
                row.putInStoreNum = Number(String(row.putInStoreNum).replace(/[^\d.]/g, ''))
            } else {
                console.log("zzzzzzzzzzzzzz")
                // 不允许小数：只保留数字字符
                row.putInStoreNum = Number(String(row.putInStoreNum).replace(/[^\d]/g, ''))
            }
            // 确保数量不小于0
            if (row.putInStoreNum <= 0) {
                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('是否确认所选择的数据项？')
                .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(type) {
            const params = {
                level: 4,
            }
            const res = await getDeviceTypeTree(params)
            if (type) {
                this.disableNodes(res.data, '1')
            } else {
                this.disableNodes(res.data, '0')
            }
            this.deviceTypeTree = res.data
        },
        // 递归禁用节点
        disableNodes(nodes, manageType, level = 1) {
            nodes.forEach((node) => {
                node.level = level
                if (node.children) {
                    this.disableNodes(node.children, manageType, level + 1)
                } else if (!node.children && node.level < 4) {
                    node.disabled = true
                } else if (
                    node.manageType &&
                    node.level == 4 &&
                    node.manageType != manageType
                ) {
                    node.disabled = true
                }
            })
        },
        /////// 设备类型树  切换
        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)]
            nodes = [this.$refs.deviceTypeCascader.panel.getNodeByValue(val)]
            console.log("xxxxxxxx",nodes)
            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.unitValue = node.data.unitValue
            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);
        },

        /**
         * -----------------------------------------------------------------------------------------------------------------------------
         */
        /* 查看详情 */
        queryDetails(row) {
            // this.sendParams.kindName = row.kindName
            this.dialogQuery.infoId = row.id
            this.dialogQuery.pageNum = 1
            this.getDetailsList()
            this.openRecord = true
            
        },

        getDetailsList() {
            getDetailsListApi(this.dialogQuery).then((response) => {
                this.dialogList = response.rows
                this.dialogTotal = response.total
            })
        },

        handleDialogQuery() {
            this.dialogQuery.pageNum = 1
            this.getDetailsList()
        },

        resetDialogQuery() {
            this.dialogQuery.keyWord = ''
            this.handleDialogQuery()
        },

        closeDialog() {
            this.openRecord = false
            this.dialogList = []
            this.dialogTotal = 0
            this.dialogQuery = {
                pageNum: 1,
                pageSize: 10,
                keyWord: '',
                infoId: '',
            }
        },


        handleMaCodeBlur(row) {
            if (!row.maCode) {
                this.$message.warning('设备编码不能为空')
            }
        },
        // 校验检验日期
        changeCheckTime() {
            if (
                this.codeForm.nextCheckTime &&
                this.codeForm.thisCheckTime > this.codeForm.nextCheckTime
            ) {
                this.codeForm.nextCheckTime = ''
                this.$message.warning('下次检验日期不能早于检验日期!')
            } else if (!this.codeForm.thisCheckTime) {
                this.codeForm.nextCheckTime = ''
            }
        },
        changeCheckTimeRow(row) {
            if (row.nextCheckTime && row.thisCheckTime > row.nextCheckTime) {
                row.nextCheckTime = ''
                this.$message.warning('下次检验日期不能早于检验日期!')
            } else if (!row.thisCheckTime) {
                row.nextCheckTime = ''
            }
        },
    },
}
</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;
}
::v-deep .el-input-number.is-without-controls .el-input__inner {
    text-align: start;
}
</style>
