<template>
  <!-- 类型管理 -->
  <div class="app-container" id="toolsType">
    <el-row :gutter="20">
      <!--树数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="typeName"
            placeholder="请输入类型名称"
            clearable
            maxlength="50"
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style>
          <el-tree
            style="height: 700px; overflow: scroll"
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :default-expand-all="true"
            highlight-current
            @node-click="handleNodeClick"
          >
            <span
              class="custom-tree-node"
              slot-scope="{ node, data }"
              @mousemove="onMousemove(data)"
              @mouseleave="onMouseleave()"
            >
              <span v-if="isMousemoveId === data.id && node.label.length > 5">{{
                  node.label.slice(0, 3) + "..."
                }}</span>
              <span v-else>{{ node.label }}</span>

              <span class="btn-items" v-if="isMousemoveId === data.id">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  @click.stop="() => appendTreeNode(data)"
                >
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit-outline"
                  style="color: #67c23a"
                  v-if="data.id !== 0"
                  @click.stop="() => editTreeNode(data)"
                >
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  style="color: #f56c6c"
                  v-if="data.id !== 0  && data.level !== 0"
                  @click.stop="() => removeTreeNode(data)"
                >
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="关键字" prop="keyword">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入关键字"
              clearable
              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-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="typeList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column label="序号" align="center" width="80" type="index">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="类型编码"
            align="center"
            key="typeCode"
            prop="typeCode"
            show-overflow-tooltip
            v-if="false"
          />
          <el-table-column
            label="仓库信息"
            align="center"
            key="houseName"
            prop="houseName"
            show-overflow-tooltip
            v-if="false"
          />
          <el-table-column
            label="施工类型"
            align="center"
            key="itemType"
            prop="itemType"
            show-overflow-tooltip
          />
          <el-table-column
            label="物资类型"
            align="center"
            key="materialType"
            prop="materialType"
            show-overflow-tooltip
          />
          <el-table-column
            label="物资名称"
            align="center"
            key="materialName"
            prop="materialName"
            show-overflow-tooltip
          />
          <el-table-column
            label="规格型号"
            align="center"
            key="typeName"
            prop="typeName"
            show-overflow-tooltip
          >
          </el-table-column>

          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleView(scope.row)"
                v-hasPermi="['ma:type:query']"
              >
                查看
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['ma:type:edit']"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.manageType == 1"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="updateStorageNum(scope.row)"
                v-hasPermi="['ma:type:edit']"
              >
                修改库存
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['ma:type:remove']"
              >
                删除
              </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-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1300px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库信息">
              <!-- <el-select
                                v-model="form.keeperData"
                                filterable
                                placeholder="请选择仓库信息"
                                style="width: 100%"
                                :disabled="isLevel1Disabled"
                            > -->
              <el-input
                v-model="form.houseName"
                type="text"
                placeholder="请输入仓库信息"
                maxlength="99"
                :disabled="isLevel1Disabled"
              />
              <!-- <el-option
                                    v-for="keeper in keeperDataRange"
                                    :key="keeper.value"
                                    :label="keeper.label"
                                    :value="keeper.value"
                                ></el-option> -->

              <!-- </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="施工类型">
              <el-input
                v-model="form.itemType"
                type="text"
                placeholder="请输入施工类型"
                maxlength="99"
                :disabled="isLevel2Disabled"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物资类型">
              <el-input
                v-model="form.materialType"
                type="text"
                placeholder="请输入物资类型"
                maxlength="99"
                :disabled="isLevel3Disabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物资名称">
              <el-input
                v-model="form.materialName"
                type="text"
                placeholder="请输入物资名称"
                maxlength="99"
                :disabled="isLevel4Disabled"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="typeName">
              <el-input
                v-model="form.typeName"
                type="text"
                placeholder="请输入规格型号"
                maxlength="200"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="管理模式" prop="manageType">
              <el-select
                v-model="form.manageType"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option value="0" label="编码管理">编码管理</el-option>
                <el-option value="1" label="数量管理">数量管理</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unitName">
              <el-input
                v-model="form.unitName"
                type="text"
                placeholder="请输入计量单位"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量数值" prop="unitValue">
              <el-select
                v-model="form.unitValue"
                filterable
                placeholder="请选择计量数值"
                style="width: 100%"
              >
                <el-option
                  v-for="item in unitValueOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="是否扣税" prop="isCharging">
              <el-select
                v-model="form.isCharging"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option value="0" label="扣税">扣税</el-option>
                <el-option value="1" label="不扣税">不扣税</el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <!-- <el-row>
          <el-col :span="8">
            <el-form-item label="总保有量" prop="name9">
              <el-input
                v-model="form.name9"
                type="number" :min="0"
                placeholder="请输入总保有量"
                maxlength="20"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在库数量" prop="name8">
              <el-input
                v-model="form.name8"
                type="number" :min="0"
                placeholder="请输入在库数量"
                maxlength="20"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在用数量" prop="name7">
              <el-input
                v-model="form.name7"
                type="number" :min="0"
                placeholder="请输入在用数量"
                maxlength="20"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="在修数量" prop="name6">
              <el-input
                v-model="form.name6"
                type="number" :min="0"
                placeholder="请输入在修数量"
                maxlength="20"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="待报废数量" prop="name5">
              <el-input
                v-model="form.name5"
                type="number" :min="0"
                placeholder="请输入待报废数量"
                maxlength="20"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="丢失数量" prop="name4">
              <el-input
                v-model="form.name4"
                type="number" :min="0"
                placeholder="请输入丢失数量"
                maxlength="20"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row>
          <el-col :span="12">
            <el-form-item
              label="内部租赁价(元/天)"
              prop="leasePrice"
              label-width="140px"
            >
              <el-input-number
                v-model="form.leasePrice"
                placeholder="请输入"
                maxlength="20"
                controls-position="right"
                :min="0" :max="999999999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="购置价(元/不含税)"
              prop="buyPrice"
              label-width="140px"
            >
              <el-input-number
                v-model="form.buyPrice"
                placeholder="请输入"
                controls-position="right"
                :min="0" :max="999999999999999"
                maxlength="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="赔偿价(元)" prop="payPrice" label-width="120px">
              <el-input
                v-model="form.payPrice"
                placeholder="请输入"
                maxlength="20"
                type="number" :min="0"
                style="width: 170px"
              />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item
              label="外部租赁价(元/天)"
              prop="rentPrice"
              label-width="140px"
            >
              <el-input-number
                v-model="form.rentPrice"
                placeholder="请输入"
                maxlength="20"
                controls-position="right"
                :min="0" :max="999999999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否试验" prop="isTest">
              <el-select
                v-model="form.isTest"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option value="0" label="否">否</el-option>
                <el-option value="1" label="是">是</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNum">
              <el-input
                v-model.number="form.sortNum"
                type="number" :min="1" @input="(v)=>(form.sortNum=v.replace(/[^\d]/g,''))"
                placeholder="请输入排序"
                maxlength="10"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检验周期(月)" prop="testCycle">
              <el-input-number
                v-model="form.testCycle"
                controls-position="right"
                :min="0" :max="99999"
                placeholder="请输入"
                maxlength="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="抽检比例(%)" prop="samplingRatio">
              <el-input-number
                v-model="form.samplingRatio"
                controls-position="right"
                :min="0" :max="100"
                placeholder="请输入"
                maxlength="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="核定载荷(T/MPa)"
              prop="ratedLoad"
            >
              <el-input
                v-model="form.ratedLoad"
                placeholder="请输入"
                maxlength="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item
              label="试验载荷(T/MPa)"
              prop="testLoad"
            >
              <el-input
                v-model="form.testLoad"
                placeholder="请输入"
                maxlength="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="持荷时间(分)" prop="holdingTime">
              <el-input-number
                v-model="form.holdingTime"
                controls-position="right"
                :min="0" :max="999999999"
                placeholder="请输入"
                maxlength="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否为机具" prop="jiJuType">
              <el-select
                v-model="form.jiJuType"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option value="2" label="否">否</el-option>
                <el-option value="1" label="是">是</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否检验" prop="isCheck">
              <el-select
                v-model="form.isCheck"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option value="0" label="否">否</el-option>
                <el-option value="1" label="是">是</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库管员">
              <el-select
                v-model="form.keeperArr"
                filterable multiple
                placeholder="请选择库管员"
                style="width: 100%"
              >
                <el-option
                  v-for="keeper in KeeperOptions"
                  :key="keeper.userId"
                  :label="keeper.userName"
                  :value="keeper.userId+''"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修班组">
              <el-select
                v-model="form.repairerArr"
                filterable multiple
                placeholder="请选择维修班组"
                style="width: 100%"
              >
                <el-option
                  v-for="keeper in repairerOptions"
                  :key="keeper.userId"
                  :label="keeper.userName"
                  :value="keeper.userId+''"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template>
          <el-button
            v-if="this.title == '新增' || this.title == '修改'"
            type="primary"
            @click="submitForm"
          >确 定
          </el-button
          >
        </template>

        <el-button @click="cancel">取 消</el-button>

        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
    </el-dialog>
    <!-- 修改库存对话框 -->
    <el-dialog
      :title="storageTitle"
      :visible.sync="storageOpen"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="storageForm" :model="storageForm" :rules="storageRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="当前库存" prop="preStoreNum">
              <el-input
                v-model="storageForm.preStoreNum"
                type="number"
                :min="0"
                placeholder="当前库存数量"
                maxlength="10"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="新库存数量" prop="storageNum">
              <el-input
                v-model="storageForm.storageNum"
                type="number"
                :min="0"
                placeholder="请输入新的库存数量"
                maxlength="10"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStorageForm">确 定</el-button>
        <el-button @click="storageOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" height="650px" :src="dialogImageUrl" alt/>
    </el-dialog>

    <!-- 新增弹框 -->
    <el-dialog
      :title="addTitle"
      :visible.sync="addTitleVisible"
      v-if="addTitleVisible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        label-width="120px"
        :model="addFormParams"
        :rules="addFormParamsRules"
        ref="addFormParamsRef"
      >
        <el-row :gutter="24">
          <el-col :span="12" v-if="addTitle === '新增'">
            <el-form-item label="所属上级">
              <el-input
                style="width: 100%"
                disabled
                v-model="addFormParams.label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="typeName">
              <el-input style="width: 100%" v-model="addFormParams.typeName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addTitle === '修改' && this.levelTemp == 3">
            <el-form-item label="是否录入编码" prop="isEnter">
              <el-select style="width: 100%" v-model="addFormParams.isEnter">
                <el-option label="是" value="1"/>
                <el-option label="否" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addTitle === '修改' && this.levelTemp == 2">
            <el-form-item label="是否绑定班组长" prop="keeperUserId">
              <el-select style="width: 100%" v-model="addFormParams.keeperUserId">
                <el-option v-for="(item, index) in teamLeaderList" :key="index" :label="item.keeperUserName"
                           :value="item.keeperUserId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="text-align: right">
          <el-form-item>
            <el-button size="small" type="primary" style="color: #fff;" @click="onSubmit">确 定</el-button>
            <el-button size="small" @click="onCancel">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
var exportLevel = 0;
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getMaTypeList,
  getListByMaType,
  getMaType,
  queryKeeperDataApi,
  queryKeeperProApi,
  queryKeeperMatApi,
  queryKeeperNameApi,
  delMaType,
  // 添加更新库存的API
  updateStorageNumApi,
  addMaType,
  updateMaType,
  getUserTypeList,
  updatePartType,
  getUserListApi
} from "@/api/ma/base";
import {getKeeperIds} from "@/api/ma/typeConfigKeeper";
import {getRepairIds} from "@/api/ma/typeConfigRepair";
import {imgUpLoad} from "@/api/system/upload";

export default {
  name: "Type",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      unitValueOptions: [{id: "0", name: "整数"}, {id: "1", name: "小数"}],
      // 库管员用户数据
      keeperList: null,
      keeperDataRange: [],
      KeeperOptions: [],
      repairerOptions: [],
      //维修员用户数据
      repairUserList: null,
      //资产类型数据
      propList: null,
      // 类型名称
      typeName: undefined,
      // 树选项
      treeOptions: undefined,
      treeTemp: [],
      treeTempTwo: [],
      //列表数据
      typeList: undefined,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        companyId: "",
        isCheck: '0',
        jiJuType:'1'
      },
      chosenTypeId: "",
      leasePrice: "",
      uploadHeader: process.env.VUE_APP_BASE_API,
      imageUrl: "",
      imageName: "",
      fileList: [],
      field101fileList: [],
      levelTemp: undefined,
      idTemp: undefined,
      parentId: undefined,
      level2Temp: undefined,
      level2TempName: undefined,
      level1TempName: undefined,
      level0TempName: undefined,
      level1Temp: undefined,
      uploadUrl: process.env.VUE_APP_BASE_API + "/system", // 上传的图片服务器地
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: undefined,
        level: 0,
        // phonenumber: undefined,
        // status: undefined,
        // typeId: undefined
      },
      // 修改库存对话框相关数据
      storageOpen: false,
      storageTitle: "修改库存",
      storageForm: {
        typeId: '',
        preStoreNum: 0,
        storageNum: 0,
        reason: ''
      },
      storageRules: {
        storageNum: [
          {required: true, message: "新库存数量不能为空", trigger: "blur"},
        ],
      },
      // 表单校验
      rules: {
        typeName: [
          {
            required: true,
            message: "规格型号不能为空",
            trigger: "blur",
          },
        ],
        manageType: [
          {
            required: true,
            message: "管理模式不能为空",
            trigger: "change",
          },
        ],
        unitName: [
          {
            required: true,
            message: "计量单位不能为空",
            trigger: "change",
          },
        ],
        buyPrice: [
          {
            required: true,
            message: "购置价不能为空",
            trigger: "blur",
          },
        ],
        leasePrice: [
          {
            required: true,
            message: "内部租赁价不能为空",
            trigger: "blur",
          },
        ]
      },
      companyId: undefined,
      dialogImageUrl: "",
      dialogVisible: false,
      configOpen: false,
      cform: {
        price: "",
        afterPrice: "",
        useDate: "",
      },
      /* 新增弹框等数据源定义 */
      addTitleVisible: false,
      addTitle: "", // 新增弹框标题
      addFormParams: {
        label: "",
        typeName: "",
        companyId: 101,
        isEnter: '',
        keeperUserId: '',
      },
      teamLeaderList: [],
      addFormParamsRules: {
        typeName: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
      },
      isMousemoveId: null,
      isLevel1Disabled: false,
      isLevel2Disabled: false,
      isLevel3Disabled: false,
      isLevel4Disabled: false,

      //编辑时存的租赁价格
      leasePriceTemp: undefined,
    };
  },
  watch: {
    // 根据名称筛选部门树
    typeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeData();
    this.getKeeperData();
    this.getRepairerData();
    // this.getList()
  },
  methods: {
    async getKeeperData() {
      const itemName = "ku_guan_role_ids";
      let roleIdsTemp = []
      await getKeeperIds(itemName).then((response) => {
        const roleIds = response.rows[response.rows.length - 1].itemValue
          .split(",")
          .map((item) => Number(item));
        roleIdsTemp = roleIds;
      });
      await getUserTypeList(roleIdsTemp.join(',')).then((response) => {
        this.KeeperOptions = response.rows;
      });
    },
    /** 修改库存按钮操作 */
    updateStorageNum(row) {
      this.storageForm = {
        typeId: row.typeId,
        preStoreNum: row.storageNum || 0,
        storageNum: row.storageNum || 0,
      };
      this.storageOpen = true;
    },

    /** 提交库存修改表单 */
    submitStorageForm() {
      this.$refs["storageForm"].validate((valid) => {
        if (valid) {
          // 转换为数字类型
          this.storageForm.storageNum = Number(this.storageForm.storageNum);

          updateStorageNumApi(this.storageForm).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("库存修改成功");
              this.storageOpen = false;
              this.getList(); // 刷新列表
            } else {
              this.$modal.msgError(response.msg || "库存修改失败");
            }
          }).catch(error => {
            this.$modal.msgError("库存修改失败");
          });
        }
      });
    },
    async getRepairerData() {
      const itemName = "wei_xiu_role_ids";
      let roleIdsTemp = []
      await getRepairIds(itemName).then((response) => {
        const roleIds = response.rows[response.rows.length - 1].itemValue
          .split(",")
          .map((item) => Number(item));
        roleIdsTemp = roleIds;
      });
      await getUserTypeList(roleIdsTemp.join(',')).then((response) => {
        this.repairerOptions = response.rows;
      });
    },


    /** 查询物资类型 */
    async getKeeperDataList(data) {
      let keepdataRes = await queryKeeperDataApi({
        // typeId:data.keeperData
      });
      this.keeperDataRange = keepdataRes.data.map((item) => {
        return {
          label: item.houseName,
          value: item.houseId,
        };
      });
      this.form.keeperData = this.keeperDataRange.value;
    },

    /** 查询新增页面-上级类型下拉树结构 */
    getTreeData() {
      getMaTypeList().then((response) => {
        this.treeOptions = response.data;
        console.log(this.treeOptions)
        if (this.treeOptions.length > 0) {
          if (this.treeOptions[0].children && this.treeOptions[0].children.length > 0) {
            const firstNode = this.treeOptions[0].children[0];
            this.queryParams.typeId = firstNode.id;
            this.queryParams.level = 1;
            this.queryParams.houseId = firstNode.houseId;
            this.getList();
          } else {
            this.queryParams.typeId = this.treeOptions[0].id;
            this.queryParams.level = 0;
            this.queryParams.houseId = this.treeOptions[0].id;
            this.getList();
          }
        }
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getListByMaType(this.queryParams).then((response) => {
        if (response.code === 200 && response.data ) {
          this.typeList = response.data.rows
          this.total = response.data.total
        }
        this.loading = false;
      });
    },
    // 筛选节点 - 左侧树
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件 - 左侧树
    async handleNodeClick(data, node) {
      if (data.level == 0) {
        this.queryParams.typeId = data.id;
        this.queryParams.level = data.level;
        this.queryParams.houseId = data.id;
      } else {
        this.queryParams.typeId = data.id;
        this.queryParams.level = data.level;
        this.queryParams.houseId = data.houseId;
      }
      this.handleQuery();
      if (node.level == 1) {
        this.isLevel1Disabled = true;
        this.isLevel2Disabled = false;
        this.isLevel3Disabled = false;
        this.isLevel4Disabled = false;
        this.form.keeperData = data.id;
      } else if (node.level == 2) {
        this.isLevel1Disabled = true;
        this.isLevel2Disabled = true;
        this.isLevel3Disabled = false;
        this.isLevel4Disabled = false;
        this.form.keeperDataPro = data.id;
      } else if (node.level == 3) {
        this.isLevel1Disabled = true;
        this.isLevel2Disabled = true;
        this.isLevel3Disabled = true;
        this.isLevel4Disabled = false;
        this.form.keeperDataPro = data.id;
        this.form.keeperDataMat = data.id;
      } else if (node.level == 4) {
        this.isLevel1Disabled = true;
        this.isLevel2Disabled = true;
        this.isLevel3Disabled = true;
        this.isLevel4Disabled = true;
        this.form.keeperDataPro = data.id;
        this.form.keeperDataMat = data.id;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        photoUrl: "",
        photoName: "",
        documentUrl: "",
        documentName: "",
        parentId: "",
        jiJuType: '1',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.typeId = undefined;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.level = 0;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.typeId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.jiJuType = '1';
      this.open = true;
      this.title = "新增";
    },
    //查看
    handleView(row) {
      this.reset();
      const typeId = row.typeId;
      getMaType(typeId).then((response) => {
        this.form = response.data;
        if (response.data.repairerId) {
          this.form.repairerArr = response.data.repairerId.split(",")
        }
        if (response.data.keeperId) {
          this.form.keeperArr = response.data.keeperId.split(",")
        }
        this.form.isCharging = this.form.isCharging + "";
        this.form.jiJuType = this.form.jiJuType + "";
        this.form.isTest = this.form.isTest + "";

        // this.form.houseName = row.houseName;
        this.form.itemType = row.itemType;
        this.form.materialType = row.materialType;
        this.form.materialName = row.materialName;
        this.isLevel1Disabled = true;
        this.isLevel2Disabled = true;
        this.isLevel3Disabled = true;
        this.isLevel4Disabled = true;
        this.open = true;
        this.title = "查看";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const typeId = row.typeId;
      getMaType(typeId).then((response) => {
        this.form = response.data;
        this.leasePriceTemp = response.data.leasePrice;
        if (response.data.repairerId) {
          this.form.repairerArr = response.data.repairerId.split(",")
        }
        if (response.data.keeperId) {
          this.form.keeperArr = response.data.keeperId.split(",")
        }
        this.form.isCharging = this.form.isCharging + "";
        this.form.jiJuType = this.form.jiJuType + "";
        this.form.isTest = this.form.isTest + "";
        // this.form.houseName = row.houseName;
        this.form.itemType = row.itemType;
        this.form.materialType = row.materialType;
        this.form.materialName = row.materialName;
        this.isLevel1Disabled = true;
        this.isLevel2Disabled = true;
        this.isLevel3Disabled = true;
        this.isLevel4Disabled = true;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form, "提交参数---");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.keeperArr != null && this.form.keeperArr.length > 0) {
            this.form.keeperId = this.form.keeperArr.join(",")
          }
          if (this.form.repairerArr != null && this.form.repairerArr.length > 0) {
            this.form.repairerId = this.form.repairerArr.join(",")
          }
          if (this.form.typeId != undefined) {
            if (this.form.leasePrice != this.leasePriceTemp) {
              this.$modal
                .confirm("是否确认修改后的内部租赁价？")
                .then(() => {
                  this.form.isUpdateLeasePrice = true;
                  updateMaType(this.form).then((response) => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                    // this.getTreeData();
                  });
                })
                .catch(() => {
                });
            } else {
              updateMaType(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                // this.getTreeData();
              });
            }
          } else {
            addMaType(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // this.getTreeData();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const typeId = row.typeId;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delMaType(typeId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
          // this.getTreeData();
        })
        .catch(() => {
        });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.imageUrl = "";
      this.form.photoUrl = "";
      this.form.photoName = "";
    },

    /** 导出按钮操作 */
    // handleExport() {
    //     // this.download('system/user/export', {
    //     //   ...this.queryParams
    //     // }, `user_${new Date().getTime()}.xlsx`)
    // exportMaterial(this.queryParams).then(res => {
    //     downloadFile({ fileName: `物资类型信息_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
    //   })
    // },
    /** 导出按钮作 */
    handleExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };

      const currentTime = formatTime(new Date());
      let queryTemp = this.queryParams;
      // queryTemp.level = 0;
      this.download(
        "/material/ma_type/export",
        {
          ...queryTemp,
        },
        `物资类型信息_${currentTime}.xlsx`
      );
    },
    /* 树节点操作 */
    treeChange(val) {
      console.log(val, "树节点");

      this.form.companyId = val.companyId;
    },

    /* 树节点增加 */
    appendTreeNode(data) {
      this.levelTemp = data.level;
      this.idTemp = data.id;
      console.log("dataAdd", data);
      if (data.level === 3) {
        this.reset();
        Object.assign(this.form, data);

        // 初始化层级信息
        this.level0TempName = '';
        this.level1TempName = '';
        this.level2TempName = '';

        // 递归查找层级信息
        if (this.treeOptions && this.treeOptions.length > 0) {
          this.findLevelInfo(this.treeOptions, data);
        }

        this.isLevel1Disabled = true;
        this.isLevel2Disabled = true;
        this.isLevel3Disabled = true;
        this.isLevel4Disabled = true;
        this.form.parentId = data.id;
        this.form.houseName = this.level0TempName;
        this.form.itemType = this.level1TempName;
        this.form.materialType = this.level2TempName;
        this.form.materialName = data.label;
        this.form.sortNum = data.number + 1
        this.open = true;
        this.title = "新增";
      } else {
        Object.assign(this.addFormParams, data);
        this.addFormParams.typeName = "";
        this.addTitle = "新增";
        this.addTitleVisible = true;
      }
    },

    // 递归查找层级信息的方法
    findLevelInfo(nodes, targetData) {
      for (const node of nodes) {
        if (node.level === 0 && node.id === targetData.houseId) {
          this.level0TempName = node.label;
        }
        if (node.level === 2 && node.id === targetData.parentId) {
          this.level2TempName = node.label;
          // 递归查找 level 为 1 的父节点
          if (node.parentId !== undefined) {
            this.findLevel1Info(this.treeOptions, node.parentId);
          }
        }
        if (node.children && node.children.length > 0) {
          this.findLevelInfo(node.children, targetData);
        }
      }
    },

    // 递归查找 level 为 1 的节点信息
    findLevel1Info(nodes, parentId) {
      for (const node of nodes) {
        if (node.level === 1 && node.id === parentId) {
          this.level1TempName = node.label;
          break;
        }
        if (node.children && node.children.length > 0) {
          this.findLevel1Info(node.children, parentId);
        }
      }
    },

    /* 树节点删除 */
    removeTreeNode(data) {
      // this.$message.success('删除--')
      console.log(data, "删除时的数据源--");
      const typeId = data.id;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delMaType(typeId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getTreeData();
        })
        .catch(() => {
        });
    },
    // 获取班组长列表
    getTeamLeaderList() {
      getUserListApi().then((res) => {
        this.teamLeaderList = res.data
      })
    },
    /* 树节点修改 */
    editTreeNode(data) {
      console.log('🚀 ~ editTreeNode ~ data:', data)
      this.levelTemp = data.level;
      if (this.levelTemp === 2) {
        this.getTeamLeaderList()
      }
      console.log('🚀 ~ editTreeNode ~ this.levelTemp:', this.levelTemp)
      this.idTemp = data.id;
      this.parentId = data.parentId;
      console.log("data", data);
      Object.assign(this.addFormParams, data);
      this.addTitle = "修改";
      this.addFormParams.typeName = data.label;
      this.addTitleVisible = true;
    },
    /* 确定 */
    onSubmit() {
      const {id, typeName, isEnter, keeperUserId} = this.addFormParams;
      console.log("level", this.levelTemp);
      console.log("idTemp", this.idTemp);
      const addParams = {
        parentId: this.levelTemp == 0 ? 0 : this.idTemp,
        typeName,
        level: this.levelTemp,
        houseId: this.levelTemp == 0 ? id : null,
      };

      const editParams = {
        houseId: id,
        typeName,
        level: this.levelTemp,
        parentId: this.parentId,
        typeId: id,
        isEnter,
        keeperUserId,
      };

      this.$refs["addFormParamsRef"].validate(async (valid) => {
        if (valid) {
          if (this.addTitle === "新增") {
            const res = await addMaType(addParams);
            if (res.code === 200) {
              this.$message.success("新增成功！");
              this.addTitleVisible = false;
              this.getList();
              this.getTreeData();
            }
          } else {
            let res = null
            if (this.levelTemp == 0) {
              res = await updatePartType(editParams);
            } else {
              res = await updateMaType(editParams);
            }
            if (res.code === 200) {
              this.$message.success("修改成功！");
              this.addTitleVisible = false;
              this.getList();
              this.getTreeData();
            }
          }
        }
      });
    },
    /* 取消 */
    onCancel() {
      this.addTitleVisible = false;
    },
    getParentName(list, id) {
      try {
        list.forEach((e) => {
          if (e.id == id) {
            this.form.label = e.label;
            throw new Error();
          } else {
            if (e.children && e.children.length > 0) {
              this.getParentName(e.children, id);
            }
          }
        });
      } catch (error) {
      }
    },

    onMousemove(data) {
      this.isMousemoveId = data.id;
    },
    onMouseleave() {
      this.isMousemoveId = null;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}

::v-deep .btn-items .el-button + .el-button {
  margin-left: 6px;
}

.btn-items {
  margin-left: 4px;

  .el-button--text {
    font-size: 16px;
  }
}

::v-deep .el-tree .el-tree-node__expand-icon.expanded {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}

::v-deep .el-tree .el-icon-caret-right:before {
  content: "\e783";
  font-size: 16px;
}

::v-deep
.el-tree
.el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
  content: "\e781";
  font-size: 16px;
  color: #1890ff;
}

::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
  color: #1890ff !important;
}

::v-deep .el-tree-node__expand-icon.is-leaf {
  color: transparent !important;
}

::v-deep
.el-tree--highlight-current
.el-tree-node.is-current
> .el-tree-node__content {
  background-color: #8decf1;
}

::v-deep .el-dialog {
  // 表单标签文字样式
  .el-form-item__label {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
    // line-height: 1.5;
  }

  // 输入框文字样式
  .el-input__inner {
    font-size: 14px;
    color: #303133;

    &::placeholder {
      font-size: 13px;
      color: #c0c4cc;
    }
  }

  // 单位文字样式
  span {
    font-size: 14px;
    // color: #606266;
    margin-left: 8px;
  }

  // 下拉选择框文字样式
  .el-select {
    .el-input__inner {
      font-size: 14px;
      color: #303133;
    }
  }

  // 只读输入框样式
  .el-input.is-disabled .el-input__inner {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
  }
}

// 表格内文字样式
::v-deep .el-table {
  font-size: 14px;

  th {
    font-weight: 500;
    color: #303133;
  }

  td {
    color: #606266;
  }
}

// 按钮文字样式
::v-deep .el-button {
  font-size: 14px;

  &--text {
    font-size: 13px;
  }
}

// 树节点文字样式
::v-deep .el-tree-node__label {
  font-size: 14px;
  color: #606266;
}

// 搜索框文字样式
::v-deep .el-input--small {
  .el-input__inner {
    font-size: 13px;

    &::placeholder {
      font-size: 13px;
      color: #c0c4cc;
    }
  }
}

::v-deep .el-dialog .el-input__inner {
  text-align: start !important;
}
</style>
