<template>
  <div>
    <com-head :options="headList">
      <el-form label-width="84px" inline="true">
        <el-form-item label="角色名称：">
          <el-input
            v-model="search.state.searchKey"
            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" :disabled="getRoke('add')" @click="()=>{newAddclick(null,'新增')}">新增角色</el-button>
      </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="roleName"></el-table-column>
        <el-table-column label="角色类型" prop="type">
            <template #default="scope">
                  {{ scope.row.type==0?'预设':'自定义' }}
            </template>
        </el-table-column>
        <el-table-column label="所属架构" prop="deptName" ></el-table-column>
        <el-table-column label="创建人" prop="nickName"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></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="()=>{newAddclick(row.id,'查看')}" v-power="'view'"
              >查看</span
            >
            <span class="oper-span" :class="{disable:editDisable(row)}" @click="()=>{newAddclick(row.id,'编辑')}" v-power="'edit'"
              >编辑</span
            >
            <!-- v-if="auth.delete" -->
            <span
              class="oper-span"
              style="color: var(--primaryColor)"
              @click="delInfo(row)"
              :class="{disable:row.type == 0}"
              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 || 0"
      />
    </div>

    <com-dialog
      :title="`${operateType}角色`"
      @quit="
        newData = {};
        deptIdList = [];
      "
      v-model:show="newShow"
      :showClose="operateType != '查看'"
      :enterText="operateType == '查看'?'确定':false"
      :cornerClose="operateType == '查看'"
      @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.roleName"
            :disabled="operateType == '查看'"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所属架构："
          v-if="user.roleKey !== 'admin-ordinary'"
        >
          <el-input
            maxlength="15"
            :disabled="true"
            v-model="user.info.deptName"
            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"
                :default-checked-keys="Object.keys(radioData)"
                @check="handleClick"
                @node-click="handClick"
                :props="{ children: 'children', label: 'name',disabled:'disabled' }"
              />
              <!-- @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"
                :disabled="operateType == '查看'"
              >
                <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 auth from "@/state/viewAuth";
import user from "@/state/user";
import { getRoke } from '@/util'
import axios from "axios";
import { ADMIN_USER_ID } from "@/constant";
import {
  getTreeselect,
  getRoleTree,
  detailRole,
  getPageList,
  updateRole,
  removeRole,
  changeUserStatus,
  userEdit,
} from "@/request/config";
import { getApp } from "../../app";

export default {
  name: "user",
  setup() {
    const flag = ref(true);
    const state = getTableState({
      getUrl: getPageList,
      updateUrl: updateRole,
      operAttr: {
        roleName: "",
        userName: "",
        deptId: "",
        password: "",
        confirmPwd: "",
        roleId: "",
        maxlevel: 1,
      },
      searchAttr: { roleName: "", status: "", deptId: "",searchKey:'' },
    });
    const headList = ref([{ name: "角色管理", value: 2 }]);
    const roleKey = ref({
      admin: "admin-dept",
      "admin-dept": "admin-ordinary",
    });
    const operRoleId = ref("");
    const delInfo = async (row) => {
      if(row.type == 0){
        return  getApp().$message({ message: "预设角色不能删除", type: "warning" });
      }
      let isOk = await getApp().$confirm(
        "删除角色后，相关用户需重新配置角色，确认要删除组织吗？",
        "删除"
      );
      if (isOk) {
        await axios.post(removeRole+row.id , { 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;
    };
    const newAddclick = async (id,type) => {
      let reqApi = getRoleTree;//id?getTreeByRole+id:getRoleTree
      let treeRes = await axios.get(reqApi, {roleId:id});
      data.selectShow = null;
      data.selectId = id
      if(type != '新增'){
          let res = await axios.get(detailRole+id, {roleId:id});
          let { roleName,perm,deptName} = res.data
          let radioData = {},checkedList=[],halfCheckedKeys=[]
          perm.forEach(ele => {
            if(ele.type == 'button'){
              checkedList.push(ele.permissionId)
              radioData[ele.permissionId] = ele.dataScope || '1'
            }else{
              halfCheckedKeys.push(ele.permissionId)
            }
          })
          console.log('halfCheckedKeys',halfCheckedKeys,perm);
          data.radioData = radioData
          data.checkedList = checkedList
          data.halfCheckedKeys = halfCheckedKeys
          data.newData = {
            ...data.newData,
            roleName,
            deptName,
          }
      }else{
        data.newData.deptName = user.deptName
        data.radioData = {}
      }
      data.roledata = type == '查看'?(treeRes.data.map(ele => {
        ele.disabled = true
        ele.children && ele.children.map(item => item.disabled = true)
        return ele
      })):treeRes.data || [];
      data.operateType = type || '新增'
      data.newShow = true;
      
    };
    const data = reactive({
      newShow: false,
      editName: "", //修改编辑用户名称
      selectId:'',
      operateType:'新增',
      deptIdList: [],
      halfCheckedKeys:[],
      radio: 1,
      roleLevel:sessionStorage.getItem('roleLevel'),
      radioData: {},
      nodekey: "",
      selectShow: false,
      roleSelct: [
        { id: 1, value: "全部数据" },
        { id: 3, value: "所属组织及下级组织数据" },
        { id: 4, value: "所属组织内部数据" },
        { id: 5, value: "个人创建数据" },
      ],
      checkedList:[],//tree 选中树
      selectData: {},
      roledata: [],
      treedata: [],
      newData: {
        userName: "",
        userId: "",
        password: "",
        userRole: "",
      },
    });
    onMounted(async () => {
      getTreedata();
    });
    return {
      ...state,
      ...toRefs(data),
      flag,
      getTreedata,
      headList,
      delInfo,
      auth,
      user,
      operRoleId,
      ADMIN_USER_ID,
      roleKey,
      newAddclick,
      getRoke,
    };
  },
  methods: {
    editDisable(row){
      let disable = false
      if(row.type == 0 ){
      // if(row.type == 0 && this.roleLevel != 1){
        disable = true
      }
      return disable
    },
    //@check事件
    handleClick(data, checked) {
      console.log(checked);
      console.log(data);
      this.checkedList = checked.checkedKeys
      this.halfCheckedKeys = checked.halfCheckedKeys
      let CurrentKey = this.$refs.tree.getCurrentKey();
      if (
        checked.checkedKeys.includes(data.id) &&
        data.type == 'button' &&
        CurrentKey == data.id
      ) { //找到高亮且勾选的item
        this.setselectShow(data, data.id);
      } else {
        this.selectShow = null;
      }
    },
    radioChange(val) {
      let id = this.selectShow.id;
      this.radioData[id] = val;
      console.log("radioChange", this.radioData);
    },
    handClick(data) {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let selectShow = checkedNodes.find((ele) => data.id == ele.id) || null;
      if (data.type == 'button') {
        this.setselectShow(selectShow, data.id);
      }
      console.log("handClick",data);
    },
    setselectShow(selectShow, id) {
      this.selectShow = selectShow;
      this.radio = parseInt(this.radioData[id] || 1)
      if(!this.radioData[id]&& this.operateType !== '查看')this.radioData[id] = 1
    },
    handcurrentChange(a, b) {
      console.log("handcurrentChange", a, b);
      console.log("ref", this.selectShow);
    },
    assembleData(val) {
      let data = val.map(ele => {
        ele.children && ele.children(ele => ele.disabled = true)
        return ele
      })
      console.log('assembleData',data);
      return data
    },
    async newSubmit() {
      if(this.operateType == '查看'){
         return  this.newShow = false;
      }
      if (!this.newData.roleName) {
        return this.$message.error("请输入用户姓名", "提示");
      }
      let perm = {}
      this.checkedList.map(ele =>{ 
        if(this.radioData[ele]){
          perm[ele] = this.radioData[ele]
        }else{
          perm[ele] = 1
        }
      })
      this.halfCheckedKeys.forEach(element => {
          perm[element] = 1
      });
      console.log("newSubmit", this.halfCheckedKeys,perm);
      let id = this.selectId
      let apiinfo = await axios.post(updateRole, { //新增修改角色
        "id": id || '',
        "perm": {
          ...perm,
        },
        "roleName": this.newData.roleName
      });
      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,
        roleName: 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>
