<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="false"
            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"
                  @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="tableDataList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column label="序号" align="center" width="80" type="index">
                <template slot-scope="scope">
                    <span>{{(queryParams.pageNum - 1) * 10 + 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
                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 :visible.sync="dialogVisible">
      <img width="100%" height="650px" :src="dialogImageUrl" alt />
    </el-dialog>

    <!-- 新增弹框 -->
    <el-dialog
      :title="addTitle"
      :visible.sync="addShowVisible"
      v-if="addShowVisible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        label-width="80px"
        :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-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> 
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getMaTypeList,
  getListByMaType,
  getMaType,
  queryKeeperDataApi,
  delMaType,
  addMaType,
  updateMaType, 
} from "@/api/ma/base"; 
import { imgUpLoad } from "@/api/system/upload";

export default {
  name: "ToolsType",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      unitValueOptions: [{id:"0",name:"整数"},{id:"1",name:"小数"}],
      // 库管员用户数据 
      // keeperDataRange: [],
      KeeperOptions: [],//选择库管员数据
      repairerOptions: [],//维修员用户数据   
      // 类型名称
      typeName: undefined,
      // 左侧树-树选项
      treeOptions: undefined,
      treeTemp: [], 
      //列表数据
      tableDataList: [],
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",    
      // 表单参数
      form: {
        companyId: "",
      },     
      levelTemp: undefined,
      idTemp: undefined,
      parentId: undefined, 
      defaultProps: {
        children: "children",
        label: "label",
      }, 
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: undefined,
        level: 0, 
      }, 
      // 表单校验
      rules: {
        // leasePrice: [
        //   {
        //     required: true,
        //     message: "规格型号不能为空",
        //     trigger: "blur",
        //   },
        // ],
      },
      companyId: undefined,
      dialogImageUrl: "",
      dialogVisible: false,
      /* 新增弹框等数据源定义 */
      addShowVisible: false,
      addTitle: "", // 新增弹框标题
      addFormParams: {
        label: "",
        typeName: "",
        companyId: 101,
      }, 
      addFormParamsRules: {
        typeName: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
      },
      isMousemoveId: null, 
    };
  },
  watch: {
    // 根据名称筛选部门树
    typeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeData(); 
  },
  methods: {
    /** 查询新增页面-上级类型下拉树结构 */
    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) => {
        this.tableDataList = 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.form.keeperData = data.id;
      } else if (node.level == 2) { 
        this.form.keeperDataPro = data.id;
      } else if (node.level == 3) { 
        this.form.keeperDataPro = data.id;
        this.form.keeperDataMat = data.id;
      } else if (node.level == 4) { 
        this.form.keeperDataPro = data.id;
        this.form.keeperDataMat = data.id;
      }
    },
     /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() { 
      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;
    }, 
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = { parentId: ""};
      this.resetForm("form");
    }, 
    //查看
    handleView(row) {
      console.log(row) 
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset(); 
      // this.open = true; 
      // this.title = "重命名文件"; 
    }, 
    /** 删除按钮操作 */
    handleDelete(row) {
      // const typeId = row.typeId;
      // this.$modal
      //   .confirm("是否确认删除数据项？")
      //   .then(function () {
      //     return delMaType(typeId);
      //   })
      //   .then(() => {
      //     this.$modal.msgSuccess("删除成功");
      //     this.getList();
      //     this.getTreeData();
      //   })
      //   .catch(() => {});
    },
    /** 导出按钮作 */
    handleExport() {
      let queryTemp = this.queryParams;
      // queryTemp.level = 0;
      this.download(
        "/material/ma_type/export",
        {
          ...queryTemp,
        },
        `物资类型信息_${new Date().getTime()}.xlsx`
      );
    },
    // /* 树节点操作 */
    // treeChange(val) {
    //   console.log(val, "树节点"); 
    //   this.form.companyId = val.companyId;
    // },

    /* 树节点增加 */
    appendTreeNode(data) {
      this.levelTemp = data.level;
      this.idTemp = data.id; 
      if (data.level === 3) {
        this.reset();
        Object.assign(this.form, data);  
        this.form.parentId = data.id; 
        this.open = true;
        this.title = "新增";
      } else {
        Object.assign(this.addFormParams, data);
        this.addFormParams.typeName = "";
        this.addTitle = "新增";
        this.addShowVisible = true;
      }
    },
    /* 树节点删除 */
    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(() => {});
    },
    /* 树节点修改 */
    editTreeNode(data) {
      this.levelTemp = data.level;
      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.addShowVisible = true;
    },
    /* 确定 */
    onSubmit() {
      const { id, typeName } = 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,
      };

      this.$refs["addFormParamsRef"].validate(async (valid) => {
        if (valid) {
          if (this.addTitle === "新增") {
            const res = await addMaType(addParams);
            if (res.code === 200) {
              this.$message.success("新增成功！");
              this.addShowVisible = false;
              this.getList();
              this.getTreeData();
            }
          } else {
            const res = await updateMaType(editParams);
            if (res.code === 200) {
              this.$message.success("修改成功！");
              this.addShowVisible = false;
              this.getList();
              this.getTreeData();
            }
          }
        }
      });
    },
    /* 取消 */
    onCancel() {
      this.addShowVisible = 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;
    }
  }
}
</style>
