<script setup>
import { computed, ref, watch } from 'vue'
import selectBox from '../workFlow/selectBox.vue'
import selectResult from '../workFlow/selectResult.vue'
import { getDebounceData, getRoleList, roles, searchVal } from './common'
import $func from '@/plugins/preload.js'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: () => [],
  },
})
const emits = defineEmits(['update:visible', 'change'])
const checkedRoleList = ref([])
const list = computed(() => {
  return [{
    type: 'role',
    not: true,
    data: roles.value,
    isActive: item => $func.toggleClass(checkedRoleList.value, item, 'roleId'),
    change: (item) => {
      checkedRoleList.value = [item]
    },
  }]
})
const resList = computed(() => {
  return [{
    type: 'role',
    data: checkedRoleList.value,
    cancel: item => $func.removeEle(checkedRoleList.value, item, 'roleId'),
  }]
})
const closeDialog = () => {
  emits('update:visible', false)
}
const visibleDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    closeDialog()
  },
})
watch(() => props.visible, (val) => {
  if (val) {
    getRoleList()
    searchVal.value = ''
    checkedRoleList.value = props.data.map(({ name, targetId }) => ({
      roleName: name,
      roleId: targetId,
    }))
  }
})
const total = computed(() => checkedRoleList.value.length)
const saveDialog = () => {
  const checkedList = checkedRoleList.value.map(item => ({
    type: 2,
    targetId: item.roleId,
    name: item.roleName,
  }))
  emits('change', checkedList)
}
const delList = () => {
  checkedRoleList.value = []
}
</script>

<template>
  <el-dialog v-model="visibleDialog" title="选择角色" width="600px" append-to-body custom-class="promoter_person">
    <div class="person_body clear">
      <div class="person_tree l">
        <input v-model="searchVal" type="text" placeholder="搜索角色" @input="getDebounceData($event, 2)">
        <select-box :list="list" />
      </div>
      <select-result :total="total" :list="resList" @del="delList" />
    </div>
    <template #footer>
      <el-button @click="closeDialog">
        取 消
      </el-button>
      <el-button type="primary" @click="saveDialog">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<style>
@import "@/css/dialog.css";
</style>
