<template>
  <div class="classify">
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain @click="addClassify"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain @click="editClassify"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain @click="deleteClassify"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-card v-loading="loading">
      <el-row :gutter="10" class="content">
        <el-col :span="6">
          <el-input
            placeholder="输入关键字进行过滤"
            size="small"
            v-model="filterText"
          >
          </el-input>

          <el-tree
            class="filter-tree"
            :data="data"
            :props="defaultProps"
            node-key="id"
            @node-click="clickTree"
            highlight-current
            :default-expanded-keys="defaultExpanded"
            :filter-node-method="filterNode"
            ref="tree"
          >
            <span slot-scope="{ node, data }">
              {{ data.code }}{{ data.materialType }}
            </span>
          </el-tree>
        </el-col>

        <el-col :span="18">
          <span class="title">基本信息</span>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="140px"
            class="demo-ruleForm"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料基本分类编码" prop="code">
                  <el-input
                    :disabled="disable"
                    v-model="ruleForm.code"
                  ></el-input>
                  <span>编码规则x-xxx-xxx-xxx</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料基本分类名称" prop="materialType">
                  <el-input
                    :disabled="disable"
                    v-model="ruleForm.materialType"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="启用状态" prop="isEnable">
                  <el-select
                    v-model="ruleForm.isEnable"
                    placeholder="启用状态"
                    clearable
                    :disabled="disable"
                    style="width: 230px"
                  >
                    <el-option
                      v-for="dict in dict.type.material_enable"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <span class="title">辅助属性</span>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="辅助属性结构" prop="marasstframe">
                  <el-select
                    v-model="ruleForm.marasstframe"
                    placeholder="属性结构"
                    clearable
                    :disabled="disable"
                    style="width: 230px"
                  >
                    <el-option
                      v-for="dict in dict.type.sys_assist_condtion"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="" prop="name">
                  <!-- <el-checkbox-group :disabled="disable" v-model="checkList"> -->
                  <el-checkbox
                    :disabled="disable"
                    v-model="ruleForm.isInventory"
                    label="isInventory"
                    >库存状态</el-checkbox
                  >
                  <!-- <el-checkbox label="项目"></el-checkbox>
                  <el-checkbox label="供应商"></el-checkbox>
                  <el-checkbox label="生产厂商"></el-checkbox>
                  <el-checkbox label="客户"></el-checkbox>
                  <el-checkbox label="特征码"></el-checkbox> -->
                  <el-checkbox
                    :disabled="disable"
                    v-model="ruleForm.isProductBatch"
                    label="isProductBatch"
                    >产品批号</el-checkbox
                  >
                  <!-- </el-checkbox-group> -->
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item v-if="!disable">
                  <el-button type="primary" @click="submitForm('ruleForm')"
                    >保存</el-button
                  >
                  <el-button @click="resetForm('ruleForm')">取消</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import {
  getTree,
  getDetail,
  add,
  delClassify,
  edit,
} from "@/api/classify/basic";
export default {
  name: "classify",
  dicts: ["material_enable", "sys_assist_condtion"],
  data() {
    return {
      loading: false,
      filterText: "",
      data: [],
      defaultProps: {
        children: "childrens",
        label: "materialType",
      },
      ruleForm: {
        code: "",
        materialType: "",
        isEnable: "0",
        delFlag: "",
        marasstframe: "",
        isInventory: "",
        isProductBatch: "",
      },
      rules: {
        code: [
          {
            required: true,
            message: "请输入物料基本分类编码",
            trigger: "blur",
          },
        ],
        materialType: [
          {
            required: true,
            message: "请输入物料基本分类名称",
            trigger: "blur",
          },
        ],
      },
      checkList: [],
      disable: true,
      biao: { parentId: 0 },
      // 删除节点id
      delId: "",
      // 判断是新增还是修改
      isAdd: true,
      defaultExpanded: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeData();
    //
  },
  mounted() {},
  methods: {
    // 获取树形结构
    getTreeData(data) {
      this.loading = true;
      getTree({})
        .then((res) => {
          let { code, rows } = res;
          if (code === 200) {
            this.data = rows;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取物料基本分类详情
    getDetailData(id) {
      getDetail(id).then((res) => {
        let { code, data } = res;
        if (code === 200) {
          console.log("data", data);
          this.ruleForm = data;
          this.ruleForm.isInventory = data.isInventory === "0" ? true : false;
          this.ruleForm.isProductBatch =
            data.isProductBatch === "0" ? true : false;
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.materialType.indexOf(value) !== -1;
    },
    clickTree(data, node) {
      console.log("data", data, node);
      // 如果点击新增时选择了树形节点，则不回显数据,且需要清空ruleForm内的数据
      if (this.disable) {
        this.getDetailData(data.id);
      } else {
        this.$refs["ruleForm"].resetFields();
      }
      // 标记是否为树形结构最外层
      this.biao.parentId = data.id;
      // 将节点id用作删除id
      this.delId = data.id;

      let { id } = data;

      if (this.defaultExpanded.findIndex((item) => item === id) === -1) {
        this.defaultExpanded.push(id);
        this.defaultExpanded = [...new Set(this.defaultExpanded)];
      } else {
        this.defaultExpanded = this.defaultExpanded.filter(
          (item) => item !== id
        );
      }
    },
    submitForm(formName) {
      let isInventory = this.ruleForm.isInventory ? "0" : "2";
      let isProductBatch = this.ruleForm.isProductBatch ? "0" : "2";
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            //判断是走新增还是修改
            console.log("add!");
            console.log(this.biao.parentId);
            console.log(this.ruleForm);
            let params = {
              ...this.ruleForm,
              ...this.biao,
              isInventory,
              isProductBatch,
            };
            console.log("params", params);
            add(params).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.getTreeData();
                // this.$refs['ruleForm'].resetFields();
                this.disable = true;
              }
            });
          } else {
            //修改
            console.log("edit");
            let ids = { id: this.biao.parentId };
            console.log("ids", ids);
            let params = {
              ...this.ruleForm,
              ...ids,
              isInventory,
              isProductBatch,
            };
            console.log("params", params);
            edit(params).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.getTreeData();
                // this.currentNode = params;
                console.log("this.data", this.defaultExpanded);
                this.disable = true;
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      console.log(formName);
      if (this.isAdd) {
        this.$refs[formName].resetFields();
        this.disable = true;
      } else {
        this.disable = true;
      }
    },
    // 点击新增按钮
    addClassify() {
      // console.log('值呢：', this.ruleForm)
      // 如果点击了树形节点后再点击新增，则清空数据再填写
      if (this.biao.parentId !== 0) {
        this.$refs["ruleForm"].resetFields();
      }
      this.disable = false;
      this.isAdd = true;
    },
    // 删除按钮
    deleteClassify() {
      if (this.biao.parentId == 0) {
        this.$message({
          message: "请选择删除节点",
          type: "warning",
        });
      } else {
        console.log("删除", this.delId);
        delClassify({ id: this.delId }).then((res) => {
          if (res.code === 200) {
            this.getTreeData();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }
        });
      }
    },
    // 修改按钮
    editClassify() {
      if (this.biao.parentId == 0) {
        this.$message({
          message: "请选择修改节点",
          type: "warning",
        });
      } else {
        console.log("修改");
        this.disable = false;
        this.isAdd = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.classify {
  height: calc(100vh - 84px);
  padding: 12px;
  box-sizing: border-box;
  overflow-y: auto;
}
.title {
  font-weight: bold;
}
</style>
