<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="KEY" prop="groupKey">
        <el-input
          v-model="queryParams.groupKey"
          placeholder="请输入用户key"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分组名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入分组名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否可用" prop="enabled">
        <el-select
          v-model="queryParams.enabled"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option label="可用" :value="true"> </el-option>
          <el-option label="禁用" :value="true"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="keyList">
      <el-table-column
        prop="groupKey"
        label="用户KEY"
        width="200"
      ></el-table-column>
      <el-table-column prop="groupName" label="分组名称"></el-table-column>
      <el-table-column label="是否可用" align="center" prop="enabled">
        <template slot-scope="scope">
          <span>{{ scope.row.enabled ? "可用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <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-view"
            @click="handleLook(scope.row)"
            >查看日志</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSend(scope.row)"
            >发送日志</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <div style="width: 10px; display: inline-block"></div>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleDelete(scope.row)"
          >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或修改 -->
    <el-dialog
      :title="title"
      :visible.sync="openScope"
      width="550px"
      append-to-body
    >
      <el-form
        :model="form"
        label-width="80px"
        label-position="top"
        :rules="rules"
        ref="form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分组名称" prop="groupName">
              <el-input
                v-model="form.groupName"
                placeholder="请输入分组名称"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分组KEY" prop="groupKey">
              <el-input
                v-model="form.groupKey"
                placeholder="请输入分组KEY"
                clearable
                size="small"
                :disabled="title === '修改消息分组'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <!-- <el-form-item label="归属部门" prop="deptList">
              <treeselect
                v-model="form.deptList"
                :options="deptOptions"
                :disable-branch-nodes="true"
                :show-count="true"
                :normalizer="normalizer"
                multiple
                placeholder="请选择归属部门"
              />
            </el-form-item> -->
            <el-form-item label="归属部门" prop="deptList">
              <el-tree
                :data="deptOptions"
                show-checkbox
                ref="deptRef"
                node-key="deptId"
                check-strictly
                default-expand-all
                empty-text="加载中，请稍后"
                :props="defaultProps"
                @check="handleCheckChange"
              ></el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可用" prop="enabled">
              <el-switch v-model="form.enabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="用户" prop="userList">
          <el-transfer
            class="transfer"
            filterable
            filter-placeholder="请输入组员"
            v-model="form.userList"
            :titles="['所有人', '组员']"
            :data="userList"
          >
          </el-transfer>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitScope">确 定</el-button>
        <el-button @click="cancelScope">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 日志 -->
    <el-dialog
      title="日志"
      :visible.sync="logOpen"
      width="750px"
      append-to-body
    >
      <el-table :data="logData" :loading="logLoading" style="width: 100%" max-height="450">
				<el-table-column prop="msgContext" label="发送消息"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column prop="sendTime" label="发送时间"/>
      </el-table>
			<pagination
				v-show="logTotal > 0"
				:total="logTotal"
				:page.sync="formLog.pageNum"
				:limit.sync="formLog.pageSize"
				@pagination="getLogList"
			/>
			<div slot="footer" class="dialog-footer">
        <el-button @click="logOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserKeyList,
  addUserKey,
  editUserKey,
  delUserKey,
  sendMassage,
  lookLog,
} from "@/api/system/userKey";
import { listDept } from "@/api/system/dept";
import { allUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "UserKey",
  components: { Treeselect },
  data() {
    return {
      normalizer(node) {
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children,
        };
      },
      // 查询参数
      queryParams: {
        pageSize: 20,
        pageNum: 1,
      },
      // 显示搜索条件
      showSearch: true,
      // loading
      loading: false,
      // 新增修改dailogtitle
      title: "",
      // 新增参数
      form: { enabled: true },
      // 控制新增弹窗
      openScope: false,
      // 表单校验
      rules: {
        groupName: [
          { required: true, message: "分组名称不能为空", trigger: "blur" },
        ],
        groupKey: [
          { required: true, message: "用户key不能为空", trigger: "blur" },
        ],
      },
      // 表格数据
      keyList: [],
      // 列表个数
      total: 0,
      // 绑定表格数据
      userList: [],
      // 保存选中的人员
      selectionUsers: [],
      // 保存点击绑定人员的keyID
      keyId: null,
      //
      selectUserList: [],
      // 部门树选项
      deptOptions: undefined,
      // 获取日志参数
      formLog: {
        pageSize: 20,
        pageNum: 1,
        msgGroupId: null,
      },
      // 查看日志弹窗控制
      logOpen: false,
      // 日志数据
      logData: [],
      logLoading: false,
			logTotal: 0,
      defaultProps: {
        children: "children",
        label: "deptName",
        value: 'deptId'
      }
    };
  },
  created() {
    this.getTreeselect();
    this.getList();
    this.getUserList();
  },
  methods: {
    cancelMenu() {
      if (this.$refs.deptRef != undefined) {
        this.$refs.deptRef.setCheckedKeys([]);
      }
    },
    /** 归属岗位 */
    handleCheckChange(checkedNode, checkedKeys) {
      console.log(checkedNode, checkedKeys);
      this.$set(this.form, 'deptList', checkedKeys.checkedKeys)
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = [], halfCheckedKeys = []
      if (this.$refs.deptRef != undefined) {
        checkedKeys = this.$refs.deptRef.getHalfCheckedKeys();
        halfCheckedKeys = this.$refs.deptRef.getCheckedKeys();
      }
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return [...checkedKeys];
    },
    /** 查看日志 */
    handleLook(row) {
      this.formLog = {
        ...this.formLog,
        msgGroupId: row.id,
      };
      this.logOpen = true;
      this.getLogList();
    },
    /** 获取日志 */
    getLogList() {
      this.logLoading = true;
      lookLog(this.formLog).then((res) => {
        this.logData = res.data.records;
        this.logLoading = false;
				this.logTotal = res.data.total
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listDept().then((response) => {
        this.deptOptions = this.changeTree(response.data);
      });
    },
    changeTree(tree) {
      if (Array.isArray(tree) && tree.length > 0) {
        let tre = tree.map((item) => {
          let { children, ...ite } = item;
          if (children.length > 0) {
            let ee = this.changeTree(children);
            return {
              children: ee,
              ...ite,
            };
          } else {
            return ite;
          }
        });
        return tre;
      } else {
        return tree;
      }
    },
    /** 搜索 */
    handleQuery() {
      let { startTime, endTime } = this.queryParams;
      if (startTime) {
        startTime = this.parserTime(startTime);
      }
      if (endTime) {
        endTime = this.parserTime(endTime);
      }
      this.queryParams = { ...this.queryParams, startTime, endTime };
      this.getList();
    },
    /** 时间转换 */
    parserTime(time) {
      const d = new Date(time);
      const resDate =
        d.getFullYear() +
        "-" +
        this.p(d.getMonth() + 1) +
        "-" +
        this.p(d.getDate());
      return resDate;
    },
    p(s) {
      return s < 10 ? "0" + s : s;
    },
    /** 重置 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增 */
    handleAdd() {
      this.form = { enabled: true }
      this.getTreeselect();
      this.openScope = true;
      this.title = "新增消息分组";
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getUserKeyList(this.queryParams).then((response) => {
        this.keyList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 新增弹窗确定 */
    submitScope() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            console.log(this.form);
            editUserKey(this.form).then((response) => {
              if (response.data) {
                this.msgSuccess("修改成功");
                this.openScope = false;
                this.form = {};
                this.getList();
                this.cancelMenu()
              }
            });
          } else {
            addUserKey(this.form).then((response) => {
              if (response.data) {
                this.msgSuccess("新增成功");
                this.openScope = false;
                this.form = {};
                this.getList();
                this.cancelMenu()
              }
            });
          }
        }
      });
    },
    /** 新增弹窗取消 */
    cancelScope() {
      this.form = { enabled: true };
      this.openScope = false;
      this.cancelMenu()
    },
    /** 修改数据 */
    handleUpdate(row) {
      console.log(row.deptList);
      this.getTreeselect();
      this.$nextTick(()=>{
        setTimeout(() => {
          if (row.deptList) {
            row.deptList.forEach((element) => {
              let node = this.$refs.deptRef.getNode(element);
              console.log(node.isLeaf);
              // if (node.isLeaf) {
                this.$refs.deptRef.setChecked(node, true);
              // }
            });
          }
        }, 100)
      })
    
      this.form = { ...row };
      this.openScope = true;
      this.title = "修改消息分组";
    },
    /** 发送日志 */
    handleSend(row) {
      this.$prompt('请输入"' + row.groupName + '"要发的消息', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          sendMassage(row.id, value).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("发送成功，发送的消息是：" + value);
            }
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    /** 删除数据 */
    handleDelete(row) {
      console.log(row.id);
      delUserKey(row.id).then((res) => {
        if (res.data) {
          this.msgSuccess("删除成功");
          this.getList();
        }
      });
    },
    /** 获取人员 */
    getUserList() {
      allUser().then((res) => {
        this.selectUserList = res.data.map((item) => ({
          id: item.userId,
          name: item.nickname,
          remark: item.remark,
        }));
        let resData = res.data.filter((item) => item.userId !== 0);
        this.userList = resData.map((item) => ({
          key: item.userId,
          label: item.nickname,
        }));
      });
    },
  },
};
</script>

<style lang="scss">
.transfer {
  & > .el-transfer__buttons {
    display: inline-flex !important;
    flex-direction: column !important;
    padding: 0 10px !important;
    .el-button + .el-button {
      margin-left: 0;
    }
  }
}
</style>