<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入设备类型名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="devicetypeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20":xs="24">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="父级标识" prop="parentId">-->
<!--        <el-input-->
<!--          v-model="queryParams.parentId"-->
<!--          placeholder="请输入父级标识"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceId">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="bom数量" prop="bomAmount">-->
<!--        <el-input-->
<!--          v-model="queryParams.bomAmount"-->
<!--          placeholder="请输入bom数量"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="祖级列表" prop="ancestors">-->
<!--        <el-input-->
<!--          v-model="queryParams.ancestors"-->
<!--          placeholder="请输入祖级列表"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="是否标识：1-是；2-否" prop="isFlag">-->
<!--        <el-input-->
<!--          v-model="queryParams.isFlag"-->
<!--          placeholder="请输入是否标识：1-是；2-否"-->
<!--          clearable-->
<!--          @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"
          v-hasPermi="['dms:bom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="bomList"
      row-key="deviceBomId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
<!--      <el-table-column label="父级标识" prop="parentId" />-->
      <el-table-column label="设备ID" align="center" prop="deviceId" />
      <el-table-column label="设备名称" align="center" prop="deviceId" >
        <template slot-scope="scope">
            <span
              v-for="(item, index) in ledgerList"
              :key="index"
              :value="item.ledgerList"
              v-if="scope.row.deviceId == item.deviceId"
            >
              {{ item.deviceName }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="bom数量" align="center" prop="bomAmount" />
<!--      <el-table-column label="祖级列表" align="center" prop="ancestors" />-->
<!--      <el-table-column label="是否标识：1-是；2-否" align="center" prop="isFlag" />-->
<!--      <el-table-column label="标识" align="center" prop="isFlag">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.is_flag" :value="scope.row.isFlag"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="备注" align="center" prop="remark" />
      <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="['dms:bom:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['dms:bom:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dms:bom:remove']"
          >删除</el-button>
        </template>

      </el-table-column>
    </el-table>
      </el-col>
    </el-row>
    <!-- 添加或修改设备BOM信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级标识" prop="parentId">
          <treeselect @input="change" v-model="form.parentId" :options="bomOptions" :normalizer="normalizer"
                      placeholder="请选择父级标识" />
        </el-form-item>
<!--        <el-form-item label="设备ID">-->
<!--          <el-input v-model="form.deviceId" placeholder="请输入设备ID，关联dms_base_device_ledger的device_id" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备名称" prop="deviceId" >
          <el-select v-model="form.deviceId" placeholder="请选择设备">
            <el-option
              v-for="item in ledgerList"
              :key="item.deviceId"
              :label="item.deviceName"
              :value="item.deviceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="bom数量" prop="bomAmount"  v-if="isShowBom">
          <el-input v-model="form.bomAmount" placeholder="请输入bom数量" />
        </el-form-item>
<!--        <el-form-item label="是否标识：1-是；2-否" prop="isFlag">-->
<!--          <el-input v-model="form.isFlag" placeholder="请输入是否标识：1-是；2-否" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="标识" prop="isFlag">-->
<!--          <el-radio-group v-model="form.isFlag">-->
<!--            <el-radio-->
<!--              v-for="dict in dict.type.is_flag"-->
<!--              :key="dict.value"-->
<!--              :label="parseInt(dict.value)"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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>
  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom ,selectBomByDeviceType} from "@/api/dms/bom";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listLedger } from '@/api/dms/ledger'
import { listDevicetype } from '@/api/dms/devicetype'

export default {
  name: "Bom",
  dicts: ['is_flag'],
  components: {
    Treeselect
  },
  data() {
    return {
      typeNames:undefined,
      devicetypeOptions:[],
      defaultProps: {
        children: "children",
        label: "typeName"
      },
      isShowBom:false,
      deptName:undefined,
      ledgerList:[],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 设备BOM信息表格数据
      bomList: [],
      bomLists: [],
      // 设备BOM信息树选项
      bomOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        deviceId: null,
        bomAmount: null,
        ancestors: null,
        isFlag: null,
        deviceName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "设备ID，关联dms_base_device_ledger的device_id不能为空", trigger: "blur" }
        ],
        bomAmount: [
          { required: true, message: "bom数量不能为空", trigger: "blur" },
          {  pattern: /^-?\d+\.?\d*$/, message: '请输入数字', trigger: 'blur'}
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeviceLedger();
    this.getTreeselectDeviceType();
  },
  methods: {
    change(){
      if (this.form.parentId != 0){
        this.isShowBom = true;
        this.form.bomAmount = null;
      }
      if (this.form.parentId ==0){
        this.isShowBom = false;
        this.form.bomAmount = 1;
      }
    },

    /** 查询设备台账信息列表 */
    getDeviceLedger() {
      this.loading = true;
      listLedger(this.queryParams).then(response => {
        this.ledgerList = response.rows;
      });
    },
    /** 查询设备BOM信息列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then(response => {
        this.bomList = this.handleTree(response.data, "deviceBomId", "parentId");
        this.loading = false;
      });
    },
    /** 转换设备BOM信息数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deviceBomId,
        label: node.deviceId,
        children: node.children
      };
    },
	/** 查询设备BOM信息下拉树结构 */
    getTreeselect() {
      listBom().then(response => {
        this.bomOptions = [];
        const data = { deviceBomId: 0, deviceId: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "deviceBomId", "parentId");
        this.bomOptions.push(data);
      });
    },
    /** 查询设备类型信息下拉树结构 */
    getTreeselectDeviceType() {
      listDevicetype().then(response => {
        this.devicetypeOptions = [];
        const data = { deviceTypeId: 0, typeName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "deviceTypeId", "parentId");
        this.devicetypeOptions.push(data);
        // console.log(data)
      });
    },
    //因为bom表没有设备类型，所以不能直接搜索 通过设备类型查询设备
    selectDeviceBom(){
      this.loading = true;
      selectBomByDeviceType(this.queryParams.deviceTypeId).then(response => {
        this.bomList = this.handleTree(response.data, "deviceBomId", "parentId");
        this.loading = false;
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.typeName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log(data.deviceTypeId)
      if(data.deviceTypeId ==0){
        this.resetQuery();
      }
      else {
      this.queryParams.deviceTypeId = data.deviceTypeId;
      this.selectDeviceBom();
      }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceBomId: null,
        parentId: null,
        deviceId: null,
        bomAmount: null,
        ancestors: null,
        isFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deviceName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();

    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.deviceName = null;
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.deviceBomId) {
        this.form.parentId = row.deviceBomId;
      } else {
        this.form.parentId = 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.parentId = row.deviceBomId;
      }
      getBom(row.deviceBomId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备BOM信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceBomId != 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.deviceBomId + '"的数据项？').then(function() {
        return delBom(row.deviceBomId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
