<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">BOM管理</div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:bom:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-sort"
            size="mini"
            @click="toggleExpandAll"
          >展开/折叠
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
        </el-col>
        <right-toolbar ref="toolBarRef" @customCols="customColsHandler" :showSearch.sync="showSearch"
                       showColumnsType="transfer" :columns="columns"></right-toolbar>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="父id" prop="pid">
          <el-input
            v-model="queryParams.pid"
            placeholder="请输入父id"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料ID" prop="goodsId">
          <el-input
            v-model="queryParams.goodsId"
            placeholder="请输入物料ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="goodsName">
          <el-input
            v-model="queryParams.goodsName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="序号" prop="serialNumber">
          <el-input
            v-model="queryParams.serialNumber"
            placeholder="请输入序号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数量" prop="goodsNum">
          <el-input
            v-model="queryParams.goodsNum"
            placeholder="请输入数量"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <div ref="mainTablePanel" :style="{height: mainTableDivHeight}">
        <el-table
          v-if="refreshTable"
          v-loading="loading"
          border
          size="mini"
          :height="mainTableHeight"
          :data="bomList"
          row-key="id"
          :default-expand-all="isExpandAll"
          :max-height="900"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :key="rndKey"
          @header-dragend="handleHeaderDragEnd">
          <el-table-column v-for="item in columns" :key="item.key" :label="item.label" align="center"
                           :prop="item.columnName" v-if="item.visible" :width="item.width">
            <template v-slot="scope">
              <dict-tag v-if="item.columnName === 'goodsType'" v-slot="scope" :options="dict.type.goods_type"
                        :value="scope.row[item.columnName]"/>
              <span v-else>{{ scope.row[item.columnName] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:bom:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['system:bom:add']"
              >新增
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:bom:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加或修改物料bom对话框 -->
    <el-dialog id="dialog-container" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="父id" prop="pid">
                <treeselect v-model="form.pid" :options="bomOptions" :normalizer="normalizer" placeholder="请选择父id"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料ID" prop="goodsId">
                <el-input v-model="form.goodsId" placeholder="请输入物料ID"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料名称" prop="goodsName">
                <el-input v-model="form.goodsName" placeholder="请输入物料名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料分类" prop="unit">
                <el-select v-model="form.goodsType" placeholder="请选择物料分类">
                  <el-option
                    v-for="dict in dict.type.goods_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="序号" prop="serialNumber">
                <el-input v-model="form.serialNumber" placeholder="请输入序号"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数量" prop="goodsNum">
                <el-input v-model="form.goodsNum" placeholder="请输入数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {addBom, delBom, getBom, listBom, updateBom} from "@/api/system/bom";
import {listCOLUMN} from "@/api/system/column";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Bom",
  dicts: ['goods_type', 'common_status'],
  components: {
    Treeselect
  },
  data() {
    return {
      rndKey: 0,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 物料bom表格数据
      bomList: [],
      // 物料bom树选项
      bomOptions: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "bom",
      rightToolbarShow: false,
      tableNo: 0,
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pid: null,
        goodsId: null,
        goodsName: null,
        goodsType: null,
        serialNumber: null,
        goodsNum: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      columns: []
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.computedTableHeight();
  },
  watch: {
    'showSearch': function () {
      this.computedTableHeight();
    }
  },
  methods: {
    handleHeaderDragEnd(newWidth, oldWidth, column, event) {
      // 当列宽发生变化时，将变化值写入到columns变量中。
      this.columns.map((obj) => {
        if (obj.columnName == column.property) obj.width = newWidth;
      });
      this.$refs.toolBarRef.saveConfig(this.columns);

    },
    customColsHandler(columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },

    /** 查询用户展示字段定义管理列表 */
    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;

        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;

        var mainHeight = tablePanelHeight;
        this.mainTableDivHeight = mainHeight + "px";
        this.mainTableHeight = (mainHeight - 25) + "px";
      })
    },
    /** 查询物料bom列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then(response => {
        console.log(response.data.list)
        this.bomList = this.handleTree(response.data.list, "id", "pid");
        if (this.columns.length == 0) this.columns = response.data.column;
        console.log(response.data)
        this.loading = false;
      });
    },
    /** 转换物料bom数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.goodsName,
        children: node.children
      };
    },
    /** 查询物料bom下拉树结构 */
    getTreeselect() {
      listBom().then(response => {
        this.bomOptions = [];
        const data = {id: 0, goodsName: '顶级节点', children: []};
        data.children = this.handleTree(response.data, "id", "pid");
        this.bomOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        goodsId: null,
        goodsName: null,
        goodsType: null,
        serialNumber: null,
        goodsNum: null,
        remark: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.pid = row.id;
      } else {
        this.form.pid = 0;
      }
      this.open = true;
      this.title = "添加物料bom";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.pid = row.pid;
      }
      getBom(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料bom";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除物料bom编号为"' + row.id + '"的数据项？').then(function () {
        return delBom(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}
</style>
