<template>
  <div class="permissions h-full">
    <div class="left" v-loading="loading">
      <PageTitle title="选择菜单" class="mb-[24px]" />

      <SearchWithButton
        width="240px"
        class="my-[16px]"
        placeholder="搜索菜单功能名称"
        v-model="condMenuName"
        @on-search="getData"
        @clear="getData"
      />

      <t-tree
        :data="menuTree"
        v-model:expanded="expandeds"
        :actived="[menuId]"
        @active="onTreeAcitve"
        activable
        hover
        transition
      >
      </t-tree>
    </div>
    <div class="right">
      <PageTitle title="数据权限" class="mb-[24px]" />

      <div class="flex items-center mb-[24px]">
        <span class="mr-[38px]">通用范围</span>
        <t-checkbox class="!text-[var(--td-font-gray-2)]" :default-checked="true" readonly>本人创建数据</t-checkbox>
      </div>
      <div class="flex mb-[24px] w-full">
        <span class="mr-[20px]">自定义范围</span>
        <div class="w-[calc(100%-90px)]">
          <t-radio-group variant="primary-filled" v-model="type" default-value="1">
            <t-radio-button value="1">角色</t-radio-button>
            <t-radio-button value="2">地区</t-radio-button>
          </t-radio-group>
          <div class="permissions-main">
            <SearchWithButton
              v-if="type == '1'"
              class="max-w-[384px] mb-[20px]"
              placeholder="搜索角色名称"
              v-model="roleName"
              @on-search="GetRoleList"
              @clear="
                () => {
                  roleName = ''
                  GetRoleList()
                }
              "
            />

            <!-- <t-input
              v-if="type == '1'"
              class="max-w-[384px] mb-[20px]"
              v-model="roleName"
              placeholder="搜索角色名称"
              @enter="GetRoleList"
              clearable
            >
              <template #suffixIcon>
                <search-icon :style="{ cursor: 'pointer' }" />
              </template>
            </t-input> -->

            <!-- 地区 -->
            <t-checkbox-group :disabled="!menuId" v-model="areas" v-show="type == '2'">
              <t-checkbox
                v-for="item in areaList"
                :value="item.dictDataId"
                :key="item.dictDataId"
                :label="item.valueName"
              />
            </t-checkbox-group>
            <!-- 角色 -->
            <t-checkbox-group v-model="roles" :disabled="!menuId" v-show="type == '1'">
              <t-checkbox v-for="item in roleList" :value="item.roleId" :key="item.roleId" :label="item.roleName" />
            </t-checkbox-group>
          </div>
        </div>
      </div>
    </div>

    <CopyPermissions ref="copyPermissionsRef" :menu-tree="menuTree" />
  </div>
</template>

<script setup lang="ts" name="data-permissions">
import { TreeProps } from 'tdesign-vue-next'
import { ResMenuTree, ResDataRange, AreasRole } from '@/api/interface/menu/index'
import { getMenuTree, postSaveDataRange, getDataRange } from '@/api/modules/menu/index'
import { ResDictionary } from '@/api/interface/dectionory/index'
import { getGetDictDataByName } from '@/api/modules/dectionory/index'
import { ResRoleList } from '@/api/interface/user-roles/index'
import { getRoleList } from '@/api/modules/user-roles/index'
import CopyPermissions from './copy-permissions.vue'

const copyPermissionsRef = ref()

const condMenuName = ref('')
const loading = ref(false)
const menuTree = ref<ResMenuTree[]>([])
const menuId = ref('')

const props = defineProps({
  roleId: {
    type: String,
    default: ''
  },
  tabValue: {
    type: Number,
    default: 1
  }
})

const expandeds = ref<string[]>()

watch([toRef(props, 'roleId')], () => {
  getData()
})

watch(toRef(props, 'tabValue'), (val: number) => {
  if (val == 2) {
    getData()
  }
})

watch(menuId, val => {
  const expands = expandeds.value || []
  expandeds.value = [...new Set(expands.concat(val as string))]
  emit('updateMenuId', menuId.value)
})

// 为树形结构的每个节点添加新参数且删除没有选择数据
function newParamToTree(tree: ResMenuTree[]): ResMenuTree[] {
  return tree
    .filter(node => node.selected)
    .map(node => {
      // 过滤出 select 为 true 的节点.map(node => {
      const newNode = {
        ...node,
        children: node?.children || [],
        label: node?.menuName || '-',
        value: node?.menuId
      }
      if (newNode.children && newNode.children.length > 0) {
        newNode.children = newParamToTree(newNode.children)
      }
      return newNode
    })
}

// 获取菜单树
const getData = () => {
  loading.value = true
  getMenuTree({ roleId: props.roleId, condMenuName: condMenuName.value })
    .then(res => {
      if (Array.isArray(res.data)) {
        // 检查 res.data 是否为数组
        menuTree.value = newParamToTree(res.data)
        menuId.value = menuTree.value[0]?.menuId || ''
        if (menuId.value) {
          GetDataRange()
        } else {
          areas.value = []
          roles.value = []
        }
      } else {
        menuId.value = '' // 如果不是数组，设置为空字符串
        menuTree.value = [] // 如果不是数组，设置为空数组
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 点击树
const onTreeAcitve: TreeProps['onActive'] = (checked, context) => {
  console.info('onChange checked:', checked)
  menuId.value = context.node?.data?.menuId || ''
  GetDataRange()
}

// 角色地区选择
const type = ref('1')
const areas = ref<string[]>([])
// 获取所有的地区
const areaList = ref<ResDictionary[]>([])
const getAreaList = () => {
  getGetDictDataByName({ dictName: '地区' }).then(res => {
    areaList.value = res.data
  })
}

// 获取所有的的角色
const roles = ref<string[]>([])
const roleName = ref('')
const roleList = ref<ResRoleList[]>([])

const GetRoleList = () => {
  getRoleList({ status: 2, roleName: roleName.value }).then(res => {
    roleList.value = res.data
  })
}

// 获取保存的数据权限
const GetDataRange = () => {
  loading.value = true
  getDataRange({ roleId: props.roleId, menuId: menuId.value })
    .then(res => {
      if (res.data) {
        const data = res.data as ResDataRange
        areas.value = data.areas?.map((item: { id: string }) => item.id) || []
        roles.value = data.roles?.map((item: { id: string }) => item.id) || []
      }
    })
    .finally(() => {
      loading.value = false
    })
}

const submit = () => {
  if (!menuId.value) {
    return MessagePlugin.error('请选择菜单')
  }

  emit('loading', true)
  // 组装地区数据
  const areaLists: AreasRole[] =
    areaList.value
      .filter(item => areas.value.includes(item.dictDataId as string))
      .map(e => {
        return { id: e.dictDataId as string, name: e.valueName as string }
      }) || []

  // 组装角色数据
  const rolesLists: AreasRole[] =
    roleList.value
      .filter(item => roles.value.includes(item.roleId as string))
      .map(e => {
        return { id: e.roleId as string, name: e.roleName as string }
      }) || []

  postSaveDataRange({ roleId: props.roleId, menuId: menuId.value, dataRange: { areas: areaLists, roles: rolesLists } })
    .then(() => {
      getData()
      MessagePlugin.success('保存成功')
    })
    .finally(() => {
      emit('loading', false)
    })
}

// 调用权限克隆
const copyPermissions = (roleID: string, sourceMenuID: string) => {
  copyPermissionsRef.value.open(roleID, sourceMenuID)
}

onMounted(() => {
  getAreaList()
  GetRoleList()
  getData()
})

const emit = defineEmits<{
  loading: [value: boolean]
  updateMenuId: [menuId: string]
}>()
defineExpose({
  getData,
  submit,
  copyPermissions
})
</script>

<style lang="less" scoped>
.permissions {
  display: flex;
  box-sizing: border-box;

  .left {
    box-sizing: border-box;
    width: 282px;
    padding: 16px;
    border-right: 1px solid var(--td-border);
  }

  .right {
    flex: 1;
    padding: 16px;
    // max-height: calc(100% - 150px);
    // overflow: auto;

    :deep(.t-radio-group.t-radio-group--filled) {
      padding: 0;

      .t-is-checked {
        background: linear-gradient(135deg, var(--td-brand-color), var(--td-success-color-11));
        border-radius: 2px;
      }
    }
  }

  &-main {
    padding: 16px;
    border: 1px solid var(--td-border);
    max-height: calc(100% - 150px);
    min-height: 80px;
    overflow: auto;

    :deep(.t-checkbox) {
      width: 178px;
      color: var(--td-font-gray-1);

      .t-checkbox__label {
        max-width: calc(100% - 24px);
      }
    }
  }
}
</style>
