<template>
  <div>
    <com-head :options="headList">
      <el-form label-width="84px" inline="true">
        <el-form-item label="角色名称：">
          <el-input
            v-model="search.state.nickName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属架构：">
          <com-company v-model="search.state.deptId" />
        </el-form-item>
        <el-form-item class="searh-btns">
          <el-button type="primary" @click="search.submit">查询</el-button>
          <el-button type="primary" plain @click="search.reset">重置</el-button>
        </el-form-item>
      </el-form>
    </com-head>

    <div class="body-layer" style="padding-top: 8px">
      <div class="body-but">
        <el-button type="primary" @click="newAddclick">新增角色</el-button>
        <!-- <h3 style="visibility: hidden;">用户列表</h3> -->
      </div>

      <el-table
        class="user-table"
        ref="multipleTable"
        :data="dataList.state"
        tooltip-effect="dark"
        style="width: 100%;max-height:480px"
        @row-click="selectRow"
      >
        <el-table-column label="序号" width="55" v-slot:default="{ $index }">
          <div style="text-align: center">
            {{ pag.state.size * (pag.state.currPage - 1) + $index + 1 }}
          </div>
        </el-table-column>
        <el-table-column label="角色名称" prop="userName"></el-table-column>
        <el-table-column label="角色类型" prop="nickName"></el-table-column>
        <el-table-column
          label="所属架构"
          prop="departmentName"
        ></el-table-column>
        <el-table-column label="创建人" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="roleName"></el-table-column>
        <el-table-column label="操作" v-slot:default="{ row }">
          <!-- v-if="auth.update || auth.updatePwd || auth.delete"  v-if="auth.update"-->
          <!-- row.roleKey == roleKey[user.roleKey] -->
          <template v-if="user.roleKey !== 'admin-ordinary'">
            <span class="oper-span" @click="delInfo(row)" v-power="'view'"
              >查看</span
            >
            <span class="oper-span" @click="updateInfo(row)" v-power="'edit'"
              >编辑</span
            >
            <!-- v-if="auth.delete" -->
            <span
              class="oper-span"
              style="color: var(--primaryColor)"
              @click="delInfo(row)"
              v-power="'del'"
              >删除</span
            >
          </template>
        </el-table-column>
      </el-table>
      <com-pagination
        @size-change="pag.sizeChange"
        @current-change="pag.currentChange"
        :current-page="pag.state.currPage"
        :page-size="pag.state.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pag.state.total"
      />
    </div>

    <com-dialog
      title="编辑用户"
      v-model:show="oper.state.show"
      @submit="operItem"
      width="540"
    >
      <el-form ref="form" :model="form" label-width="90px" class="user-from">
        <el-form-item label="用户姓名" class="mandatory">
          <el-input
            v-model.trim="editName"
            placeholder="请输入"
            maxlength="15"
          ></el-input>
        </el-form-item>
      </el-form>
    </com-dialog>

    <com-dialog
      title="新增角色"
      @quit="
        newData = {};
        deptIdList = [];
      "
      v-model:show="newShow"
      @submit="newSubmit"
      width="540"
    >
      <el-form ref="form" :model="form" label-width="90px" class="user-from">
        <el-form-item label="角色名称：" class="mandatory">
          <el-input
            maxlength="15"
            v-model="newData.nickName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所属架构："
          v-if="user.roleKey !== 'admin-ordinary'"
        >
          <el-input
            maxlength="15"
            disabled="true"
            v-model="newData.userRokename"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <div class="title">功能权限</div>
              <el-tree
                ref="tree"
                :data="roledata"
                highlight-current
                show-checkbox
                :current-node-key="nodekey"
                node-key="id"
                @check="handleClick"
                @node-click="handClick"
                :props="{ children: 'children', label: 'label' }"
              />
              <!-- @current-change="handcurrentChange" 
                @check-change="handcheckchange"-->
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <div class="title">数据权限</div>
              <el-radio-group
                v-if="selectShow"
                v-model="radio"
                @change="radioChange"
              >
                <el-radio
                  style="line-height:28px"
                  v-for="item in roleSelct"
                  :key="item.id"
                  :label="item.id"
                  size="medium"
                  >{{ item.value }}</el-radio
                >
              </el-radio-group>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </com-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted } from "vue";
import getTableState from "@/state/tableRef";
import comDialog from "@/components/dialog";
import comHead from "@/components/head";
import comCompany from "@/components/company-select";
import comPagination from "@/components/pagination";
// import roleCompany from "@/components/role-select";
// import comSelect from "@/components/company-select";
import auth from "@/state/viewAuth";
import user from "@/state/user";
import axios from "axios";
// import { encryption } from "@/util";
import { PHONE, EPSW } from "@/constant/REG";
import { ADMIN_USER_ID } from "@/constant";

import {
  getTreeselect,
  getUserList,
  updateUser,
  deleUser,
  changeUserStatus,
  userAdd,
  userEdit,
} from "@/request/config";
import { getApp } from "../../app";

export default {
  name: "user",
  setup() {
    const flag = ref(true);
    const state = getTableState({
      getUrl: getUserList,
      updateUrl: updateUser,
      operAttr: {
        nickName: "",
        userName: "",
        deptId: "",
        password: "",
        confirmPwd: "",
        roleId: "",
        maxlevel: 1,
      },
      searchAttr: { nickName: "", status: "", deptId: "" },
    });
    const headList = ref([{ name: "角色管理", value: 2 }]);
    const roleKey = ref({
      admin: "admin-dept",
      "admin-dept": "admin-ordinary",
    });
    const operRoleId = ref("");
    const updateInfo = (row) => {
      if (!row.status) {
        return getApp().$message.error("请先启用用户", "提示");
      }
      data.editName = row.nickName;
      operRoleId.value = row.roleId;
      state.oper.value.readyUpdate(row);
    };
    const delInfo = async (row) => {
      let isOk = await getApp().$confirm(
        "用户被删除后，无法登陆使用，无法编辑场景（可将该用户关联的相机绑定到其他管理员），确认要删除组织吗？",
        "删除"
      );
      if (isOk) {
        await axios.post(deleUser, { id: row.id });
        getApp().$message({ message: "操作成功", type: "success" });
        state.search.value.submit();
      }
    };
    const getTreedata = async () => {
      let res = await axios.get(getTreeselect, {});
      data.treedata = res.data;
      console.log("data.treedata", data.treedata);
      // getApp().$ref.treeBox.setCurrentKey(user.info.id)
    };
    const newAddclick = () => {
      data.newShow = true;
    };
    const data = reactive({
      newShow: false,
      editName: "", //修改编辑用户名称
      deptIdList: [],
      radio: 1,
      radioData: {},
      nodekey: "",
      selectShow: false,
      roleSelct: [
        { id: 1, value: "全部数据" },
        { id: 2, value: "所属组织及下级组织数据" },
        { id: 3, value: "所属组织内部数据" },
        { id: 4, value: "个人创建数据" },
      ],
      selectData: {},
      roledata: [
        {
          id: 1,
          label: "场景管理",
          value: true,
          children: [
            {
              id: 14,
              label: "查看",
              value: false,
            },
            {
              id: 19,
              label: "删除",
              value: false,
            },
            {
              id: 10,
              label: "编辑",
              value: false,
            },
          ],
        },
        {
          id: 2,
          label: "火调管理",
          value: true,
          children: [
            {
              id: 24,
              label: "查看",
              value: false,
            },
            {
              id: 29,
              label: "删除",
              value: false,
            },
            {
              id: 20,
              label: "编辑",
              value: false,
            },
          ],
        },
      ],
      treedata: [],
      newData: {
        userName: "",
        userId: "",
        userRokename: "全部数据",
        password: "",
        userRole: "",
      },
    });
    onMounted(async () => {
      getTreedata();
    });
    return {
      ...state,
      ...toRefs(data),
      flag,
      getTreedata,
      headList,
      delInfo,
      updateInfo,
      auth,
      user,
      operRoleId,
      ADMIN_USER_ID,
      roleKey,
      newAddclick,
    };
  },
  methods: {
    //@check事件
    handleClick(data, checked) {
      console.log(checked);
      console.log(data);
      let CurrentKey = this.$refs.tree.getCurrentKey();
      if (
        checked.checkedKeys.includes(data.id) &&
        !data.value &&
        CurrentKey == data.id
      ) {
        this.setselectShow(data, data.id);
      } else {
        this.selectShow = null;
      }
    },
    radioChange(val) {
      let id = this.selectShow.id;
      this.radioData[id] = val;
      console.log("radioChange", val);
    },
    handClick(data) {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let selectShow = checkedNodes.find((ele) => data.id == ele.id) || null;
      if (!data.value) {
        this.setselectShow(selectShow, data.id);
      }
      console.log("handClick", this.selectShow);
    },
    setselectShow(selectShow, id) {
      this.selectShow = selectShow;
      this.radio = this.radioData[id] || 1;
    },
    handcurrentChange(a, b) {
      console.log("handcurrentChange", a, b);
      console.log("ref", this.selectShow);
    },
    changeDeptId(val) {
      this.newData.deptId = val && val[val.length - 1];
    },
    async newSubmit() {
      console.log("newSubmit", this.user, this.newData);
      if (!this.newData.nickName) {
        return this.$message.error("请输入用户姓名", "提示");
      }
      if (!this.newData.roleId) {
        return this.$message.error("请选择用户角色", "提示");
      }
      console.log(PHONE.REG.test(this.newData.userName), this.newData.userName);
      if (!this.newData.userName) {
        return this.$message.error("请选择用户账户", "提示");
      } else if (!PHONE.REG.test(this.newData.userName)) {
        return this.$message.error(PHONE.tip, "提示");
      }
      if (!this.newData.psw) {
        return this.$message.error("请输入登录密码", "提示");
      } else if (!EPSW.REG.test(this.newData.psw)) {
        return this.$message.error(EPSW.tip, "提示");
      }
      let apiinfo = await axios.post(userAdd, {
        nickName: this.newData.nickName,
        password: this.newData.psw,
        userName: this.newData.userName,
        roleId: this.newData.roleId,
        deptId: this.newData.deptId,
        // ...this.newData
      });
      this.$message({ message: apiinfo.msg || "成功", type: "success" });
      // await this.$confirm('每个组织只能创建一个总管理员~', '新增用户')
      this.newData = {};
      this.deptIdList = [];
      this.newShow = false;
      this.dataList.refer();
    },
    async operItem() {
      if (!this.editName) {
        return this.$message.error("请输入用户名称", "提示");
      }
      console.log("state.oper", this.oper);
      await axios.post(userEdit, {
        id: this.oper.state.id,
        nickName: this.editName,
      });
      this.$message({ message: "编辑成功", type: "success" });
      this.oper.reset();
      this.editName = "";
      this.dataList.refer();
    },
    async changeUserStatus(row, d) {
      let msg = row.status
        ? `用户被禁用后，无法登录使用，无法编辑场景（可将该用户关联的相机绑定到其它管理员）。确定要禁用吗？`
        : `用户被启用后，可正常登录使用。确定要启用吗？`;
      try {
        if (d || (await this.$confirm(msg, "提示"))) {
          await axios.post(changeUserStatus, {
            status: Number(!row.status),
            userId: row.id,
          });
          this.dataList.refer();
        }
        return true;
      } catch {
        return false;
      }
    },
  },
  components: {
    "com-dialog": comDialog,
    "com-head": comHead,
    "com-company": comCompany,
    // "com-role": roleCompany,
    "com-pagination": comPagination,
    // "com-select": comSelect
  },
};
</script>

<style lang="scss" scoped>
.grid-content {
  border: 1px solid #e8e8e8;
  border-bottom: none;
  .title {
    background: #fafafa;
    padding: 12px 10px;
    border-bottom: 1px solid #ebeef5;
    line-height: 20px;
  }
  .el-radio-group {
    width: 100%;
    .el-radio {
      padding: 12px 10px;
      border-bottom: 1px solid #ebeef5;
      display: block;
      margin-right: 0;
      &:last-child {
        // border-bottom: none;
      }
    }
  }
}
.body-layer {
  .body-but {
    text-align: right;
    margin-bottom: 15px;
  }
}
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}

.user-from {
  // width: 380px;
  margin: 0 auto;
}

.tip {
  position: fixed;
  left: 50%;
  top: 50%;
  z-index: 999;

  &::before {
    content: "密码重置为Fcb20210225，可登录修改";
    position: absolute;
    width: 205px;
    left: 50%;
    transform: translateX(-50%);
    bottom: 100%;
    border-radius: 4px;
    padding: 10px;
    z-index: 2000;
    font-size: 12px;
    line-height: 1.2;
    min-width: 10px;
    word-wrap: break-word;
    background: #303133;
    color: #fff;
    margin-bottom: 6px;
  }

  &::after {
    content: "";
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    border-color: transparent;
    border-style: solid;
    border-width: 6px;
    border-top-color: #303133;
    border-bottom-width: 0;
  }
}

.maker {
  font-weight: 400;
  color: #969799;
  line-height: 20px;
}
</style>

<style lang="less">
.user-table.el-table .cell {
  overflow: inherit;
}
.el-tree {
  max-height: 400px;
  overflow-y: auto;
  border-bottom: 1px solid #ebeef5;
  .el-tree-node__content {
    border-bottom: 1px solid #ebeef5;
    padding: 12px 10px;
    &:last-child {
      // border-bottom: none;
    }
  }
}
</style>
