<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
            highlight-current
            @node-click="handleNodeClick"
          >
          </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="typeName">
            <el-input
              v-model="queryParams.typeName"
              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="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleBind"
              v-hasPermi="['machinery:type:add']"
              >绑定</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-minus"
              size="mini"
              @click="handleNoBind"
              v-hasPermi="['machinery:type:add']"
              >解绑</el-button
            >
          </el-col>
          <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"
          ref="multipleTable"
          row-key="typeId"
          default-expand-all
          :tree-props="{ children: 'children' }"
          border
          @selection-change="handleSelectionChange"
          @select="handleSelect"
          @select-all="handleSelectAll"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :reserve-selection="true"
          />
          <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"
            prop="parentOneLevelName"
            show-overflow-tooltip
          />
          <el-table-column
            label="施工类型"
            align="center"
            prop="parentFourLevelName"
            show-overflow-tooltip
          />
          <el-table-column
            label="物资类型"
            align="center"
            prop="parentThreeLevelName"
            show-overflow-tooltip
            width="100"
          />
          <el-table-column
            label="物资名称"
            align="center"
            prop="parentTwoLevelName"
            show-overflow-tooltip
          />
          <el-table-column
            label="规格型号"
            align="center"
            prop="parentThreeLevelName"
            show-overflow-tooltip
          />
          <el-table-column
            label="库管员"
            align="center"
            prop="keeperUserName"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.keeperUserName == null" style="color: red">
                {{ "请绑定" }}
              </div>
              <div v-else>
                {{ scope.row.keeperUserName }}
              </div>
              <!-- <div v-else style="color: red;"></div> -->
            </template>
          </el-table-column>
          <el-table-column
            label="维修员"
            align="center"
            prop="repairUserName"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.repairUserName == null" style="color: red">
                {{ "请绑定" }}
              </div>
              <div v-else>
                {{ scope.row.repairUserName }}
              </div>
              <!-- <div v-else style="color: red;"></div> -->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-user-solid"
                @click="handleUpdateKeep(scope.row)"
                v-hasPermi="['machinery:type:config']"
              >
                库管解绑
              </el-button>
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-user-solid"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['machinery:type:edit']"
              >
                维修解绑
              </el-button>
              <!-- <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)"
                                v-hasPermi="['machinery:type:del']"
                            >
                                删除
                            </el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// import {
//     getListByMaType,
//     getMaTypeList,
//     getMaType,
//     addMaType,
//     updateMaType,
//     delMaType,
// } from '@/api/store/tools'
import { getUserByRoleList, getMaUserList } from "@/api/system/user";
import {
  getProLists,
  getMaTypeList,
  getListByMaType,
  getMaType,
  queryKeeperDataApi,
  queryKeeperProApi,
  queryKeeperMatApi,
  queryKeeperNameApi,
  delMaType,
  addMaType,
  updateMaType,
} from "@/api/baseGround/base";
import {
  getMatConfigList,
  getListByMatConfig,
  bindRepair,
} from "@/api/baseGround/matConfig";
import { getInfo } from "@/api/login";
import { downloadFile } from "@/utils/download";
export default {
  name: "ToolsType",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalTemp:0,
      countTemp: 1,
      totalAll:0,
      // 库管员用户数据
      keeperList: null,
      keeperDataRange: [],
      keeperProRange: [],
      keeperMatRange: [],
      keeperNameRange: [],
      //维修员用户数据
      repairUserList: null,
      //资产类型数据
      propList: null,
      // 类型名称
      typeName: undefined,
      // 树选项
      treeOptions: undefined,
      //列表数据
      typeList: undefined,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      chosenTypeId: "",
      leasePrice: "",

      fileList: [],
      //上传地址
      // uploadUrl:'http://192.168.0.14:21624/system',//线上服务器地址+system
      // uploadUrl:'http://112.29.103.165:21624/system',//线上服务器地址+system
      // uploadUrl:'http://192.168.5.12:9201',//本地测试
      uploadUrl: process.env.VUE_APP_BASE_API + "/system", // 上传的图片服务器地址
      defaultProps: {
        children: "children",
        label: "label",
      },
      userIdTemp: -1,
      typeIdTemp: -1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: undefined,
        level: 0,
        // phonenumber: undefined,
        // status: undefined,
        // typeId: undefined
      },

      configOpen: false,
      cform: {
        price: "",
        afterPrice: "",
        useDate: "",
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    typeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getInfo()
    this.getList();
    this.getTreeData();
    this.getKeeperDataList();
    // this.getUserList()
    // this.getPropData()
  },
  methods: {
    // getInfo() {
    //     getInfo().then((res) => {
    //         console.log(res, 'companyId----')
    //         this.companyId = res.user.companyId
    //     })
    // },
    keeperDataChange(e) {
      this.keeperDataRange.forEach((item) => {
        if (e === item.value) {
          this.form.keeperDataPro = null;
          this.form.keeperDataMat = null;
          this.form.keeperDataName = null;
          // 获取工程下拉选
          let keeper = queryKeeperProApi({
            houseId: e,
          }).then((projRes) => {
            this.keeperProRange = projRes.data.map((item) => {
              return {
                label: item.typeName,
                value: item.typeId,
              };
            });
          });
        }
      });
    },

    keeperDataProChange(e) {
      this.keeperProRange.forEach((item) => {
        if (e === item.value) {
          this.form.keeperDataMat = null;
          this.form.keeperDataName = null;
          // 获取工程下拉选
          let keeper = queryKeeperMatApi({
            typeId: e,
          }).then((projRes) => {
            this.keeperMatRange = projRes.data.map((item) => {
              return {
                label: item.typeName,
                value: item.typeId,
              };
            });
          });
        }
      });
    },

    keeperDataMatChange(e) {
      this.keeperMatRange.forEach((item) => {
        if (e === item.value) {
          this.form.keeperDataName = null;
          // 获取工程下拉选
          let keeper = queryKeeperNameApi({
            typeId: e,
          }).then((projRes) => {
            this.keeperNameRange = projRes.data.map((item) => {
              return {
                label: item.typeName,
                value: item.typeId,
              };
            });
          });
        }
      });
    },

    /** 查询物资类型 */
    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;
    },

    async getKeeperDataListTemp(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

      let keepproRes = await queryKeeperProApi({
        houseId: data.keeperDataPro,
      });
      this.keeperProRange = keepproRes.data.map((item) => {
        return {
          label: item.typeName,
          value: item.typeId,
        };
      });
      this.form.keeperDataPro = this.keeperProRange.value;
    },
    /** 查询新增页面-上级类型下拉树结构 */
    getTreeData() {
      getMatConfigList().then((response) => {
        this.treeOptions = response.data;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getListByMatConfig(this.queryParams).then((response) => {
        this.typeList = response.data;
        response.data.forEach(item=>{
          if(item.children.length!=0){
            this.totalTemp=this.totalTemp+item.children.length
          }
        })
        this.totalTemp = this.totalTemp + response.data.length

        this.loading = false;
      });
    },
    // 筛选节点 - 左侧树
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件 - 左侧树
    handleNodeClick(data, node) {
      // this.queryParams.level = data.level
      this.handleQuery();
      (this.userIdTemp = data.id), (this.queryParams.userId = data.id);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        photoUrl: "",
        photoName: "",
        documentUrl: "",
        documentName: "",
        parentId: "",
      };
      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);
      console.log('ids----',this.ids)
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleSelect(selection, row) {
      this.toggleSelection(selection, row);
    },
    handleSelectAll(selection) {
      // this.countTemp++;
      console.log('selectionThree',selection)
      if (this.countTemp == 1 && selection.length == this.typeList.length) {
        this.typeList.forEach((row) => {
          this.toggleSelection([row], row);
        });
          this.countTemp=2
      } else if (
        this.countTemp == 2 &&
        selection.length == this.totalTemp - this.typeList.length
      ) {
        this.typeList.forEach((row) => {
          this.toggleSelectionFalse([row], row);
        });
        this.countTemp=1
      } 
    },
    //   else if (
    //     this.countTemp != 1 &&
    //     this.countTemp != 2 &&
    //     selection.length == this.totalTemp
    //   ) {
    //     this.typeList.forEach((row) => {
    //       this.toggleSelection([row], row);
    //     });
    //   } else if (
    //     this.countTemp != 1 &&
    //     this.countTemp != 2 &&
    //     selection.length == this.totalTemp - this.typeList.length
    //   ) {
    //     this.typeList.forEach((row) => {
    //       this.toggleSelectionFalse([row], row);
    //     });
    //   }
    // },
    toggleSelection(selection, row) {
      if (row.children && row.children.length) {
        row.children.forEach((child) => {
          this.$refs.multipleTable.toggleRowSelection(
            child,
            selection.includes(row)
          );
          this.toggleSelection(selection, child);
        });
      }
    },
    toggleSelectionFalse(selection, row) {
      if (row.children && row.children.length) {
        row.children.forEach((child) => {
          this.$refs.multipleTable.toggleRowSelection(
            child,
            !selection.includes(row)
          );
          this.toggleSelectionFalse(selection, child);
        });
      }
    },
    /** 绑定按钮操作 */
    handleBind() {
      if (this.userIdTemp == -1) {
        this.$alert("未勾选绑定人，无法绑定", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
        return;
      }
      //   if (this.ids.length == 0) {
      //     this.$alert("未进行勾选，无法绑定", "提示", {
      //       type: "warning",
      //       confirmButtonText: "确定",
      //     });
      //     return;
      //   } else {
      //     const ids = this.ids.join(",");
      //   }
      console.log(this.typeIdTemp);
      bindRepair({
        typeId: this.typeIdTemp,
        userId: this.userIdTemp,
        bindFlag: 1,
        bindRoleType: 1,
      }).then((response) => {
        this.$modal.msgSuccess("绑定成功");
        this.getList();
      });
    },

    /** 解绑按钮操作 */
    handleNoBind() {
      if (this.userIdTemp == -1) {
        this.$alert("未勾选绑定人，无法绑定", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
        return;
      }
      if (this.ids.length == 0) {
        this.$alert("未进行勾选，无法解绑", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
        return;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const typeId = row.typeId;
      const userId = row.repairUserId;
      bindRepair({
        typeId: typeId,
        userId: userId,
        bindFlag: 2,
        bindRoleType: 2,
      }).then((response) => {
        this.$modal.msgSuccess("解绑成功");
        this.getList();
      });
    },

    handleUpdateKeep(row) {
      const typeId = row.typeId;
      const userId = row.keeperUserId;
      console.log("typeId", typeId);
      console.log("userId", userId);
      bindRepair({
        typeId: typeId,
        userId: userId,
        bindFlag: 2,
        bindRoleType: 1,
      }).then((response) => {
        this.$modal.msgSuccess("解绑成功");
        this.getList();
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form, "提交参数---");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.typeId != undefined) {
            updateMaType(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getTreeData();
            });
          } else {
            // this.form.companyId = this.companyId
            addMaType(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getTreeData();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const typeIds = row.typeId;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delMaType(typeIds);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
          this.getTreeData();
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    // 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() {
      this.download(
        "/material/ma_type/export",
        {
          ...this.queryParams,
        },
        `物资类型信息_${new Date().getTime()}.xlsx`
      );
    },
    /* 树节点操作 */
    treeChange(val) {
      console.log(val, "树节点");

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

    /* 树节点增加 */
    appendTreeNode(data) {
      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.addTitleVisible = true;
      }
    },
    /* 树节点删除 */
    removeTreeNode(data) {
      // this.$message.success('删除--')
      console.log(data, "删除时的数据源--");
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delMaType(data.id);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getTreeData();
        })
        .catch(() => {});
    },
    /* 树节点修改 */
    editTreeNode(data) {
      console.log(data, "修改");
      Object.assign(this.addFormParams, data);
      this.addTitle = "修改";
      this.addFormParams.typeName = data.label;
      this.addTitleVisible = true;
    },
    /* 确定 */
    onSubmit() {
      const { id, typeName } = this.addFormParams;
      const addParams = {
        parentId: id,
        typeName,
      };
      const editParams = {
        typeId: id,
        typeName,
      };

      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.getTreeData();
            }
          } else {
            const res = await updateMaType(editParams);
            if (res.code === 200) {
              this.$message.success("修改成功！");
              this.addTitleVisible = false;
              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;
}
</style>
