<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-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="采集时间">
            <el-date-picker
              v-model="dateRangeone"
              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="dateRangetwo"
              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-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <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="monitorId"
            prop="monitorId"
            v-if="columns[0].visible"
          />
          <el-table-column
            label="计量设备名称"
            align="center"
            key="monitorName"
            prop="monitorName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="采集时间"
            align="center"
            key="collectTime"
            prop="collectTime"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="正向有功(kW·h)"
            align="center"
            key="zxyg"
            prop="zxyg"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="采集方式"
            align="center"
            key="collectType"
            prop="collectType"
            v-if="columns[4].visible"
            width="120"
          >
            <template slot-scope="scope1">
              <div>
                {{
                  scope1.row.collectType == 0
                    ? "手动"
                    : scope1.row.collectType == 1
                    ? "自动"
                    : "抄表"
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</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="600px" append-to-body>
      <el-form ref="formadd" :model="formadd" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="计量设备名称" prop="nickName">
              <el-input
                @click.native="istoselect"
                readonly
                placeholder=""
                v-model="formadd.monitorName"
                class="input-with-select"
              >
                <el-button
                  @click="istoselect"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
              <!-- <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" /> -->
              <!-- <el-input
              focus="istoselect"
                placeholder="请输入内容"
                prefix-icon="el-icon-search"
                v-model="input2">
              </el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="采集时间" prop="collectTime">
              <el-date-picker
                v-model="formadd.collectTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="抄录数值" prop="phonezxygnumber">
              <el-input v-model="formadd.zxyg" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>
    <!-- 二次弹窗 -->
    <el-dialog
      :title="title2"
      :visible.sync="opentwo"
      width="400px"
      :append-to-body="false"
    >
      <el-form ref="form" :model="form1" label-width="80px">
        <el-col>
          <div class="head-container">
            <el-input
              v-model="deptName1"
              placeholder="请输入计量设备名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <el-scrollbar style="height: 50vh">
            <div class="head-container">
              <el-tree
                :data="deptOptionstwo"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree1"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleNodeClicktwo"
              />
            </div>
          </el-scrollbar>
        </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 {
  listUser,
  delUser,
  addUser,
  updateUser,
  deptTreeSelect,
} from "@/api/ems/base/additionalRecording";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      pageNum:"",
      pageSize: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      deptOptionstwo: undefined,
      // 是否显示弹出层
      open: false,
      //二次弹出层
      opentwo: false,
      // 部门名称
      deptName: undefined,
      deptName1: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      dateRangeone: "",
      dateRangetwo: "",
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      formadd: {},
      form1: {},
      formaaa: {},
      defaultProps: {
        children: "children",
        label: "lable",
      },
      title2: "",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        //二次弹窗
        opentwo: false,
        // 弹出层标题（用户导入）
        //title: "",

        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // orderByColumn: "collectTime",
        objid:"",
        collectType: 0,
       // isAsc: "desc",
        monitorId: "",
        params: {
          beginCollectTime: "",
          endCollectTime: "",
        },
      },
      // 列信息
      columns: [
        { key: 0, label: `计量设备编号`, visible: true },
        { key: 1, label: `计量设备名称`, visible: true },
        { key: 2, label: `采集时间`, visible: true },
        { key: 3, label: `正向有功(kW·h)`, visible: true },
        { key: 4, label: `采集方式`, visible: true },
      ],
      // 表单校验
      rules: {
        monitorId: [{ required: true, message: "计量设备名称不能为空" }],
        collectTime: [{ required: true, message: "采集时间不能为空" }],
        zxyg: [{ required: true, message: "抄录数值不能为空" }],
        // 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"
        //   }
        // ]
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    deptName1(val) {
      this.$refs.tree1.filter(val);
    },
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      this.queryParams.params.beginCollectTime = this.dateRangeone;
      this.queryParams.params.endCollectTime = this.dateRangetwo;
      this.queryParams.params.beginTime = this.dateRangeone;
      this.queryParams.params.endTime = this.dateRangetwo;
      this.queryParams.params.pageNum = this.queryParams.pageNum;
      this.queryParams.params.pageSize = this.queryParams.pageSize;
      listUser(this.queryParams).then((response) => {
        // console.log(response)
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //数组转树形结构
    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() {
      deptTreeSelect().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) {
      console.log(data)
      this.queryParams.objid = data.id;
      this.queryParams.monitorId = data.monitorId;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.formadd = {
        monitorName: "",
        collectTime: "",
        zxyg: "",
        monitorId: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeone = "";
      this.dateRangetwo = "";
      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;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电实时数据";
    },
    //二次弹窗
    istoselect() {
      //this.reset();
      deptTreeSelect().then((response) => {
        response.map((item, index) => {
          item, (item.oid = item.id), (item.lable = item.name);
        });
        this.deptOptionstwo = this.tranListToTreeData(response);
        //this.deptOptions = response.data;
        this.opentwo = true;
        this.title2 = "设备计量信息选择";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      //const userId = row.objid;
      this.formadd = row;
      this.open = true;
      this.title = "修改电实时数据";
      // getUser(userId).then(response => {
      //   this.form = response.data;
      //   this.postOptions = response.posts;
      //   this.roleOptions = response.roles;
      //   this.$set(this.form, "postIds", response.postIds);
      //   this.$set(this.form, "roleIds", response.roleIds);
      //   this.open = true;
      //   this.title = "修改用户";
      //   this.form.password = "";
      // });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["formadd"].validate((valid) => {
        if (valid) {
          console.log("t", this.formadd.objid);
          if (this.formadd.objid != undefined) {
            updateUser({
              objid: this.formadd.objid,
              monitorId: this.formadd.monitorId,
              monitorName: this.formadd.monitorName,
              collectTime: this.formadd.collectTime,
              zxyg: this.formadd.zxyg,
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser({
              monitorId: this.formadd.monitorId,
              collectTime: this.formadd.collectTime,
              zxyg: this.formadd.zxyg,
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 二次弹窗节点单击事件
    handleNodeClicktwo(data) {
      console.log("data", data);
      this.formaaa.monitorName = data.name;
      this.formaaa.monitorId = data.monitorId;

      // this.handleQuery();
    },
    //二次弹窗 取消按钮
    canceltwo() {
      this.formaaa.monitorName = "";
      this.formaaa.monitorId = "";
      this.opentwo = false;
      //this.reset();
    },
    //二次弹窗确认按钮
    submitFormtwo: function () {
      this.opentwo = false;
      this.formadd.monitorName = this.formaaa.monitorName;
      this.formadd.monitorId = this.formaaa.monitorId;
      //this.canceltwo();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.objid;
      console.log("row", row);
      this.$modal
        .confirm("确定删除该条电实时数据信息吗?")
        .then(function () {
          console.log("userIds", userIds);
          return delUser({ ids: userIds });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let paramsexport = JSON.parse(JSON.stringify(this.queryParams));
      delete paramsexport.pageSize;
      delete paramsexport.pageNum;
      this.download(
        "ems/record/dnbInstant/export",
        {
          ...paramsexport,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss">
.app-container {
  ::v-deep.head-container .sidebar-wrapper .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .is-horizontal {
    display: none;
  }
}
</style>
