<template>
  <div class="permission-container">
    <el-form :model="permissionForm" :rules="permissionRules" ref="permissionFormRef" label-width="200px" class="demo-ruleForm">
      <el-form-item :label="$t('role_names')" prop="role_name">
        <el-input v-model="permissionForm.role_name"></el-input>
      </el-form-item>
    <!--   <el-form-item label="数据范围" prop="dept_ids">
        <el-cascader
          @visible-change="visibleChange"
          ref="cascader"
          :clearable="true"
          v-model="permissionForm.dept_ids"
          :options="deptList"
          @change="selectHandle"
          :props="props"
        ></el-cascader>
      </el-form-item> -->
      <el-form-item :label="$t('role_describe')" prop="role_describe">
        <el-input v-model="permissionForm.role_describe"></el-input>
      </el-form-item>
      <el-form-item :label="$t('role_permission')" prop="permission">
        <el-checkbox :indeterminate="allIndeterminate" v-model="allCheck" @change="handleCheckAll">{{$t('sel_all')}}</el-checkbox>
        <div v-for="(item) in permissions" :key="item.identifier" class="level_1">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-checkbox
                v-model="item.checked"
                :label="item.title"
                :indeterminate="checkIndeterminate(item.children)"
                @change="handleCheckboxChanged(item,'')"
              ></el-checkbox>
            </el-col>
            <el-col :span="20">
              <div v-for="(_item) in item.children" :key="_item.identifier" class="checkbox-dropdown">
                <el-popover placement="bottom" trigger="hover" :open-delay="300" :disabled="!hasChildren(_item)" :append-to-body="false">
                  <template #reference>
                    <el-checkbox
                      v-model="_item.checked"
                      :indeterminate="checkIndeterminate(_item.children)"
                      @click.stop
                      @change="handleCheckboxChanged(_item, item)"
                    >
                      {{ _item.title }}
                      <template v-if="hasChildren(_item)">
                        <i class="el-icon-arrow-down"></i>
                      </template>
                    </el-checkbox>
                  </template>
                  <div class="role-dropdown__list" v-if="hasChildren(_item)">
                    <div class="role-dropdown" v-for="(__item) in _item.children" :key="__item.identifier">
                      <el-popover placement="right" trigger="hover" :open-delay="200" :disabled="!hasChildren(__item)" :append-to-body="false">
                        <template #reference>
                          <div class="role-dropdown__label">
                            <el-checkbox
                              v-model="__item.checked"
                              :indeterminate="checkIndeterminate(__item.children)"
                              @click.stop
                              @change="handleCheckboxChanged(__item, _item)"
                            >
                              {{ __item.title }}
                              <template v-if="hasChildren(__item)">
                                <i class="el-icon-arrow-right"></i>
                              </template>
                            </el-checkbox>
                          </div>
                        </template>
                        <div class="role-dropdown__list" v-if="hasChildren(__item)">
                          <div class="role-dropdown" v-for="(___item, __index) in __item.children" :key="__index">
                            <el-popover placement="right" trigger="hover" :open-delay="200" :disabled="!hasChildren(___item)" :append-to-body="false">
                              <template #reference>
                                <div class="role-dropdown__label">
                                  <el-checkbox
                                    v-model="___item.checked"
                                    :indeterminate="checkIndeterminate(___item.children)"
                                    @click.stop
                                    @change="handleCheckboxChanged(___item, __item)"
                                    >{{ ___item.title }}</el-checkbox
                                  >
                                </div>
                              </template>
                            </el-popover>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                  </div>
                </el-popover>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" size="small" style="margin-top: 15px" @click="saveRolePermission">保存设置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
    
    <script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as API_Auth from '@/api/auth';
import * as API_Menus from '@/api/menus';
import * as API_Setting from '@/api/setting';
/*   import { Foundation } from '../../composables/ui-utils'; */
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const route = useRoute();
const router = useRouter();

const props = {
  label: 'name',
  value: 'id',
  emitPath: false,
  multiple: true,
  checkStrictly: true,
};

const checked = ref(true);
const deptList = ref<any>([]);
const oneDimensionalList = ref([]); // 源数据平铺成一级节点

/** 权限 表单 */
const permissionForm = reactive<{
  data_scope: string,
  role_name: string,
  dept_ids: string,
  role_describe: string,
}>({
  data_scope: 'ALL',
  role_name: '',
  dept_ids: "",
  role_describe: '',
});

/** 权限 表单规则 */
const permissionRules = reactive({
  role_name: [
    { required: true, message: t('place')+t('role_names')+'!', trigger: 'blur' },
    { min: 1, max: 10, message: t('role_name_error'), trigger: 'blur' },
  ],
});

const permissions = ref<any>([]);
const allCheck = ref(false);
const allIndeterminate = ref(false);
const isAllSelected = ref(false);

const role_id = ref<any>(route.query.id);
console.log('role_id:', route.query);
/* const searchSelectAllNodeIndex = () => {
  let selectAllOptionIndex = -1;
  permissionForm.dept_ids.forEach((res, index) => {
    if (res.length === 1) {
      selectAllOptionIndex = index;
    }
  });
  return selectAllOptionIndex;
}; */

const visibleChange = (visible) => {
  if (visible) {
    deptList.value.unshift({
      id: '全选',
      name: '全选',
      value: '全选',
    });
  } else {
    deptList.value.shift();
  }
};

// 选择级联选择器
/* const selectHandle = async (e = []) => {
  const selectLength = e.filter((v) => v !== '全选').length;
  const has_all_option = e.some((v) => v === '全选');
  let dept_ids = [...permissionForm.dept_ids];

  if (has_all_option && isAllSelected.value) {
    // 移除了选项中除全部外的某个节点
    dept_ids = dept_ids.filter((v) => v !== '全选');
    dept_ids.splice(searchSelectAllNodeIndex(), 1);
    permissionForm.dept_ids = dept_ids;
    isAllSelected.value = false;
  } else if (has_all_option && !isAllSelected.value) {
    // 选中全部节点
    isAllSelected.value = true;
    const deptListData = deptList.value;
    const dept_ids:any = [];
    const loopSelectData = (list) => {
      list.forEach((e) => {
        dept_ids.push(e.id);
        if (e.children && e.children.length > 0) {
          loopSelectData(e.children);
        }
      });
    };
    loopSelectData(deptListData);
    permissionForm.dept_ids = dept_ids;
  } else if (!has_all_option && isAllSelected.value) {
    // 取消选中全部节点
    isAllSelected.value = false;
    permissionForm.dept_ids = [];
  } else if (selectLength === oneDimensionalList.value.length) {
    isAllSelected.value = true;
    dept_ids.unshift('全选');
    permissionForm.dept_ids = dept_ids;
  }
  nextTick(() => {
    // 强制更新
  });
}; */
/* 处理树形数据 */
let buildTree = function buildTree(list, parent_id) {
  const tree:any = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i].parent_id === parent_id) {
      const node = {
        id: list[i].id,
        parent_id: list[i].parent_id,
        name: list[i].name,
        create_time: list[i].create_time,
        remark: list[i].remark,
        sn: list[i].sn,
        sort: list[i].sort,
        type: list[i].type,
        region_ids: list[i].region_ids,
        children: buildTree(list, list[i].id),
      };
      tree.push(node);
    }
  }
  return tree;
};
/** 获取部门 */
const GET_DeptList = () => {
  API_Setting.getDeptList({page_no:1,page_size:1000}).then((response) => {
    deptList.value = buildTree(response, '0');
    const oneDimensionalListData:any = [];
    const loopData = (list) => {
      list.forEach((e) => {
        oneDimensionalListData.push(e);
        if (e.children && e.children.length > 0) {
          loopData(e.children);
        }
      });
    };
    loopData(response);
    oneDimensionalList.value = oneDimensionalListData;
    if (permissionForm.dept_ids.length === oneDimensionalListData.length) {
      // 设置数据范围全选
     /*  permissionForm.dept_ids.push('全选'); */
      isAllSelected.value = true;
    }
  });
};

/** 判断是否还有子集 */
const hasChildren = (item) => {
  return Array.isArray(item.children) && item.children.length !== 0;
};

/** 全选 */
const handleCheckAll = (checked) => {
  allIndeterminate.value = false;
  permissions.value = setPermissionsCheck(permissions.value, checked);
};

/** 选择 */
const handleCheckboxChanged = (item, parent) => {
  if (item.children && item.children.length) {
    item.children = setPermissionsCheck(item.children, item.checked);
  }
  countAllPermissions(permissions.value);
  countParentChecked(permissions.value);
};

/** 设置权限状态 */
const setPermissionsCheck = (permissions, checked) => {
  const perm = [...permissions];
  perm.map((item) => {
    item.checked = checked;
    if (item.children && item.children.length) {
      item.children = setPermissionsCheck(item.children, checked);
    }
  });
  return perm;
};

/** 检测是否有不确定性 */
const checkIndeterminate = (permissions) => {
  if (!Array.isArray(permissions)) return false;
  const _len = permissions.length;
  const __len = permissions.filter((item) => item.checked).length;
  return __len !== 0 && _len !== __len;
};

/** 获取所有权限展开后的长度、被选中的长度 */
const countAllPermissions = (perms?: any[]) => {
  const currentPermissions = perms || permissions.value;
  if (!Array.isArray(currentPermissions)) {
    console.warn('permissions is not an array:', currentPermissions);
    return [];
  }
  const _list:any = [];
  currentPermissions.forEach((item) => {
    _list.push(item);
    if (item.children) _list.push(...countAllPermissions(item.children));
  });
  const length = _list.length;
  const length_checked = _list.filter((_item) => _item.checked).length;
  allCheck.value = length === length_checked;
  allIndeterminate.value = length_checked !== 0 && length !== length_checked;
  return _list;
};

/** 计算所有父辈的选中状态 */
const countParentChecked = (perms?: any[]) => {
  const currentPermissions = perms || permissions.value;
  currentPermissions.forEach((item) => {
    if (item.children && item.children.length) {
      countParentChecked(item.children);
      const length = item.children.length;
      const checked_length = item.children.filter((_item) => _item.checked).length;
      item.checked = !!checked_length;
    }
  });
};

/** 保存角色权限 */
const permissionFormRef = ref();
const saveRolePermission = () => {
  permissionFormRef.value.validate((valid) => {
    if (valid) {
      let params = {
        ...permissionForm,
        menus: permissions.value,
      };
  /*     if (!params.dept_ids) {
        ElMessage.error('请选择数据范围！');
        return;
      }
      params.dept_ids = params.dept_ids.filter((v) => v !== '全选');
      if (params.dept_ids) {
        if (isAllSelected.value) {
          params.data_scope = 'ALL';
          params.dept_ids = params.dept_ids.join(',');
        } else {
          params.data_scope = 'DEPT_CUSTOM';
          params.dept_ids = params.dept_ids.join(',');
        }
      } */
      const saveSuccess = () => {
        ElMessage.success(t('sub_success'));
        router.push({ name: 'roleManage' });
      };
      role_id.value === '0' ? API_Auth.addRole(params).then(() => saveSuccess()) : API_Auth.editRole(role_id.value, params).then(() => saveSuccess());
    } else {
      ElMessage.error(t('form_erroe'));
      return false;
    }
  });
};

/** 获取权限菜单树 */
const GET_RolePermission = () => {
  API_Menus.getMenusChildren().then((res) => {
    if (role_id.value !== '0') {
      API_Auth.getRolePermission(role_id.value).then((response) => {
        // ... existing code ...
        const checkedIds = expandRouters(response.menus);
        permissions.value = filterRoleRouter(res, checkedIds);
        if (Array.isArray(permissions.value)) {
          countAllPermissions();
        } else {
          console.warn('Invalid permissions data:', permissions.value);
        }
        GET_DeptList();
      });
    } else {
      permissions.value = res;
      if (Array.isArray(permissions.value)) {
        countAllPermissions();
      } else {
        console.warn('Invalid permissions data:', permissions.value);
      }
      GET_DeptList();
    }
  });
};

/** 展开路由的identifier */
const expandRouters = (menus) => {
  const routers:any = [];
  menus.forEach((item) => {
    item.checked && routers.push(item.identifier);
    if (item.children && item.children.length) {
      routers.push(...expandRouters(item.children));
    }
  });
  return routers;
};

/** 递归筛选被选中的路由 */
const filterRoleRouter = (routers, ids) => {
  const _routers:any = [];
  routers.forEach((item) => {
    if (ids.includes(item.identifier) || item.hidden) {
      item.checked = true;
    } else {
      item.checked = false;
    }
    if (item.children) {
      item.children = filterRoleRouter(item.children, ids);
    }
    _routers.push(item);
  });
  return _routers;
};

onMounted(() => {
  GET_RolePermission();
});

watch(
  () => route.query.id,
  () => {
    role_id.value = route.query.id;
    GET_RolePermission();
  }
);
</script>
    
  <style scoped>
.permission-container {
  padding: 10px;
  background-color: #fff;
  padding-bottom: 150px;
}

.level_1 {
  padding: 15px 0;
  border-bottom: 1px dashed #e7e7e7;
}

.level_1:last-child {
  border-bottom: none;
}

::v-deep .el-form-item__label {
  padding-top: 15px;
}

::v-deep .el-form-item__content {
  display: block;
  border-left: 1px solid #e7e7e7;
  padding-left: 20px;
  padding-top: 15px;
}

::v-deep .el-form-item__content .el-form-item__error {
  padding-left: 20px;
}

::v-deep .el-form-item:last-child .el-form-item__content {
  padding-top: 0;
}

::v-deep .el-form-item:not(:first-child) {
  border-top: 1px solid #e7e7e7;
  position: relative;
}

::v-deep .el-form-item:not(:first-child)::after {
  content: ' ';
  width: 1px;
  height: 22px;
  background-color: #e7e7e7;
  position: absolute;
  top: -22px;
  left: 200px;
}

::v-deep .el-button-group {
  display: inline-block;
}

::v-deep .el-button-group .el-button {
  display: inline-block;
  padding: 0;
  border: none;
}

::v-deep .el-button-group .el-button:focus,
::v-deep .el-button-group .el-button:hover {
  color: #606266;
  border-color: #fff;
  background-color: #fff;
}

.checkbox-dropdown {
  display: inline-block;
  min-width: 130px;
  cursor: pointer;
}

.checkbox-dropdown .checked {
  color: #409eff;
}

.role-dropdown {
  display: flex;
  align-items: center;
  width: 25%;
  height: 30px;
  margin-bottom: 10px;
}

.role-dropdown:last-child {
  margin-bottom: 0;
}

.role-dropdown__label {
  display: flex;
  align-items: center;
  width: 100%;
}

::v-deep .role-dropdown__label .el-checkbox__label {
  color: inherit;
}

.role-dropdown__list {
  max-height: 320px;
  overflow-y: auto;
}
</style>