<script lang="ts">
export default {
  name: "role",
};
</script>

<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import { listRolePages, isvaildTo, addDept, renewDept, deleDept, assignmentPer, setMenuById, setOrgscope, postOrgscope } from "@/api/role";
//定义表格数据
const tableData: any = ref([]);
const multipleSelection = ref([]);
// 权限
const tree = ref()

// 表格加载
const loading = ref(false)
function gettableData() {
  let params = {
    rolename: input.value,
  };
  loading.value = true;
  listRolePages(params).then((result) => {
    tableData.value = result;
    loading.value = false;
  }).catch((err) => {
    loading.value = false;
  });
}
//表格多选事件
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
function switchChange(row: any) {
  const elMessage = ref()
  if (row.isvaild == '0') {
    elMessage.value = "确定设置该角色为无效吗？"
  } else if (row.isvaild == '1') {
    elMessage.value = "确定设置该角色为有效吗？"
  }
  ElMessageBox.confirm(elMessage.value, "提示信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        isvaild: row.isvaild,
        id: row.id,
      };
      isvaildTo(params).then(() => {
        gettableData();
        ElMessage({
          type: "success",
          message: "改变成功",
        });
      });
    })
    .catch(() => {
      gettableData();
    });
}
const infoForm = ref();
//搜索内容及点击搜索按钮
const input = ref("");
//新建角色
const title = ref("");
const info: any = ref({
  rolename: "",
  level: "系统管理员",
  description: "",
});
const faultList: any = [
  {
    value: "1",
    label: "超级管理员",
  },
  {
    value: "2",
    label: "系统管理员",
  },
  {
    value: "3",
    label: "一般用户",
  },
];
const dialogVisible = ref(false);
function addClick() {
  title.value = "新增角色";
  info.value = {
    rolename: "",
    level: "系统管理员",
    description: "",
  };
  dialogVisible.value = true;
}
//新建角色-确认按钮/修改按钮
function confirmClick(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {

      if (!info.value.id) {
        const params = {
          rolename: info.value.rolename,
          level: info.value.level,
          description: info.value.description,
        };
        addDept(params).then((res) => {
          gettableData();
          dialogVisible.value = false;
        });
      } else if (info.value.id) {
        const params = {
          rolename: info.value.rolename,
          level: info.value.level,
          description: info.value.description,
          id: info.value.id,
        };
        renewDept(params).then((res) => {
          gettableData();
          dialogVisible.value = false;
        });
      } else {
        return false;
      }
    }
  });
}

//新建角色-取消按钮
function handleClose() {
  dialogVisible.value = false;
  businessVisible.value = false;
  organizeVisible.value = false;
  accessVisible.value = false
  businessVisible.value = false
  if (infoForm.value != null) infoForm.value.resetFields();
}
//新建角色-rules
const rules = ref({
  rolename: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  level: [{ required: true, message: "请选择角色级别", trigger: "change" }],
});
//修改角色
function editrole(row: any) {
  title.value = "修改角色";
  info.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
}
//业务范围修改
const businessVisible = ref(false);
function businessclick(row: any) {
  // businessVisible.value = true;
  ElMessageBox.confirm("此模块允许用户进行定制。", "提示信息", {
    confirmButtonText: "确定",
    type: "warning",
  })
    .then(() => {
      businessVisible.value = false;
    });
}

// 业务范围弹窗-确认按钮
// function businesssubmit(row: any) {
//   businessVisible.value = false;
// }
//组织范围修改
const organizeVisible = ref(false);
const deptdata = ref()
const roleIda = ref('')
function organizeclick(row: any) {
  organizeVisible.value = true;
  roleIda.value = row.id
  const params = {
    roleId: row.id
  }
  setOrgscope(params).then((res) => {
    deptdata.value = res
  })
}
function accessCheckAllChange(indexone: any) {
  const Arrayall: any = ref([])
  for (var j = 0; j < deptdata.value[indexone].children.length; j++) {
    Arrayall.value.push(deptdata.value[indexone].children[j].orgname)
  }
  deptdata.value[indexone].array = deptdata.value[indexone].checkinfo ? Arrayall : []
  deptdata.value[indexone].bool = false
}
function accessCheckedCitiesChanges(indexone: any) {
  const checkedCount = deptdata.value[indexone].array.length
  const cities = deptdata.value[indexone].children.length
  deptdata.value[indexone].checkinfo = checkedCount === cities
  deptdata.value[indexone].bool = checkedCount > 0 && checkedCount < cities

}
function organizesubmit() {
  const allid: any = ref([])
  deptdata.value.forEach((item: any) => {
    item.children.forEach((element: any) => {
      item.array.forEach((res: any) => {
        if (res == element.orgname) {
          allid.value.push(element.id)
        }
      })
    })
  })
  const params = {
    id: roleIda.value,
    orgscope: allid.value.toString()
  }
  postOrgscope(params).then((res) => {
    ElMessage({
      type: "success",
      message: "组织范围修改成功",
    });
    organizeVisible.value = false
  })
}
//删除角色
function delrole(row: any) {
  ElMessageBox.confirm("确定删除此角色吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        id: row.id,
      };
      deleDept(params).then(() => {
        gettableData();
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      });
    })
}
//权限分配
const accessVisible: any = ref()
const accessdata: any = ref([])
//默认展开节点的key数组
const DefaultDeployment: any = ref([])
//传参id
const Passparameter: any = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
}
const rowid = ref()
function menuChange(data: any, ids: any) {
  data.forEach((item: any) => {
    if (item.checkinfo == true) {
      ids.push(item.id)
      DefaultDeployment.value.push(item.id)
    }
    if (item.children) {
      menuChange(item.children, ids)
    }
  })
}
function assignment(row: any) {
  rowid.value = row.id
  accessVisible.value = true
  const params = {
    roleId: rowid.value
  }
  assignmentPer(params).then((res: any) => {
    accessdata.value = res
    let ids: any = []
    menuChange(res, ids)
    nextTick(() => {
      tree.value.setCheckedKeys(ids)
    })

  })
}


// 树形选择器
function currentChecked(nodeObj: any, SelectedObj: any) {
  Passparameter.value = SelectedObj.checkedKeys.concat(SelectedObj.halfCheckedKeys)
}
// 权限范围-权限范围-确定
function accesssubmit() {
  const parans = {
    id: rowid.value,
    menuIds: Passparameter.value.toString()
  }
  setMenuById(parans).then((res) => {
    accessVisible.value = false
    gettableData()
    ElMessage({
      type: "success",
      message: "修改成功",
    });
  })
}
// 多选删除？
function delClick() {
  ElMessageBox.confirm("确定删除已选择角色吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.id)
    })
    let params = {
      id: id.join(','),
    };
    deleDept(params).then(() => {
      gettableData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
function dateFormat(row: any) {
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}

onMounted(() => {
  gettableData();
});
</script>

<template>
  <div class="invalidcatalogue-box">
    <div class="conductproject-bg-box">
      <div
        style="display: flex;display: -webkit-flex; justify-content: space-between; -webkit-justify-content: space-between;margin-bottom: 10px">
        <div style="display: flex;display: -webkit-flex;">
          <el-input v-model="input" placeholder="请输入角色名称" @keyup.enter="gettableData" style="width: 200px" clearable />
          <el-button type="primary" style="margin-left: 10px" @click="gettableData">搜索</el-button>
        </div>
        <div>
          <el-button v-hasPerm="['add:role']" type="primary" @click="addClick">
            <img src="@/assets/MenuIcon/jscz_xz.png" alt="" style="margin-right: 3px">
            新增</el-button>
          <el-button v-hasPerm="['del:role']" :type="multipleSelection.length > 0 ? 'primary' : ''"
            :disabled="multipleSelection.length <= 0" @click="delClick"><el-icon>
              <Delete />
            </el-icon> 删除</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%; height: calc(100vh - 220px)" border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: 'rgb(250 250 250)', color: '#383838', height: '50px' }">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="rolecode" label="角色编号" width="100"></el-table-column>
        <el-table-column prop="rolename" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="level" label="角色级别" width="116">
          <template #default="scope">
            <span v-show="scope.row.level == '1'">超级管理员</span>
            <span v-show="scope.row.level == '2'">系统管理员</span>
            <span v-show="scope.row.level == '3'">一般用户</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="角色描述" min-width="100"></el-table-column>
        <el-table-column prop="isvaild" label="是否有效" align="center" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.isvaild" @change="switchChange(scope.row)" style="margin-right: 4px"
              active-value="1" inactive-value="0"></el-switch>
            <span v-if="scope.row.isvaild == 1" style="color: #0099ff">有效</span>
            <span v-else style="color: #d7d7d7">无效</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastmodifier" label="最近修改者" width="120"></el-table-column>
        <el-table-column prop="lastmodifydate" label="最近修改日期" width="200">
          <template #default="scope">
            {{ dateFormat(scope.row.lastmodifydate) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <span
              style="display: flex;display: -webkit-flex; justify-content: space-around;-webkit-justify-content: space-around; ">
              <img v-hasPerm="['update:role']" src="@/assets/MenuIcon/lbcz_xg.png" alt="" title="修改"
                @click="editrole(scope.row)" style="cursor: pointer; ">
              <!-- <img src="@/assets/MenuIcon/lbcz_zyw.png" alt="" title="业务范围" @click="businessclick(scope.row)"
                style="cursor: pointer;">
              <img src="@/assets/MenuIcon/u343.png" alt="" title="组织范围" @click="organizeclick(scope.row)"
                style="cursor: pointer; "> -->
              <img src="@/assets/MenuIcon/lbcz_qx.png" alt="" title="权限分配" @click="assignment(scope.row)"
                style="cursor: pointer; ">
              <img v-hasPerm="['del:role']" src="@/assets/MenuIcon/lbcz_sc.png" alt="" title="删除"
                @click="delrole(scope.row)" style="cursor: pointer; ">
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="dialogVisible" :close-on-click-modal="false" draggable :before-close="handleClose" :title="title"
      append-to-body width="620px" height="600px">
      <el-form ref="infoForm" :model="info" :rules="rules" label-width="110px">
        <el-form-item label="角色名称：" prop="rolename">
          <el-input v-model="info.rolename" style="width: 100%" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色级别：" prop="level">
          <el-select v-model="info.level" placeholder=" " style="width: 100%">
            <el-option v-for="item in faultList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述：">
          <el-input v-model="info.description" style="width: 100%" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <span class="dialog-footer"
          style="display: flex;display: -webkit-flex; justify-content: flex-end;-webkit-justify-content: flex-end;">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="confirmClick(infoForm)">确 定</el-button>
        </span>
      </el-form>
    </el-dialog>
    <el-dialog title="组织范围" v-model="organizeVisible" width="60%" draggable :before-close="handleClose">
      <div v-for="(item, indexone) in deptdata" :label="item.name" :key="item.id" style="width:90%;margin:auto">
        <div style=" font-size: 15px;  font-weight: 700; display: inline-block; margin: 8px 0px;">{{ item.orgname }}</div>
        <div style="display: flex; display: -webkit-flex;align-items: center;-webkit-align-items: center;">
          <div>部门选择</div>
          <div style="display: flex; display: -webkit-flex;margin-left: 60px;">
            <el-checkbox v-model="item.checkinfo" :indeterminate="item.bool"
              @change="accessCheckAllChange(indexone)">全选</el-checkbox>
            <el-checkbox-group v-model="item.array" @change="accessCheckedCitiesChanges(indexone)"
              style="margin-left:20px">
              <el-checkbox v-for="k in item.children" :key="k.id" :label="k.orgname">{{ k.orgname }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="line"></div>
      </div>
      <span class="dialog-footer"
        style="display: flex; display: -webkit-flex;; justify-content: flex-end;-webkit-justify-content: flex-end;">
        <el-button @click="organizeVisible = false">取 消</el-button>
        <el-button type="primary" @click="organizesubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="权限分配" v-model="accessVisible" width="500px" :before-close="handleClose" destroy-on-close draggable style="max-height: 640px;" >
      <el-tree ref="tree" style="max-height: 400px;overflow:auto" :data="accessdata" show-checkbox node-key="id" accordion
        :default-expanded-keys="DefaultDeployment" :props="defaultProps" @check="currentChecked" />
      <span class="dialog-footer"
        style="display: flex;display: -webkit-flex; justify-content: flex-end;-webkit-justify-content: flex-end;">
        <el-button @click="accessVisible = false">取 消</el-button>
        <el-button type="primary" @click="accesssubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.invalidcatalogue-box {
  padding-right: 10px;
}

:deep(.el-tree-node__content) {
  font-size: 15px;
  font-weight: 500;
  width: 100%;
  height: 40px;
}

.dialog-footer {
  display: block;
  margin-top: 20px;
}

.conductproject-bg-box {
  padding: 20px;
  width: 100%;
  height: calc(100vh - 130px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 3px;
  box-sizing: border-box;
}

.line {
  height: 1px;
  background: rgba(240, 241, 242, 1);
  margin-top: 12px;
}

.menuspan {
  display: inline-block;
  width: 120px;
  font-size: 14px;
  font-family: "微软雅黑";
  font-weight: 400;
  font-style: normal;
  color: #787878;
}
</style>
