<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="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :default-expanded-keys="['1','2']"
            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">
      <el-form-item label="计量设备编号"   prop="monitorId">
        <el-input
          v-model="queryParams.monitorId"
          placeholder="请输入计量设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="能源类型" prop="monitorType">-->
<!--        <el-select v-model="queryParams.monitorType" placeholder="请选择能源类型" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.energy_type"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="类型对应关系"  prop="type">-->
<!--        <el-select v-model="queryParams.type" @change="gettreedata" placeholder="请选择类型对应关系" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.statistical_unit"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:typeRelation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeRelationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="自增标识" align="center" prop="objid" />-->
<!--      <el-table-column label="类型" align="center" prop="type">-->
<!--        <template slot-scope="scope1">-->
<!--          <dict-tag  :options="dict.type.statistical_unit" :value="scope1.row.type"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="类型对应关系" align="center" prop="unitName" />-->
      <el-table-column label="计量设备编号" align="center" prop="monitorId" />
      <el-table-column label="计量设备名称" align="center" prop="monitorName" />
      <el-table-column label="能源类型名称" align="center" prop="monitorType" >
        <template slot-scope="scope1">
          <dict-tag :options="dict.type.energy_type" :value="scope1.row.monitorType"/>
        </template>
      </el-table-column>
      <el-table-column label="比率" align="center" prop="rate" />
      <el-table-column label="计算方式" align="center" prop="formulaMode" >
        <template slot-scope="scope1">
          <!-- <dict-tag :options="list" :value="scope1.row.formulaMode"/> -->
          <el-tag>{{scope1.row.formulaMode==0?'加':'减'}}</el-tag>
        </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="['base:typeRelation:edit']"
          >编辑</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="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="计量设备编号" prop="monitorId">
          <el-input v-model="form.monitorId" disabled placeholder="请输入计量设备编号" />
        </el-form-item>
        <el-form-item label="比率" prop="rate">
          <el-input v-model="form.rate" placeholder="" />
        </el-form-item>
        <el-form-item label="计算方式" prop="formulaMode">
        <el-select v-model="form.formulaMode" placeholder="" clearable>
          <!-- <el-option
            v-for="dict in dict.type.statistical_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          /> -->
          <el-option
            v-for="dict in list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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 { listTypeRelation, getTypeRelation, delTypeRelation, addTypeRelation, updateTypeRelation,treeDat,treeDattwo,treeDatthree } from "@/api/ems/base/typeRelation";

export default {
  name: "TypeRelation",
  dicts: ['statistical_unit', 'energy_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //树
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 总条数
      total: 0,
      // 计量与类型对应关系表格数据
      typeRelationList: [],
      // 弹出层标题
      title: "",
      deptName: undefined,
      // 是否显示弹出层
      open: false,
      name:undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        monitorId: null,
        type: '0',
        monitorType:null,
        relationId: null,
        isAsc: 'asc'
      },
      list:[
        {label:'加',value:0},
        {label:'减',value:1}
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDeptTree();
    this.getList();
  },
  methods: {
    /** 查询计量与类型对应关系列表 */
    getList() {
      this.loading = true;
      listTypeRelation(this.queryParams).then(response => {
        this.typeRelationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    gettreedata() {
      this.getDeptTree();
    },
    tranListToTreeData(list) {
  // 最终要产出的树状数据的数组
  const treeList = []
  // 所有项都使用对象存储起来
  const map = {}

  // 建立一个映射关系：通过id快速找到对应的元素
  list.forEach(item => {
    if (!item.children) {
      item.children = []
    }
    map[item.id] = item
  })

  list.forEach(item => {
    // 对于每一个元素来说，先找它的上级
    //    如果能找到，说明它有上级，则要把它添加到上级的children中去
    //    如果找不到，说明它没有上级，直接添加到 treeList
    const parent = map[item.pId]
    // 如果存在则表示item不是最顶层的数据
    if (parent) {
      parent.children.push(item)
    } else {
      // 如果不存在 则是顶层数据
      treeList.push(item)
    }
  })
  // 返回出去
  return treeList
},
    /** 真查询部门下拉树结构 */
    getDeptTree() {
      if(this.queryParams.type== 0){
        treeDat().then(response => {
        response.map((item,index)=>{
          item,
          item.oid=item.id,
          item.lable = item.name
        })
        this.deptOptions = this.tranListToTreeData(response);
        console.log(this.deptOptions)
      });
      console.log(this.deptOptions)
      }else if(this.queryParams.type== 1){
        treeDattwo().then(response => {
        response.map((item,index)=>{
          item,
          item.oid=item.id,
          item.lable = item.name
        })
        this.deptOptions = this.tranListToTreeData(response);
        console.log(this.deptOptions)
      });
    } else if(this.queryParams.type== 2){
      treeDatthree().then(response => {
        response.map((item,index)=>{
          item,
          item.oid=item.id,
          item.lable = item.name
        })
        this.deptOptions = this.tranListToTreeData(response);
        console.log(this.deptOptions)
      });
      }

    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.lable.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.relationId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        objid: null,
        monitorId: null,
        type: null,
        relationId: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.objid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加计量与类型对应关系";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const objid = row.objid || this.ids;
       this.form = row;
        this.open = true;
        this.title = "修改计量与类型对应关系";
      // getTypeRelation(objid).then(response => {

      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.objid != null) {
            updateTypeRelation({
              objid: this.form.objid,
              monitorId: this.form.monitorId,
              rate: this.form.rate,
              formulaMode:this.form.formulaMode,
              remark: this.form.remark
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTypeRelation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const objids = row.objid || this.ids;
      this.$modal.confirm('是否确认删除计量与类型对应关系编号为"' + objids + '"的数据项？').then(function() {
        return delTypeRelation(objids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let paramsexport = JSON.parse(JSON.stringify(this.queryParams));
      delete paramsexport.relationId;
      console.log('this.queryParams',this.queryParams)
      this.download('/ems/base/typeRelation/export', {
        ...paramsexport,
      }, `typeRelation_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
