<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="" prop="params.code">
              <CustomInput v-model:params="queryParams.params.USERGROUPNAME" placeholder="角色编码" clearable
                @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQueryInfo">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <span>更新时间：{{ currentTime }}</span>
        <div class="page-table-operateBtns">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            创建
          </el-button>
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList" />
          </el-popover>

        </div>
      </div>
      <el-table :height="tableHeight" border v-loading="loading" :data="roleList" highlight-current-row row-key="id" style="width: 100%">
        <template v-for="(col, index) in column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column width="160" label="操作" align="center" class-name="table-operation" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)" v-if="!scope.row.status">
              编辑
            </el-button>
            <div class="splitLine" v-if="!scope.row.status"></div>
            <el-button type="danger" link @click.stop="delConfirm(scope.row)" v-if="!scope.row.status">
              删除
            </el-button>
            <div class="splitLine" v-if="!scope.row.status"></div>
            <!-- <el-button type="primary" link v-if="!scope.row.status" @click="enable(scope.row)">
              启用
            </el-button>
            <el-button type="primary" link v-if="!!scope.row.status" @click="disable(scope.row)">
              禁用
            </el-button> -->
            <el-button type="primary" link @click.stop="handleMenu(scope.row)">
              授权
            </el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <svg-icon icon-class="noData" width="160px" height="160px" />
        </template>
      </el-table>
      <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
    </div>
    <!--  新增或编辑  -->
    <el-drawer :title="dialog.title" v-model="dialog.visible" @close="cancel" @opened="dialogOpend">
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-position="top">

        <el-form-item label="角色编码" prop="userGroupName" v-if="!state.selectItem">
          <el-input v-model="formData.userGroupName" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色名称" prop="description">
          <el-input v-model="formData.description" placeholder="请输入角色名称" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-drawer>
    <!--  分配菜单  -->
    <el-drawer :title="menuDialog.title" v-model="menuDialog.visible" @opened="menuDialogOpend">
      <el-tree ref="treeRef" v-loading="state.tree_loading" :data="menuTree" show-checkbox node-key="id"
        highlight-current :props="defaultProps" :default-checked-keys="menuDialog.defaultCheckedKeys" />
      <template #footer>
        <el-button @click="cancelMenuDialog">取 消</el-button>
        <el-button type="primary" @click="submitRoleMenu">确 定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

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

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue';
import { ElForm, ElMessageBox, ElTree } from 'element-plus';
import { getRoleList, addRole, updateRole, delRole, saveRoleMenu } from '@/api/role';  //enableRole, disableRole, getUserGroupMenu, 
import { getMenu, getMenuWithRole } from '@/api/menu';
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(180);
const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();

interface Tree {
  id: number
  label: string
  children?: Tree[]
}

const defaultProps = {
  children: 'children',
  label: 'label',
}
const treeRef = ref<InstanceType<typeof ElTree>>()

const state = reactive({
  queryParams: {
    queryId: 'GetRoleList',
    version: 'sdk001',
    params: {
      USERID: localStorage.getItem('userId'),
      USERGROUPNAME: null,
    },
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  loading: false,
  roleList: [] as any,
  dialog: {
    title: '新增角色',
    visible: false
  },
  formData: {
    userGroupName: '',
    description: '',
    // remark: ''
  } as any,
  rules: {
    userGroupName: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
    description: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  },
  column: [] as any,
  selectItem: undefined as any,
  currentTime: '',
  menuDialog: {
    title: '授权',
    visible: false,
    defaultCheckedKeys: []
  },
  menuTree: [] as any,
  tree_loading: false as any,
  checkedMenu: [] as any
})
const {
  queryParams,
  total,
  loading,
  roleList,
  dialog,
  formData,
  rules,
  column,
  selectItem,
  currentTime,
  menuDialog,
  menuTree
} = toRefs(state);

onMounted(() => {
  state.column = [
    { header: '角色编码', field: 'USERGROUPNAME', hide: false },
    { header: '角色名称', field: 'DESCRIPTION', hide: false },
  ]
  handleQuery();
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});


// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQueryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
function handleQuery() {
  state.loading = true
  state.roleList = []
  getRoleList(state.queryParams)
    .then((res: any) => {
      if(res.data.roleList.list.length == 0){
        ElMessageBox.alert('查无数据', '提醒框', {
          confirmButtonText: 'OK',
        })
        state.loading = false
      } else {
        state.roleList = res.data.roleList.list;
        state.total = res.data.roleList.total;
        state.loading = false
        showCurrentTime();
      }
    })
    .catch(() => { });
}
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}
function showCurrentTime() {
  let date = new Date()
  state.currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ":" +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
}

/**
 * 新增用户 dialog
 */
function handleAdd() {
  selectItem.value = undefined;
  dialog.value = {
    title: '新增角色',
    visible: true
  };
}
/**
 * 编辑用户 dialog
 */
function handleUpdate(row: any) {
  state.dialog = {
    title: '编辑角色',
    visible: true
  };
  state.selectItem = row;
}

function delConfirm(row: any) {
  ElMessageBox.confirm('确认删除?',
    '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    distinguishCancelAndClose: true,
    type: 'warning',
  }).then(() => {
    handleDelete(row);
  })
}
function handleDelete(row: any) {
  delRole({ userGroupName: row.USERGROUPNAME }).then((res: any) => {
    if (res.code === '0') {
      proxy.$ElMessage.success('删除成功');
      handleQuery();
    }
  })

}

function dialogOpend() {
  formDataRef.value.resetFields();
  if (state.selectItem) {
    state.formData = {
      description: state.selectItem.DESCRIPTION,
    }
  }
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}

/**
 * 保存
 */
function submitForm() {
  formDataRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.selectItem) {// 编辑
        let params = {
          userGroupName: state.selectItem.USERGROUPNAME,
          ...state.formData,
          siteName: "1",
          remark: "1",
          accessFactory: "1",
          status: "1",
          createUser: "1",
          createTime: "1",
          lastUpdateUser: "1",
          lastUpdateTime: "1"
        }
        updateRole(params).then(() => {
          proxy.$ElMessage.success('修改成功');
          cancel();
          handleQuery();
        });
      } else {
        let params = {
          ...state.formData,
          siteName: "1",
          remark: "1",
          accessFactory: "1",
          status: "1",
          createUser: "1",
          createTime: "1",
          lastUpdateUser: "1",
          lastUpdateTime: "1"
        }
        addRole(params).then((res: any) => {
          if (res.code === '0') {
            proxy.$ElMessage.success('新增成功');
            cancel();
            handleQuery();
          }
        });
      }
    }
  });
}

/************************* 授权（分配菜单） **************************/
function handleMenu(row: any) {
  state.tree_loading = true
  state.menuDialog.visible = true;
  state.selectItem = row;
  state.menuTree = [];
  state.checkedMenu = [];
}
function cancelMenuDialog() {
  state.menuDialog.visible = false;
}
async function menuDialogOpend() {

  let param = {
    queryId: "GetHierarchicalMenuWithCheckList",
    version: "sdk001",
    params: {
      USERGROUPNAME: state.selectItem.USERGROUPNAME
    }
  }
  // 获取菜单树
  await getMenuWithRole(param).then((res: any) => {
    let arr = getTree(res.data.menuList);
    state.menuTree = getChildrenNode(arr);
    state.menuDialog.defaultCheckedKeys = getCheckedKeys(state.menuTree);
  })
  state.tree_loading = false
}
/**
 * 获取选中项
 * */
function getCheckedKeys(dataList: any) {
  if (!dataList || dataList.length === 0) return
  const tempArr: any = [];
  execChecked(dataList, tempArr);
  return tempArr;
}
function execChecked(dataList: [], tempArr: any[]) {
  let parentChecked: boolean = true
  dataList.forEach((item: any) => {
    if (item.children && item.children.length > 0) {

      let f = execChecked(item.children, tempArr);
      if (f) {
        tempArr.push(item.id);
      } else {
        parentChecked = false
      }
    } else {
      if (item.checked == 'true') {
        tempArr.push(item.id);
      } else {
        parentChecked = false
      }
    }
  })
  return parentChecked
}



function getTree(dataList: any) {
  const tempArr: any = dataList['root'];

  let keys = Object.keys(dataList);
  execGetChildren(tempArr, dataList, keys);

  return tempArr;
}

function execGetChildren(arr: any, dataList: any, keys: any) {
  arr.map((item: any) => {
    if (keys.includes(item.MENUID)) {
      item.children = dataList[item.MENUID]
      execGetChildren(item.children, dataList, keys);
    }
  })
}

function getChildrenNode(dataList: any) {
  const tempArr: any = [];
  dataList.forEach((item: any) => {
    let obj = {
      label: item.PLATFORM == 'APP' ? item.MENUNAME + "(APP)" : item.MENUNAME,
      id: item.MENUID,
      checked: item.CHECKFLAG
    } as any;
    if (item.children && item.children.length > 0) {

      obj.children = getChildrenNode(item.children)
    }
    tempArr.push(obj);
  })
  return tempArr;
}




function submitRoleMenu() {

  let parentChecked = treeRef.value!.getHalfCheckedKeys();
  let childrenChecked = treeRef.value!.getCheckedKeys(false);

  let params = {
    userGroupName: state.selectItem.USERGROUPNAME,
    menuIdList: parentChecked.concat(childrenChecked)
  }

  saveRoleMenu(params)
    .then((res: any) => {
      if (res.code === '0') {
        proxy.$ElMessage.success('关联成功');
        cancelMenuDialog();
        handleQuery();
      }
    })
    .catch(() => { });
}

</script>
<style scoped lang="scss"></style>
