<template>
  <div>
    <el-col :span="4" :xs="24">
      <!-- 新增按钮 -->
      <el-button class="groupAdd" type="primary" @click="handleAdd"
      >新增物料组</el-button>
      <div class="head-container">
        <el-input
          v-model="groupName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container">
        <el-tree
          :data="materialOptions"
          :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 }">
          <span style="width:110px; display:block; word-break:keep-all; white-space:nowrap; overflow:hidden; text-overflow:ellipsis"
            v-bind:title="node.label"
          >{{node.label}}</span>
          <span>
            <el-button
              class="btn-tree"
              type="text"
              size="medium"
              @click="() => remove(node, data)">
              －
            </el-button>
            <el-button
              v-if="node.level == 1"
              class="btn-tree"
              type="text"
              size="medium"
              @click="() => append(data)">
              ＋
            </el-button>
          </span>
        </span>
      </el-tree>
      </div>
    </el-col>
    <!-- 新增物料组窗口 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="物料组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入物料组名称" />
        </el-form-item>
      </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>
    <!-- 新增物料窗口 -->
    <!--产品物料选择弹窗-->
			<ItemSelectMaterial
				ref="itemSelectMaterial"
				@onSelected="onSelectMaterial"
			></ItemSelectMaterial>
  </div>
</template>

<script>
import {
  addMaterialGroup,
  delMaterialGroup,
  updateMaterialGroup,
  materialTreeSelect,
} from "@/api/quality/materialGroup";
import {
  addMaterialGroupDetail,
  listMaterialGroupDetail,
  delMaterialGroupDetail,
} from "@/api/quality/materialGroupDetail";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ItemSelectMaterial from "../qcIncome/selectMaterial.vue";

export default {
  name: "MaterialGroupAdd",
  comments: { Treeselect},
  components: {ItemSelectMaterial},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料树选项
      materialOptions: undefined,
      // 物料组名称
      groupName: undefined,
      // 物料组表格数据
      materialGroupList: [],
      //当前点击的节点数据
      nodeData: {},
      // 弹出层标题
      title: "",
      materialTitle: "",
      // 是否显示弹出层
      open: false,
      materialOpen: false,
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        attr1: null,
        factoryCode: null,
      },
      //表单参数
      form: {},
      //表单校验
      rules: {},
    };
  },
  watch: {
    // 根据名称筛选部门树
    groupName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getMaterialTree();
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupName: null,
        attr1: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        factoryCode: null,
        delFlag: null,
        groupId: null,
        materialCode: null,
        materialName: null,
      };
      this.resetForm("form");
    },
    /** 查询部门下拉树结构 */
    getMaterialTree() {
      materialTreeSelect().then((response) => {
        this.materialOptions = response.data;
        this.treeInit();
      });
      

    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //将默认的树节点数据传递给父组件
    treeInit() {
      const firstTreeNode = this.materialOptions[0];
      firstTreeNode.level = 1;
      this.$emit('child-event', firstTreeNode); // 触发事件并传递数据给父组件 
    },
    //树节点点击事件
    handleNodeClick(data,node) {
        this.nodeData.id = data.id;
        this.nodeData.name = data.label;
        this.nodeData.level = node.level;
        if(node.level == 2) {
          listMaterialGroupDetail(this.queryParams).then((response) => {
            this.materialGroupList = response.rows;
            const temp = this.materialGroupList.find(obj => obj.id === data.id);
            console.log(temp.materialCode);
            this.nodeData.materialCode = temp.materialCode;
            this.$emit('onNodeClick', this.nodeData);
          });
        }else{
          this.$emit('onNodeClick', this.nodeData);
        }
 
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMaterialGroup(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMaterialGroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getMaterialTree();
            });
          } else {
            addMaterialGroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getMaterialTree();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除物料组编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMaterialGroup(ids);
        })
        .then(() => {
          this.getMaterialTree();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "quality/materialGroup/export",
        {
          ...this.queryParams,
        },
        `materialGroup_${new Date().getTime()}.xlsx`
      );
    },
    /**添加树节点 */
    append(data) {
      this.reset();
      this.form.groupId = data.id;
      this.$refs.itemSelectMaterial.showFlag = true;
      },
     /**删除树节点 */
    remove(node, data) {
      const id = data.id;
      console.log(node);
      if(node.level == 1) {
        this.$modal
        .confirm('是否确认删除物料组名称为"' + data.label + '"的数据项？')
        .then(function () {
          //删除物料组
          return delMaterialGroup(id);
        })
        .then(() => {
          this.getMaterialTree();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
       }else{
        this.$modal
        .confirm('是否确认删除物料名称为"' + data.label + '"的数据项？')
        .then(function () {
          //删除物料
          return delMaterialGroupDetail(id);
        })
        .then(() => {
          this.getMaterialTree();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
       }
    },
     //物料选择确认
		onSelectMaterial(obj) {
       debugger
       this.form.materialCode = obj.code[0];
		   this.form.materialName = obj.name[0];
       console.log(this.form.groupId);
       if(this.form.materialCode != null) {
        addMaterialGroupDetail(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getMaterialTree();
            });
       }
		}
  },
};
</script>

<style>
.groupAdd {
  margin: 10px auto;
  width: 100%;
  
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  font: bolder;
  padding-right: 8px;
}
.custom-tree-node .btn-tree {
  margin: 0 8px;
  font-size: 20px;
  font: bolder;
}
</style>
