<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, getCamera, addCamera, queryCamera } from "@/api/role";
import { getTreefirst, } from "@/api/device";
import Eldialog from '@/components/seccmsdialog/eldialog.vue';
//定义表格数据
const tableData: any = ref([]);
const multipleSelection: any = ref([]);
// 权限
const tree = ref()
const screentree = 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;
}
//表格多选样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  if (rowIndex % 2 === 0) {
    return 'warning-row'
  } else if (rowIndex % 2 === 1) {
    return 'success-row'
  }
  return ''
}

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((res: any) => {
        if (res.code == '0') {
          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: "业务操作",
  }, {
    value: "4",
    label: "安全审计",
  }
];
const dialogVisible = ref(false);
function addClick() {
  title.value = "新增角色";
  info.value = {
    rolename: "",
    level: "2",
    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" }, { validator: stringlength, trigger: 'blur' }],
  level: [{ required: true, message: "请选择角色级别", trigger: "blur" }],
});
//区域名称长度
function stringlength(rule: any, value: any, callback: any) {
  if (value.length > 20) {
    return callback(new Error('字符最大长度不超过20'))
  }
  callback()
}
//修改角色
function editrole(row: any) {
  title.value = "修改角色";
  info.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;

}
//业务范围
const businessVisible = ref(false);
const roleId = ref()
function businessclick(row: any) {
  roleId.value = row.id
  businessVisible.value = true;
  leftloading.value = true
  QueryCamera()
}

//获取企业树形信息
const valueMenu = ref('1')
const menuValue = ref([
  {
    value: '1',
    label: '管理后台',
  },
  {
    value: '2',
    label: '监控大屏',
  },
])
const value = ref()
const optionSelect = ref()
const leftloading = ref(false)
function getSelect() {
  getTreefirst().then((res: any) => {
    optionSelect.value = res.data
    if (stationId.value == '' || stationId.value == undefined) {
      value.value = res.data[0].stationId
    } else {
      value.value = stationId.value
    }
    GetCamera()
  })
}
const AllCamera: any = ref([])
const leftValue: any = ref([])
const stationId = ref('')
//获取变电站下所有摄像头
function GetCamera() {
  const params = {
    stationId: value.value
  }
  getCamera(params).then((res: any) => {
    AllCamera.value = res.data
    leftloading.value = false

  })
}
//当前右侧选中
const CreamId: any = ref('')
function handleChange(row: any) {
  CreamId.value = row.toString()
}
//摄像机提交
function CreamSubmit() {
  const params = {
    id: roleId.value,
    deviceIds: CreamId.value == '' ? '' : leftValue.value.toString()
  }
  addCamera(params).then((res: any) => {
    if (res.code == 0) {
      ElMessage({
        type: "success",
        message: "增加成功",
      });
      stationId.value = AllCamera.value[0].stationId
      businessVisible.value = false;
    }
  })
}
//已分配摄像头
function QueryCamera() {
  const params = {
    id: roleId.value,
  }
  queryCamera(params).then((res: any) => {
    leftValue.value = res.data.id
    stationId.value = res.data.stationId
    getSelect()

  })
}

//组织范围修改
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: any) => {
    if (res.code == '0') {
      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((res: any) => {
        if (res.code == '0') {
          gettableData();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        }

      });
    })
}
//权限分配
const accessVisible: any = ref()
const accessdata: any = ref([])
const accessscreendata: any = ref([])

//默认展开节点的key数组
const DefaultDeployment: any = ref([])

//默认展开节点的key数组
const DefaultScreenDeployment: any = ref([])

//传参id
const Passparameter: any = ref([])
const PassScreenparameter: 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)
      if (valueMenu.value == '1') {
        DefaultDeployment.value.push(item.id)
      } else {
        DefaultScreenDeployment.value.push(item.id)
      }

    }
    if (item.children) {
      menuChange(item.children, ids)
    }
  })
}
const level = ref("")
function authorityClick(row: any) {
  rowid.value = row.id
  level.value = row.level
  valueMenu.value = "1"
  accessVisible.value = true
  assignment("1")
  assignment("2")
}

function assignment(row: any) {
  const params = {
    roleId: rowid.value,
    code: valueMenu.value
  }
  function handleTreeData(tree: any, arr: any = []) {
    if (!tree.length) return [];
    for (let item of tree) {
      let node: any = { ...item, children: [] }
      if (node.name == '日志管理' && level.value == '2') {
        node.disabled = true;
      }
      arr.push(node)
      if (item.children && item.children.length) handleTreeData(item.children, node.children)
    }
    return arr;
  }
  assignmentPer(params).then((res: any) => {
    if (valueMenu.value == '1') {
      accessdata.value = handleTreeData(res)
    } else[
      accessscreendata.value = res
    ]
    let ids: any = []
    menuChange(res, ids)
    nextTick(() => {
      if (valueMenu.value == '1') {
        tree.value.setCheckedKeys(ids)
        Passparameter.value = ids
      } else {
        screentree.value.setCheckedKeys(ids)
        PassScreenparameter.value = ids
      }

    })

  })
}
// 树形选择器
function currentChecked(nodeObj: any, SelectedObj: any) {
  Passparameter.value = SelectedObj.checkedKeys.concat(SelectedObj.halfCheckedKeys)
}
// 树形选择器
function currentScreenChecked(nodeObj: any, SelectedObj: any) {
  PassScreenparameter.value = SelectedObj.checkedKeys.concat(SelectedObj.halfCheckedKeys)
}
// 权限范围-权限范围-确定
function accesssubmit() {
  const parans = {
    id: rowid.value,
    menuIds: Passparameter.value.toString()
  }
  if (Passparameter.value.toString() != "" && PassScreenparameter.value.toString() != "") {
    parans.menuIds = Passparameter.value.toString() + "," + PassScreenparameter.value.toString()
  } else if (Passparameter.value.toString() == "" && PassScreenparameter.value.toString() != "") {
    parans.menuIds = PassScreenparameter.value.toString()
  }
  setMenuById(parans).then((res: any) => {
    if (res.code == '0') {
      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((res: any) => {
      if (res.code == '0') {
        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"
            @clear="gettableData" clearable />
          <el-button class="searchButton" type="primary" style="margin-left: 10px" @click="gettableData">搜索</el-button>
        </div>
        <div>
          <el-button class="searchButton" v-hasPerm="['add:role']" type="primary" @click="addClick">
            新增</el-button>
          <el-button class="searchButton" v-hasPerm="['del:role']" :type="multipleSelection.length > 0 ? 'primary' : ''"
            :disabled="multipleSelection.length <= 0" @click="delClick"> 删除</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%; height: calc(100vh - 250px)"
        @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
        :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px'}">
        <el-table-column type="selection" width="30" 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>
            <span v-show="scope.row.level == '4'">安全审计</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" class="effective">有效</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="200">
          <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/newimg/ht_xg.png" alt="" title="修改"
                @click="editrole(scope.row)" style="cursor: pointer;width:16px ;height: 16px; ">
              <img src="@/assets/newimg/ht_zz.png" alt="" title="变电站分配" @click="organizeclick(scope.row)"
                style="cursor: pointer;width:16px ;height: 16px; ">
              <img src="@/assets/newimg/ht_qij.png" alt="" title="摄像机分配" @click="businessclick(scope.row)"
                style="cursor: pointer;width:16px ;height: 16px;">
              <img src="@/assets/newimg/ht_qx.png" alt="" v-if="scope.row.level != '4'" title="权限分配"
                @click="authorityClick(scope.row)" style="cursor: pointer; ">
              <img src="@/assets/newimg/ht_qx1.png" alt="" v-if="scope.row.level == '4'" title="权限分配"
                style="cursor:not-allowed;width:16px ;height: 16px;">
              <img v-hasPerm="['del:role']" v-if="scope.row.isvaild == 0" src="@/assets/newimg/ht_sc.png" alt=""
                title="删除" @click="delrole(scope.row)" style="cursor: pointer;width:16px ;height: 16px; ">
              <img v-hasPerm="['del:role']" v-if="scope.row.isvaild == 1" src="@/assets/newimg/ht_sc1.png" title="删除"
                @click="" style="cursor: not-allowed;width:16px ;height: 16px;">
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Eldialog v-if="dialogVisible" :title="title" :zIndex="2000" :width="'620px'" :height="'600px'"
      @before-close="handleClose">
      <template v-slot:PopFrameContent>
        <el-form ref="infoForm" :model="info" :rules="rules" label-width="110px" style="margin-top: 15px;" >
          <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"
                v-show="item.value == '2' || item.value == '3'" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色描述：">
            <el-input v-model="info.description" style="width: 100%" :rows="4" type="textarea" placeholder="请输入角色描述"></el-input>
          </el-form-item>
          <span class="dialog-footer"
            style="display: flex;display: -webkit-flex; justify-content: center;-webkit-justify-content: center;">

            <div class="details-button" @click="handleClose">取消</div>
            <div class="details-button" @click="confirmClick(infoForm)">确定</div>
          </span>
        </el-form>
      </template>
    </Eldialog>
    <Eldialog v-if="businessVisible" :title="'摄像机分配'" :zIndex="2000" :width="'50%'" :height="'600px'"
      @before-close="handleClose">
      <template v-slot:PopFrameContent>
        <el-select v-model="value" placeholder=" " style="margin-bottom: 20px;width: 40%;" @change="GetCamera">
          <el-option v-for="item in optionSelect" :key="item.stationId" :label="item.stationName" :value="item.stationId"
            style="width:100%" />
        </el-select>
        <el-transfer v-loading="leftloading" v-model="leftValue"
          style="text-align: center;display: flex; align-items: center;height: 700px; " filterable :props="{
            key: 'patroldeviceId',
            label: 'patroldeviceName',
          }" :titles="['全部摄像头', '已选摄像头']" :button-texts="['到左边', '到右边']" :data="AllCamera" @change="handleChange"
          @right-check-change="handleChange">
        </el-transfer>
        <span class="dialog-footer"
          style="display: flex; display: -webkit-flex;; justify-content: center;-webkit-justify-content: center;">
          <div class="details-button" @click="handleClose">取消</div>
          <div class="details-button" @click="CreamSubmit">确定</div>
        </span>
      </template>
    </Eldialog>
    <Eldialog v-if="organizeVisible" :title="'变电站分配'" :zIndex="2000" :width="'60%'" :height="'600px'"
      @before-close="handleClose">
      <template v-slot:PopFrameContent>
        <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 v-if="deptdata.length != 1" class="line"></div>
        </div>
        <span class="dialog-footer"
          style="display: flex; display: -webkit-flex;; justify-content: center;-webkit-justify-content: center;">

          <div class="details-button" @click="organizeVisible = false">取消</div>
          <div class="details-button" @click="organizesubmit">确定</div>
        </span>
      </template>
    </Eldialog>
    <Eldialog v-if="accessVisible" :title="'权限分配'" :zIndex="2000" :width="'500px'" :height="'600px'"
      @before-close="handleClose">
      <template v-slot:PopFrameContent>
       
        <el-scrollbar v-show="valueMenu == '1'" height="400px" style="margin-top:15px;">
          <el-tree v-show="valueMenu == '1'" ref="tree" style="height: 400px;" :data="accessdata" show-checkbox
            node-key="id" :default-expanded-keys="DefaultDeployment" :props="defaultProps" @check="currentChecked" />
        </el-scrollbar>
        <el-scrollbar v-show="valueMenu == '2'" height="400px">
          <el-tree v-show="valueMenu == '2'" ref="screentree" style="height: 400px;" :data="accessscreendata"
            show-checkbox node-key="id" :default-expanded-keys="DefaultScreenDeployment" :props="defaultProps"
            @check="currentScreenChecked" />
        </el-scrollbar>
        <span class="dialog-footer"
          style="display: flex;display: -webkit-flex; justify-content: center;-webkit-justify-content: center;">

          <div class="details-button" @click="accessVisible = false">取消</div>
          <div class="details-button" @click="accesssubmit">确定</div>
        </span>
      </template>
    </Eldialog>
    <!-- <el-dialog title="权限分配" v-model="accessVisible" width="500px" :before-close="handleClose" destroy-on-close draggable
      style="height: 640px;">

    </el-dialog> -->
  </div>
</template>

<style scoped lang="scss">
.invalidcatalogue-box {
  padding: 17px 15px 8px 15px;
}

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

.dialog-footer {
  display: block;
  margin: 25px 0px 10px 0px;
}

.conductproject-bg-box {
  padding: 20px;
  width: 100%;
  height: calc(89vh);
  overflow: auto;
  background-color: rgba(255, 255, 255, 0);
  border: none;
  border-radius: 3px;
  box-sizing: border-box;
  background: url(@/assets/navigation/ty_1614x988.png);
  background-size: 100% 100%;
}

.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;
}

:deep(.el-transfer__buttons) {
  display: flex;
  flex-direction: column;
  align-items: center;

  .el-transfer__button {
    width: 100px;
    margin: 5px 0px;
  }

  .el-icon {
    display: none;
  }
}

:deep(.el-transfer-panel) {
  display: block !important;
  width: 40%;
  height: 100% !important;

  .el-transfer-panel__body {
    height: 90%;
  }
}

:deep(.el-transfer-panel__filter) {
  width: 100%;
}

:deep(.el-checkbox--default:hover) {
  color: #009bff;
}

:deep(.el-table:not(.el-table--border) .el-table__cell) {
  border: none;
  color: #fff;
}





:deep(.el-tree) {
  background-color: #ffffff00 !important;
  --el-tree-node-hover-bg-color: #0099ff09;
}

:deep(.el-input) {
  --el-input-bg-color: #ffffff00 !important;
}

:deep(.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label) {
  color: #fff !important;
}
</style>
