<!-- 选择角色 -->
<script setup lang="ts" name="SelectRoleDialog">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import type { IroleInfo } from './dialog'
import { getRoleList } from '@/api/system/role'
import { toTreeList } from '@/utils/structure'
import SearchArea from '@/components/SearchArea/index.vue'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: () => [],
  },
  // 是否允许多选
  isMulti: {
    type: Boolean,
    default: true,
  },
})

const emits = defineEmits(['update:visible', 'change'])
const table = ref()// 表格ref
// 数据权限类型字典
const dataScopeTypeDict: { [key: number ]: string } = {
  1: '所有数据',
  2: '所属及下属部门',
  3: '本部门',
  4: '自定义',
}
// 表格表头
const columns = ref([
  { text: '角色名称', value: 'name', align: 'left' },
  { text: '所在组织机构', value: 'deptName' },
])
const loading = ref(false)

// 默认查询条件
const defaultQuery = {
  keyword: '',
}
// 角色列表数据
const roleList = ref([]) as any

// 查询条件
const listQuery = reactive({ ...defaultQuery })
const checkedRoleList = ref([])
// 多选的数据
const multipleTable = ref([])
const closeDialog = () => {
  emits('update:visible', false)
}
const visibleDialog = computed({
  get() {
    return props.visible
  },
  set() {
    closeDialog()
  },
})
watch(() => props.visible, (val) => {
  if (!val) {
    table.value!.clearSelection()
  }
})
const saveDialog = () => {
  const checkedList = multipleTable.value.map((item: any) => ({
    ...item,
    type: 2, // type：1.成员，2.角色
    targetId: item.id,
  }))

  emits('change', checkedList)
}

// 角色查询数据
function fetchRoleData() {
  loading.value = true
  getRoleList(listQuery).then((res) => {
    const data = res.data.map((item: IroleInfo) => {
      return {
        ...item,
        dataScopeTypeName: dataScopeTypeDict[parseInt(item.dataScopeType)],
      }
    })
    const treeData = toTreeList(data)
    roleList.value = treeData
    loading.value = false
  })
}
// 多选
const handleSelectionChange = (val: any) => {
  console.log('多选角色')
  console.log(val)
  multipleTable.value = val
}
// 搜索
function search() {
  fetchRoleData()
}
// 多选框单选功能
const selectClick = (selection: any, row: any) => {
  if (!props.isMulti) {
    console.log('selectClick')
    if (selection.length > 1) {
      const del_row = selection.shift()
      table.value?.toggleRowSelection(del_row, false) // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    }
  }
}
onMounted(() => {
  search()
})
</script>

<template>
  <div class="select-role-dialog">
    <el-dialog v-model="visibleDialog" title="选择角色" max-width="80%" append-to-body custom-class="promoter_person">
      <search-area @search="search">
        <search-item>
          <el-input v-model="listQuery.keyword" placeholder="角色名称" clearable />
        </search-item>
      </search-area>
      <div style="padding: 12px;max-height: 500px;overflow: auto;">
        <el-table
          ref="table"
          v-loading="loading"
          show-overflow-tooltip
          :data="roleList"
          row-key="id"
          :border="false"
          style="width: 100%;"
          :default-expand-all="true"
          :tree-props="{ children: 'children' }"
          @selection-change="handleSelectionChange"
          @select="selectClick"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="column of columns" :key="column.value" :label="column.text" :prop="column.value" :align="column.align"
          />
        </el-table>
      </div>

      <template #footer>
        <el-button @click="closeDialog">
          取 消
        </el-button>
        <el-button type="primary" @click="saveDialog">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
@import "@/css/dialog.css";

.select-role-dialog {
  .el-table .cell {
    white-space: nowrap;
  }
}
</style>
