<template>
  <!-- 使用 useVirtual 属性开启虚拟滚动 使用虚拟滚动时，必须要固定表格高度和行高 -->
  <div class="pd10">
    <!-- 程序升级管理 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="终端型号:">
        <el-select v-model="formInline.teriminal" placeholder="请选择终端型号">
          <el-option
            v-for="item in teriminaloption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="终端状态:">
        <el-select
          v-model="formInline.teriminalstatus"
          placeholder="请选择终端状态"
        >
          <el-option
            v-for="item in teriminalstatusoption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="通讯状态:">
        <el-select v-model="formInline.state" placeholder="请选择通讯状态">
          <el-option
            v-for="item in stateoption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="程序版本:">
        <el-select v-model="formInline.program" placeholder="请选择程序版本">
          <el-option
            v-for="item in programoption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList"
          >查询</el-button
        >
        <el-button type="primary" icon="el-icon-download">导出</el-button>
        <el-button type="primary" icon="el-icon-check">批量升级</el-button>
        <!-- <el-button @click="$refs.plTreeTable.setAllTreeExpansion()"
                      >展开全部</el-button
                    > -->
        <!-- <el-button @click="$refs.plTreeTable.clearTreeExpand()"
          >关闭所有</el-button
        > -->
      </el-form-item>
      <el-form-item label="筛选:">
        <el-input v-model="formInline.search" placeholder="输入关键字筛选" />
      </el-form-item>
    </el-form>

    <!--我是pl-table大数据树形表格 必须指定 row-key  必须开启use-virtual-->
    <!-- <div :style="`height:${vh}px; overflow: hidden;`"> -->
    <!-- <el-input v-model="ssbsearch" @input="filert"  clearable @clear="clear" size="" placeholder="根据省级,市区,变电站进线筛选" style="width:30%;margin-left:20px"></el-input> -->
    <u-table
      stripe
      ref="plTreeTable"
      header-cell-class-name="table_header"
      highlight-current-row
      element-loading-text="数据加载中"
      fixed-columns-roll
      :data="treeTable"
      :row-height="rowHeight"
      :height="vh"
      :treeConfig="{
        children: 'children',
        iconClose: 'el-icon-arrow-right',
        iconOpen: 'el-icon-arrow-down',
        expandAll: true,
      }"
      v-loading="loading"
      @toggle-trand="toggleTreeExpand"
      use-virtual
      row-id="id"
      :row-config="{ isCurrent: true, isHover: true }"
      border
    >
      <!-- beautify-table
                header-drag-style -->
      <!--u-table大数据表格 你需要在列上指定某个列显示展开收起 treeNode属性-->
      <u-table-column
        prop="name"
        label="电网拓扑"
        :treeNode="true"
        min-width="150"
        :showOverflowTooltip="true"
        :show-overflow-tooltip="true"
      ></u-table-column>
      <u-table-column
        prop="devType"
        label="终端型号"
        align="center"
        :formatter="formFilter"
        :showOverflowTooltip="true"
        :show-overflow-tooltip="true"
      ></u-table-column>
      <u-table-column
        prop="versionName"
        label="版本号"
        align="center"
      ></u-table-column>
      <u-table-column
        prop="protocol"
        label="协议版本"
        align="center"
      ></u-table-column>
      <u-table-column
        prop="versionDate"
        label="版本日期"
        align="center"
      ></u-table-column>
      <u-table-column prop="runFlag" label="终端状态" align="center">
        <template slot-scope="scope">
          <el-tag
            type="primary"
            v-if="scope.row.runFlag === 0"
            style="color: #fff; background: #0099cc"
            size="small"
            >投运</el-tag
          >
          <el-tag
            type="primary"
            v-if="scope.row.runFlag === 1"
            style="color: #fff; background: #996600"
            size="small"
            >热备用</el-tag
          >
          <el-tag
            type="primary"
            v-if="scope.row.runFlag === 2"
            style="color: #fff; background: #cc0000"
            size="small"
            >停运</el-tag
          >
        </template>
      </u-table-column>
      <u-table-column prop="comFlag" label="通讯状态" align="center">
        <template slot-scope="scope">
          <el-tag
            type="primary"
            v-if="scope.row.comFlag === 0"
            style="color: #fff; background: #cc0000"
            size="small"
            >中断</el-tag
          >
          <el-tag
            type="primary"
            v-if="scope.row.comFlag === 1"
            style="color: #fff; background: #2e8b57"
            size="small"
            >正常</el-tag
          >
        </template>
      </u-table-column>
      <u-table-column
        prop="updateUser"
        label="升级人员"
        align="center"
      >
      <template slot-scope="scope">
        <!-- <span>{{ scope.row.updateBy!==null? scope.row.updateBy:'--'}}</span> -->
          <span v-if="scope.row.updateBy==null">--</span>
          <span v-if="scope.row.updateBy='/'">--</span>
          <!-- <span v-if="scope.row.updateBy !==null">{{ scope.row.updateBy }}</span> -->
        </template>
    </u-table-column>
      <u-table-column
        prop="updateTime"
        label="最新升级时间"
        align="center"
      ></u-table-column>
      <u-table-column align="center" width="220" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.level == 4"
            type="primary"
            size="mini" icon="el-icon-finished"
            @click="updateprogram(scope.row)"
            >升级</el-button
          >
          <el-button
            v-if="scope.row.level == 4"
            :disabled="scope.row.state == 1 ? true : false"
            type="primary"
            size="mini" icon="el-icon-view"
            @click="queryview(scope.row)"
            >日志查看</el-button
          >
        </template>
      </u-table-column>
      <!-- <u-table-column align="center" 
                    v-for="item in columns"
                    :key="item.id"
                    :prop="item.prop"
                    :label="item.label"
                    :min-width="item.width"/>-->
    </u-table>

    <!--升级日志查看-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title + '#终端升级日志查看'"
      :visible.sync="dialogVisible"
      width="70%"
      class="eldialot"
      :before-close="handleClose"
    >
      <el-table
        stripe
        :data="logtableData"
        header-cell-class-name="table_header"
        border
        :height="height"
        style="width: 100%"
        highlight-current-row
      >
        <el-table-column
          prop="devTypeName"
          align="center"
          label="装置序号"
        ></el-table-column>
        <el-table-column
          prop="versionId"
          align="center"
          label="版本序号"
        ></el-table-column>
        <el-table-column
          prop="flag"
          align="center"
          label="版本状态"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              type="primary"
              v-if="scope.row.flag == true"
              style="color: #fff; background: #fc0"
              >前期版本</el-tag
            >
            <el-tag
              type="primary"
              v-if="scope.row.flag == false"
              style="color: #fff; background: #0c0"
              >当前版本</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="result"
          align="center"
          label="升级结果"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              type="primary"
              v-if="scope.row.result == false"
              style="color: #fff; background: #f30"
              >升级失败</el-tag
            >
            <el-tag
              type="primary"
              v-if="scope.row.result == true"
              style="color: #fff; background: #093"
              >升级成功</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag
              type="primary"
              v-if="scope.row.state == false"
              style="color: #fff; background: #f30"
              >删除</el-tag
            >
            <el-tag
              type="primary"
              v-if="scope.row.state == true"
              style="color: #fff; background: #093"
              >正常</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="createBy"
          align="center"
          label="创建用户"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          align="center"
          label="升级时间"
        ></el-table-column>
        <el-table-column
          prop="updateBy"
          align="center"
          label="升级人员"
        >
      </el-table-column>
      </el-table>
    </el-dialog>
    <!--升级弹窗-->
    <el-dialog
      :close-on-click-modal="false"
      :title="protitle + '#终端程序升级'"
      :visible.sync="prodialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-col v-for="(item, index) in percentageoption" :key="index">
        <span style="font-size: 14px; font-weight: bold">{{ item.name }}</span
        >:
        <el-progress
          :text-inside="true"
          :stroke-width="24"
          :percentage="item.percentage"
          :status="item.status"
          :format="format"
        ></el-progress>
      </el-col>
    </el-dialog>
  </div>
  <!-- </div> -->
</template>

<script>
import version from "@/api/device/version.js";
import { dicData } from "@/assets/commjs/dictypeData";
// 下面是关于pl-table的树形数据的介绍，希望读完下面的文字

// （最大数量500）当然你可以更多，那么只会导致你遍历时间多，页面等待时间长，（并非渲染节点时间长）
// 另外 就以下的这个层级，总数据量展开后，就是 500 + 500 x 3 + 3 x 1 = 2003 的总数据量
// 如果你 第一级是500， 第二级也是500， 第三级是10。 那么你的数据量就是 500 + 500 x 500 + 500 x 10 的总数据量，这是非常吓人的
// 所以结合自己情况去给树数据，不要瞎乱给下面的数据，树节点避免不鸟去递归，如果你的数据量很大很大，那么你会死在遍历上。
// 注意,注意，注意：并非第一级不能超过500，是想告诉你们嵌套里面子节点层级数据量不要太大。比如你可这样的： 第一级为1000， 第二级为2-5的数据量，
// 第三级为2-5的数据量....， 那么这样算下来，就是 1000 + 1000 x 5  + 5 x 5  = 6025的数据量，应该是可以的，但是记住要是太大的嵌套数据。那只会导致
// 程序卡在遍历数据上，因为程序需要慢慢去递归遍历。这是没有办法的。

// 但是传统el-table  或者el-tree他们数据量超过200  就会卡。 所以我们已经很好的优化了这一点。不过看来对于树形数据的要求，应该数据量不会太大。
// 你可以在pl-table的基础上去改改样式，就可以变相的去实现el-tree的组件了哦，你隐藏下头部，把行的高度给小一点。然后隐形边框线。是不是就是el-tree了呢？？？

var shuju = [];
export default {
  name: "home",
  data() {
    return {
      formInline: {},
      title: "",
      protitle: "",
      ssbsearch: "",
      rowHeight: 20,
      search: "",
      expandRow: [],
      columns: [
        // {
        //   id:'0',
        //   prop: "name",
        //   label: "电网拓扑",
        //   width: 120,
        //   treeNode: true,
        //   showOverflowTooltip: true,
        // },
        {
          id: "1",
          prop: "devType",
          label: "终端型号",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          id: "2",
          prop: "versionName",
          label: "版本号",
          width: 230,
          showOverflowTooltip: true,
        },
        {
          id: "3",
          prop: "protocol",
          label: "协议版本",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          id: "4",
          prop: "versionDate",
          label: "版本日期",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          id: "5",
          prop: "runFlag",
          label: "终端状态",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          id: "6",
          prop: "comFlag",
          label: "通讯状态",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          id: "7",
          prop: "updateUser",
          label: "升级人员",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          id: "8",
          prop: "updateTime",
          label: "最新升级时间",
          width: 100,
          showOverflowTooltip: true,
        },
      ],
      top: 0,
      height: "",
      vh: undefined,
      pageForm: {
        total: 1000,
        pageSize: 10,
        currentPage: 1,
      },
      tableData: shuju,
      //终端型号
      teriminal: "",
      teriminaloption: [],
      //终端状态
      teriminalstatus: "",
      teriminalstatusoption: [
        { name: "全部", id: "" },
        { name: "投运", id: 0 },
        { name: "热备用", id: 1 },
        { name: "停运", id: 2 },
      ],
      //通讯状态
      state: "",
      stateoption: [
        { name: "全部", id: "" },
        { name: "正常", id: 1 },
        { name: "中断", id: 0 },
      ],
      //程序版本
      program: "",
      programoption: [],
      //弹窗列表
      logtableData: [],
      status: "",
      //进度条对象
      percentageoption: [
        {
          name: "1号测试终端",
          status: "exception",
          percentage: 20,
        },
        {
          name: "2号测试终端",
          status: "warning",
          percentage: 50,
        },
        {
          name: "3号测试终端",
          status: "success",
          percentage: 90,
        },
      ],
      loading: false,
      dialogVisible: false,
      prodialogVisible: false,
    };
  },
  computed: {
    treeTable: function () {
      var searchValue = this.formInline.search;
      if (searchValue) {
        // 一般表格的查询
        // return  this.tableData.filter(function(dataNews){
        //   return Object.keys(dataNews).some(function(key){
        //     return String(dataNews[key]).toLowerCase().indexOf(search) > -1
        //   })
        // }
        let treeData = this.tableData;
        let handleTreeData = this.handleTreeData(treeData, searchValue);
        this.setExpandRow(handleTreeData);
        this.expandRow = this.expandRow.join(",").split(",");
        return handleTreeData;
      }
      return this.tableData;
    },
  },
  created() {
    this.getDevType();
    this.getList();
  },
  mounted() {
  
    // 设置表格数据

    //  this.$nextTick(() => {
      this.setHeight()
        window.addEventListener('resize', this.setHeight)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
          this.vh = window.sessionStorage.getItem("appheight") - 55;
    this.height = window.sessionStorage.getItem("appheight") - 230;
          
        },
    formFilter(row, column) {
      ///console.log("++++++++++++++++++++++++=",row)
        let title = ''
        dicData("Dev_Type", []).forEach((item) => {
          if(row.devType != null ){
            if (item.id == row.devType) {
              title = item.name;
             }
          }else{
            title = '/';
          }
         
        });
        return title;
      
    },
    filterNode(value, data, node) {
      if (!value) {
        return true;
      }
      let _array = []; //这里使用数组存储 只是为了存储值。
      this.getReturnNode(node, _array, value);
      let result = false;
      _array.forEach((item) => {
        result = result || item;
      });
      return result;
    },
    getReturnNode(node, _array, value) {
      let isPass =
        node.data && node.data.name && node.data.name.indexOf(value) !== -1;
      isPass ? _array.push(isPass) : "";
      this.index++;
      if (!isPass && node.name != 1 && node.parent) {
        this.getReturnNode(node.parent, _array, value);
      }
    },
    //获取所有终端型号
    getDevType() {
      var code = "Dev_Type";
      this.teriminaloption = dicData(code, [], 1);
    },
    selectAll(val) {
      // <!-- console.log(val); -->
    },
    selectable(row, index) {
      if (index === 1) {
        return false;
      } else {
        // console.log(row, index);

        return true;
      }
    },
    // 合计
    summaryMethod({ columns, data }) {
      // 平均值算法（不需要自己去掉）
      function cacl(arr, callback) {
        let ret;
        for (let i = 0; i < arr.length; i++) {
          ret = callback(arr[i], ret);
        }
        return ret;
      }
      // 平均值算法（不需要自己去掉）
      Array.prototype.sum = function () {
        return cacl(this, function (item, sum) {
          if (typeof sum == "undefined") {
            return item;
          } else {
            return (sum += item);
          }
        });
      };
      // 平均值算法（不需要自己去掉）
      Array.prototype.avg = function () {
        if (this.length == 0) {
          return 0;
        }
        return this.sum(this) / this.length;
      };
      const means = []; // 合计
      const fenceSums = []; // 平均值
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push("合计");
          fenceSums.push("平均值");
        } else {
          const values = data.map((item) => Number(item[column.property]));
          // 合计
          if (!values.every((value) => isNaN(value))) {
            means[columnIndex] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // means[columnIndex] += ' 元'
            // 改变了ele的合计方式，扩展了合计场景
            // 你以为就只有上面这样玩吗？错啦，你还可以自定义样式哦
            // means[columnIndex] = '<span style="color: red">' + means[columnIndex] + '元</span>'
            means[columnIndex] =
              '<span style="color: red">' +
              means[columnIndex] +
              "元</span><br/><span>123</span>";
          } else {
            means[columnIndex] = "";
          }
          // 平均值
          const precisions = [];
          let notNumber = true;
          values.forEach((value) => {
            if (!isNaN(value)) {
              notNumber = false;
              let decimal = ("" + value).split(".")[1];
              precisions.push(decimal ? decimal.length : 0);
            }
          });
          if (!notNumber) {
            fenceSums[columnIndex] = values.avg();
          } else {
            fenceSums[columnIndex] = "";
          }
        }
      });
      // 返回一个二维数组的表尾合计
      return [means, fenceSums];
    },
    setHei(val) {
      this.height = val;
    },
    tableBodyScroll({ scrollTop }) {
      this.top = scrollTop;
    },
    allSelection() {
      this.$refs.plTable.toggleAllSelection();
    },
    clearSelection() {
      this.$refs.plTable.clearSelection();
      this.$refs.plTable2.clearSelection();
    },
    setData(num) {
      this.data.tableData = Array.from({ length: num }, (_, idx) => ({
        id: idx + 1,
        date: "2016-05-03",
        name: 1,
        ab: "欢迎使用pl-table",
        address: 1 + idx,
      }));
    },
    scrollBottom() {
      this.$refs.plTable.scrollBottom();
    },
    pagingScrollTopLeft(val) {
      this.$refs.plTable.pagingScrollTopLeft(val, 0);
    },
    // 分页事件
    handlePageSize({ page, size }) {
      // console.log(page, size);
    },
    // 获取已经展开的节点
    getTreeExpansionEvent() {
      // console.log(this.$refs.plTreeTable.getTreeExpandRecords());
    },
    //  树形表格过滤
    handleTreeData(treeData, searchValue) {
      // debugger
      if (!treeData || treeData.length === 0) {
        return [];
      }
      const array = [];
      for (let i = 0; i < treeData.length; i += 1) {
        let match = false;
        for (let pro in treeData[i]) {
          if (typeof treeData[i][pro] == "string") {
            match = treeData[i][pro].includes(searchValue);
            if (match) break;
          }
        }

        if (
          this.handleTreeData(treeData[i].children, searchValue).length > 0 ||
          match
        ) {
          array.push({
            ...treeData[i],
            children: this.handleTreeData(treeData[i].children, searchValue),
          });
        }
      }
      return array;
    },
    toggleTreeExpand() {},
    // 将过滤好的树形数据展开
    setExpandRow(handleTreeData) {
      if (handleTreeData.length) {
        for (let i of handleTreeData) {
          this.expandRow.push(i.id);
          if (i.children.length) {
            this.setExpandRow(i.children);
          }
        }
      }
    },
    selected(row, index) {
      if (row.level !== 4) {
        return false; //不可勾选
      } else {
        return true; //可勾选
      }
    },
    //日志查看
    queryview(row) {
      this.title = row.name;
      this.dialogVisible = true;
      let data = {
        id: row.id,
      };
      version.getTerminalUpLog(data).then((res) => {
        this.logtableData = res.data;
      });
    },
    //关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.prodialogVisible = false;
    },
    //升级操作
    updateprogram(row) {
      this.protitle = row.name;
      this.prodialogVisible = true;
    },
    format(percentage) {
      if (percentage <= 100 && percentage >= 90) {
        this.status = "success";
        return percentage === 100 ? "升级成功" : `${percentage}%`;
      } else if (percentage > 0 && percentage < 50) {
        this.status = "exception";
        return percentage <= 20
          ? "升级失败" + percentage + "%"
          : `${percentage}%`;
      } else if (percentage > 0 && percentage <= 50) {
        this.status = "warning";
        return percentage <= 50 ? "升级中断" : `${percentage}%`;
      }
    },
    //批量操作
    handleSelectionChange(val) {
      // console.log(val);
    },
    //查看主列表
    getList() {
      let a = new Date().getTime();
      let data = {
        comFlag: this.formInline.state,
        runFlag: this.formInline.teriminalstatus,
        devType: this.formInline.teriminal,
        version: this.formInline.program,
      };
      this.loading = true;
      version.getList(data).then((response) => {
        if (response.code === "A0000") {
          this.filertData = JSON.parse(JSON.stringify(response.data));
          this.treeData = JSON.parse(JSON.stringify(response.data));
          this.treeData2 = JSON.parse(JSON.stringify(this.treeData));
          this.treeData3 = JSON.parse(JSON.stringify(this.treeData));
          this.treeData4 = JSON.parse(JSON.stringify(this.treeData));
          var data = response.data;

          this.tableData = data;
          this.loading = false;
          // this.$refs.plTreeTable.reloadData(data)
        }
      });

      // this.tableData = response.data
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../../styles/comStyle.less");
::v-deep .el-form-item--small .el-form-item__content,
.el-form-item--small .el-form-item__label {
  height: 32px;
}
::v-deep .el-select {
  width: 150px;
}
// ::v-deep .plTableBox .el-table td,
// .plTableBox .el-table th.is-leaf {
//   border: 1px solid #ece9e9;
//   border-bottom: 1px solid #023630;
// }
// ::v-deep .plTableBox .el-table--small th {
//   padding: 8px 0;
//   border: 1px solid #012920;
// }
</style>
<style lang="scss" scoped>

</style>
