<template>
  <div class="app-container">
    <el-card style="margin-bottom: 10px" class="box-card">
      <el-row :gutter="20">
        <!--右侧用户数据-->
        <el-col :span="24" :xs="24">
          <!--头部搜索条件输入框  -->
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="线损对象编号" label-width="100px" prop="type">
              <input v-model="form.lineLossId" disabled />
            </el-form-item>
            <el-form-item label="线损对象名称" label-width="100px" prop="type">
              <input v-model="form.lineLossName" disabled />
            </el-form-item>
            <el-form-item label="监测点类型" label-width="100px" prop="type">
              <input disabled />
              <div style="margin-top: -30px">
                {{ form.monitorType == "2" ? "电" : "水" }}
              </div>
            </el-form-item>
            <el-form-item label="供入电量" label-width="100px" prop="type">
              <input v-model="form.inputUsage" disabled />
            </el-form-item>
            <el-form-item label="供出电量" label-width="100px" prop="type">
              <input v-model="form.outputUsage" disabled />
            </el-form-item>
            <el-form-item label="线损电量" label-width="100px" prop="type">
              <input v-model="form.lossUsage" disabled />
            </el-form-item>
            <el-form-item label="线损率" label-width="100px" prop="type">
              <input v-model="form.lossRate" disabled />
            </el-form-item>
            <el-form-item label="采集时间">
              <el-date-picker
                v-model="form.starttime"
                style="width: 240px"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <div>-</div>
            </el-form-item>
            <el-form-item
              ><el-date-picker
                v-model="form.endtime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 240px"
                type="datetime"
                placeholder="选择日期时间"
              ></el-date-picker
            ></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-col>
      </el-row>
    </el-card>

    <el-row style="margin-bottom: 10px" :gutter="20">
      <!--左侧部门数据-->

      <el-card style="height: 410px" class="box-card">
        <el-col style="padding-top: 30px" :span="12" :xs="24">
          <div
            style="width: 400px; height: 400px; margin-top: -40px"
            id="card"
          ></div>
        </el-col>
        <el-col :span="12" :xs="24">
          <div
            style="
              width: 400px;
              margin-left: 30px;
              height: 400px;
              margin-top: -40px;
            "
            id="card2"
          ></div>
        </el-col>
      </el-card>
    </el-row>
    <el-card style="margin-bottom: 30px" class="box-card">
      <el-row :gutter="20">
        <el-col :span="24" :xs="24">
          <!-- 用户表格 -->
          <el-table
            v-loading="loading"
            :data="userList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <!-- <el-table-column label="自增标识" align="center" key="objid" prop="objid" v-if="columns[0].visible" />
            <el-table-column label="日期" align="center" key="pointTime" prop="pointTime" v-if="columns[1].visible"
              :show-overflow-tooltip="true" /> -->
            <el-table-column
              label="监测点编号"
              align="center"
              key="monitor_id"
              prop="monitor_id"
              v-if="columns[0].visible"
            />
            <el-table-column
              label="监测点名称"
              align="center"
              key="monitor_name"
              prop="monitor_name"
              v-if="columns[1].visible"
            />
            <el-table-column
              label="耗量(kW·h)"
              align="center"
              key="expend"
              prop="expend"
              v-if="columns[2].visible"
            />
          </el-table>

          <!-- 分页 -->
          <!-- <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        /> -->
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      :title="title2"
      :visible.sync="opentwo"
      @close="canceltwo"
      width="400px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-col>
          <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="deptOptionsselect"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              show-checkbox
              default-expand-all
              highlight-current
              @check-change="handleNodeClicktwo"
            />
          </div>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormtwo">确 定</el-button>
        <el-button @click="canceltwo">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser2,
  treeDat,
  treeDattwo,
  treeDatthree,
  dnbCountingData,
  deptTreeSelect,
} from "@/api/ems/base/xiansunanalysis";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as echarts from "echarts";

export default {
  name: "TypeRelationq",
  dicts: ["statistical_unit"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // form:{lineLossId:this.$route.query.lineLossId,
      //   lineLossName:this.$route.query.lineLossName,
      //   monitorType:this.$route.query.monitorType
      // },
      form: this.$route.query,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      dateRangeone: "",
      dateRangetwo: "",
      formaaa: {},
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      defaultProps: {
        children: "children",
        label: "lable",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      opentwo: false,
      title2: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        isAsc: "asc",
        monitorId: "",
        monitorType: 2,
        params: {
          beginCollectTime: "",
          endCollectTime: "",
        },
      },

      // 列信息
      columns: [
        { key: 0, label: `监测点名称`, visible: true },
        { key: 1, label: `监测点名称`, visible: true },
        { key: 2, label: `耗量(kW·h)`, visible: true },
        // { key: 3, label: `监测点名称`, visible: true },
        // { key: 4, label: `耗量(kW·h)`, visible: true },
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      deptOptionsselect: [],
      //采集方式
      dict: [
        { label: "时", value: "hour" },
        { label: "天", value: "day" },
        { label: "月", value: "month" },
        { label: "年", value: "year" },
      ],
      dictone: [
        { label: "建筑", value: 0 },
        { label: "业态", value: 1 },
        { label: "分页", value: 2 },
      ],
      unitIdname: "",
      //柱状图
      // option: {
      //   xAxis: {
      //     type: 'category',
      //     data: ['1', '2']
      //   },
      //   yAxis: {
      //     type: 'value',
      //     axisLine: { show: true },
      //   },
      //   series: [
      //     {
      //       data: [1, 5],
      //       type: 'bar'
      //     }
      //   ]
      // },
      //饼状图：
      option: {
        tooltip: {
          trigger: "item",
          formatter: function (params) {
            return (
              params.data.name +
              "<br>" +
              "耗量:" +
              " " +
              params.data.value +
              " (" +
              params.percent +
              "%)"
            );
          },
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        series: [
          {
            name: "访问来源",
            type: "pie", // 设置图表类型为饼图
            radius: "55%", // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
            data: [
              // 数据数组，name 为数据项名称，value 为数据项值
            ],
          },
        ],
      },
      option2: {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        xAxis: {
          type: "category",
          axisPointer: {
            type: "shadow",
          },
          data: [],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            tooltip: {
              valueFormatter: function (value) {
                return value;
              },
            },
            data: [],
            type: "line", //和柱状图的区别
            areaStyle: {},
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.dateRangeone = new Date(new Date().setHours(0, 0, 0, 0));
    var d = new Date(this.dateRangeone);
    let m = ("0" + (d.getMonth() + 1)).slice(-2);
    let tian = ("0" + d.getDate()).slice(-2);
    let h = ("0" + d.getHours()).slice(-2);
    let M = ("0" + d.getMinutes()).slice(-2);
    let s = ("0" + d.getSeconds()).slice(-2);

    console.log("d", d);
    this.dateRangeone =
      d.getFullYear() + "-" + m + "-" + tian + " " + h + ":" + M + ":" + s;
    this.dateRangetwo = new Date(
      new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1
    );
    var d1 = new Date(this.dateRangetwo);
    let m1 = ("0" + (d1.getMonth() + 1)).slice(-2);
    let tian1 = ("0" + d1.getDate()).slice(-2);
    let h1 = ("0" + d1.getHours()).slice(-2);
    let M1 = ("0" + d1.getMinutes()).slice(-2);
    let s1 = ("0" + d1.getSeconds()).slice(-2);
    console.log("tian1.length", tian1);
    this.dateRangetwo =
      d1.getFullYear() +
      "-" +
      m1 +
      "-" +
      tian1 +
      " " +
      h1 +
      ":" +
      M1 +
      ":" +
      s1;
    //this.dateRangetwo = d1.getFullYear()+ '-'+m1+ '-'+tian1+ ' '+ h1+ ':'+M1+':'+s1;
    console.log("????", this.form);
    this.getList();
  },
  mounted() {
    var chartDom = document.getElementById("card");
    var myChart = echarts.init(chartDom);
    this.option && myChart.setOption(this.option);
    var chartDom = document.getElementById("card2");
    var myChart = echarts.init(chartDom);
    this.option2 && myChart.setOption(this.option2);
    console.log(">>>", this.form);
  },
  methods: {
    canceltwo() {
      this.opentwo = false;
      this.resettwo();
    },
    resettwo() {
      this.formadd = {
        monitorIds: [],
      };
    },
    // 二次弹窗节点单击事件
    handleNodeClicktwo(data) {
      console.log("data", data);
      this.formaaa.monitorName = data.name;
      this.formaaa.monitorId = data.id;

      // this.handleQuery();
    },
    //二次弹窗 取消按钮
    canceltwo() {
      this.formaaa.monitorName = "";
      this.formaaa.monitorId = "";
      this.opentwo = false;
      //this.reset();
    },
    //二次弹窗确认按钮
    submitFormtwo: function () {
      this.opentwo = false;
      this.unitIdname = this.formaaa.monitorName;
      this.queryParams.unitId = this.formaaa.monitorId;
      //this.canceltwo();
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      this.queryParams.params.beginCollectTime = this.form.starttime;
      this.queryParams.params.endCollectTime = this.form.endtime;
      this.queryParams.monitorId = this.form.monitorId;
      this.queryParams.monitorType = this.form.monitorType;
      console.log("this.datatimeone", this.queryParams);
      listUser2(this.queryParams).then((response) => {
        //表格数据处理
        console.log("response.rows", response.rows);
        let idArr = []; //相同id放在同一数组中
        let resultArr = JSON.parse(JSON.stringify(response.rows)); //最终结果数组
        console.log("fr fsdfsdjkaf jk", resultArr);
        for (let i = 0; i < resultArr.length; i++) {
          for (let j = i + 1; j < resultArr.length; j++) {
            if (resultArr[i].monitor_id === resultArr[j].monitor_id) {
              console.log("重复", resultArr[i], resultArr[j]);
              resultArr[i].expend = resultArr[i].expend + resultArr[j].expend;
              resultArr.splice(j, 1);
            }
          }
        }
        console.log("resultArr", resultArr);
        resultArr.map((item, index) => {
          item.expend = item.expend.toFixed(2);
        });
        this.userList = resultArr;
        console.log("this.userList", this.userList);
        this.total = response.total;
        this.loading = false;
        //饼状图数据处理
        let weichliarr = JSON.parse(JSON.stringify(this.userList));
        let seriesdata = [];
        weichliarr.map((item, index) => {
          seriesdata.push({ value: item.expend, name: item.monitor_name });
        });
        this.option.series[0].data = seriesdata;
        var chartDom = document.getElementById("card");
        var myChart = echarts.init(chartDom);
        this.option && myChart.setOption(this.option);
        //折线图数据处理
        let userList2 = JSON.parse(JSON.stringify(response.rows));
        let idArr1 = []; //相同id放在同一数组中
        let resultArr1 = []; //最终结果数组
        for (let i = 0; i < userList2.length; i++) {
          let index = idArr1.indexOf(userList2[i].pointTime);
          if (index > -1) {
            //有相同id存在的话,获取index索引位置
            resultArr1[index].expend += userList2[i].expend; //取相同id的value累加
          } else {
            idArr1.push(userList2[i].pointTime);
            resultArr1.push(userList2[i]);
          }
        }
        let options2xdata = [];
        let options2ydata = [];
        console.log("resultArr1", resultArr1);
        resultArr1.map((item, index) => {
          options2xdata.push(item.pointTime);
          options2ydata.push(item.expend);
        });
        this.option2.xAxis.data = options2xdata;
        this.option2.series[0].data = options2ydata;
        var chartDom = document.getElementById("card2");
        var myChart = echarts.init(chartDom);
        this.option2 && myChart.setOption(this.option2);
      });
    },
    //数组转树形结构
    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;
    },
    selemonitid() {
      this.deptOptionsselect = [];
      if (this.queryParams.unit == 0) {
        treeDat().then((response) => {
          response.map((item, index) => {
            item, (item.oid = item.id), (item.lable = item.name);
          });
          this.deptOptionsselect = this.tranListToTreeData(response);
        });
      } else if (this.queryParams.unit == 1) {
        treeDattwo().then((response) => {
          response.map((item, index) => {
            item, (item.oid = item.id), (item.lable = item.name);
          });
          this.deptOptionsselect = this.tranListToTreeData(response);
        });
      } else if (this.queryParams.unit == 2) {
        treeDatthree().then((response) => {
          response.map((item, index) => {
            item, (item.oid = item.id), (item.lable = item.name);
          });
          this.deptOptionsselect = this.tranListToTreeData(response);
        });
      }
      this.opentwo = true;
      this.title2 = "统计信息管理选择";
    },
    // /** 真查询部门下拉树结构 */
    // getDeptTree() {
    //   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)
    //     //this.deptOptions = response.data;
    //   });
    // },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.lable.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.monitorSubset = data.monitorId;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.dateRange = [];
      this.form.starttime = "";
      this.form.endtime = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      let paramsexport = JSON.parse(JSON.stringify(this.queryParams));
      delete paramsexport.pageSize;
      delete paramsexport.pageNum;
      this.download(
        "/energy/record/dnbInstant/export",
        {
          ...paramsexport,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.tree {
  width: 220px;

  ::v-deep .el-tree-node {
    white-space: normal; //关键代码!!!!!!!!!

    .el-tree-node__content {
      height: 100%;
      align-items: start;
    }
  }
}
::v-deep .box-card .el-form--inline .el-form-item {
  display: inline-block;
  margin-right: 40px;
  vertical-align: top;
}
// ::v-deep .el-card__body{
//   padding: 0px 0px 0px 0px
// }
</style>
