<template>
  <div class="app-container">
    <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"
          >
            <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="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        >新增</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" border>
          <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="partType"
            show-overflow-tooltip
          />
          <el-table-column
            label="配件名称"
            align="center"
            prop="partName"
            show-overflow-tooltip
          />
          <el-table-column
            label="规格型号"
            align="center"
            prop="paName"
            show-overflow-tooltip
          />
          <el-table-column
            label="计量单位"
            align="center"
            prop="unitName"
            show-overflow-tooltip
          />
          <el-table-column
            label="购置价格(元)"
            align="center"
            prop="buyPrice"
            show-overflow-tooltip
            width="100"
          />
          <el-table-column
            label="数量"
            align="center"
            prop="storageNum"
            show-overflow-tooltip
          />
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            show-overflow-tooltip
          />

          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['ma:type:edit']"
              >
                修改
              </el-button>
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-delete-solid"
                @click="handleDelete(scope.row)"
                v-hasPermi="['ma:type:remove']"
              >
                删除
              </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>
        <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="showHouse"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="所属上级" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="treeOptions"
                :normalizer="normalizer"
                :show-count="true"
                :searchable="false"
                :disable-branch-nodes="false"
                placeholder="选择上级菜单"
                @select="onSelect"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="规格型号" prop="paName">
              <el-input
                v-model="form.paName"
                placeholder="请输入规格型号"
                maxlength="20"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="计量单位" prop="unitName">
              <el-input
                v-model="form.unitName"
                placeholder="请输入计量单位"
                maxlength="20"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="购置价格(元)">
              <el-input
                v-model="form.buyPrice"
                placeholder="请输入购置价格"
                maxlength="20"
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入备注"
                v-model="form.remark"
                maxlength="50"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </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="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="paName">
              <el-input style="width: 100%" v-model="addFormParams.paName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="text-align: right">
          <el-form-item>
            <el-button size="small" type="primary" @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 {
  getListByPartType,
  getListTree,
  getAccessoryDetail,
  addAccessory,
  editAccessory,
  delAccessory,
  addMaType,
  updateMaType,
  delMaType,
} from "@/api/ma/partType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
export default {
  name: "PartType",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,

      loadingTwo: false,

      // 是否显示项目部Id
      showName: false,

      // 是否显示施工预警信息
      showWarn: false,

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 类型名称
      typeName: undefined,
      // 显示搜索条件
      showSearch: true,
      showHouse: false,

      typeList: undefined,
      treeList: [],
      flagTemp: 1,
      // 总条数
      total: 0,
      totalTwo: 0,
      // 施工记录表格数据
      houseList: [],
      maxLength: 100, //已选列表上限，防止数据过多请求报错
      keeperDataRange: [],
      // 班组人员表格数据
      teamList: [],
      teamTempList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        level: 1,
        id: undefined,
      },
      companyId: undefined,
      parentId: undefined,
      isMousemoveId: null,
      addTitleVisible: false,
      addTitle: "", // 新增弹框标题
      addFormParams: {
        label: "",
        paName: "",
        companyId: 101,
      },
      treeOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paName: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
      },

      addFormParamsRules: {
        paName: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getTreeselect();
  },
  watch: {
    // 根据名称筛选配件类型树
    typeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 筛选节点 - 左侧树
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 节点单击事件 - 左侧树
    async handleNodeClick(data, node) {
      if (data.level != 0) {
        this.queryParams.id = data.id;
        this.queryParams.level = data.level;
        this.handleQuery();
      } else {
        this.queryParams.id = data.children[0].id;
        this.queryParams.level = data.children[0].level;
        this.handleQuery();
      }
    },

    /** 查询配件类型列表 */
    getList() {
      this.loading = true;
      getListByPartType(this.queryParams).then((response) => {
        this.typeList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.flagTemp = 1;
      this.reset();
      this.getTreeselect();
      this.form.id = 0;
      this.showHouse = true;
      this.title = "新增";
    },

    getTreeselect() {
      getListTree().then((response) => {
        this.treeOptions = [
          {
            label: "配件类型树",
            id: 0,
            children: response.data,
            level: 0,
          },
        ];
        if (this.treeOptions[0].children.length > 0) {
          const firstNode = this.treeOptions[0].children[0];
          this.queryParams.id = firstNode.id;
          this.queryParams.level = 1;
          this.getList();
        }
      });
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },

    handleUpdate(row) {
      this.flagTemp = 2;
      this.reset();
      // this.getTreeselect();
      const id = row.id;
      getAccessoryDetail(id).then((response) => {
        this.form = response.data;
        this.showHouse = true;
        this.title = "修改";
      });
    },
    reset() {
      this.form = {
        buyPrice: "",
        remark: "",
        label: "",
        parentId: "",
      };
      this.resetForm("form");
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.keyWord = null;
      this.handleQuery();
    },

    //** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form);
          if (this.flagTemp == 2) {
            console.log("修改");
            editAccessory(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.showHouse = false;
              this.getList();
            });
          } else if (this.flagTemp == 1) {
            addAccessory(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.showHouse = false;
              this.getList();
            });
          }
        }
      });
    },

    // 取消按钮
    cancel() {
      this.showHouse = false;
      this.reset();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delAccessory(id);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {});
    },

    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());
      this.download(
        "/material/ma_part_type/export",
        {
          ...this.queryParams,
        },
        `配件数据_${currentTime}.xlsx`
      );
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    onSelect(e) {
      console.log("eeeee", e);
      this.form.id = e.id;
      this.form.level = e.level;
    },

    /* 树节点增加 */
    appendTreeNode(data) {
      this.levelTemp = data.level;
      this.idTemp = data.id;
      console.log("dataAdd", data);
      console.log("idTemp", data);
      if (data.level == 2) {
        this.reset();
        Object.assign(this.form, data);
        this.form.parentId = data.id;
        this.showHouse = true;
        this.title = "新增";
      } else {
        Object.assign(this.addFormParams, data);
        console.log("data", data);
        console.log("addFormParams", this.addFormParams);
        this.addFormParams.paName = "";
        this.addTitle = "新增";
        this.addTitleVisible = true;
      }
    },
    /* 树节点删除 */
    removeTreeNode(data) {
      // this.$message.success('删除--')
      console.log(data, "删除时的数据源--");
      const id = data.id;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delMaType(id);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getTreeselect();
        })
        .catch(() => {});
    },
    /* 树节点修改 */
    editTreeNode(data) {
      this.levelTemp = data.level;
      this.idTemp = data.id;
      this.parentId = data.parentId;
      Object.assign(this.addFormParams, data);
      this.addTitle = "修改";
      this.addFormParams.paName = data.label;
      this.addTitleVisible = true;
    },
    /* 确定 */
    onSubmit() {
      const { id, paName } = this.addFormParams;
      const addParams = {
        parentId: this.levelTemp == 0 ? 0 : this.idTemp,
        paName,
        level: this.levelTemp,
        id: id,
      };

      const editParams = {
        paName,
        level: this.levelTemp,
        parentId: this.parentId,
        id: 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.addTitleVisible = false;
              this.getList();
              this.getTreeselect();
            }
          } else {
            const res = await updateMaType(editParams);
            if (res.code === 200) {
              this.$message.success("修改成功！");
              this.addTitleVisible = false;
              this.getList();
              this.getTreeselect();
            }
          }
        }
      });
    },
    /* 取消 */
    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>
