<template>
  <custom-dialog
    ref="relationRef"
    title="选择角色"
    :hasCloseIcon="true"
    :hasFooterIcon="true"
		@close="cancel"
  >
    <view class="model-content">
      <view class="user-box" v-if="state.userList.length > 0">
        <uni-role-card
          v-for="(item, index) in state.userList"
          :key="index"
          :id="item.id"
          :name="item.name"
          :code="item.code"
          :checked="state.selectedIds.includes(item.id)"
          :disabled="props.disabledIds.includes(item.id) ? true : false"
          @tap="checked(item)"
        ></uni-role-card>
      </view>
      <view class="user-box" v-else>
        <Empty title="暂无数据" />
      </view>
    </view>
    <template #footer> 
      <custom-dialog-submit @tap="confirm"></custom-dialog-submit>
    </template>
  </custom-dialog>
</template>

<script setup>
import { reactive, ref } from "vue";
import Empty from "@/components/layout/Empty.vue";
import { getRolePage } from "@/common/api/organization/index";
const props = defineProps({
  selectedList: {
    type: Array,
    default: [],
  },
  selectedIds: {
    type: String,
    default: "",
  },
  disabledIds: {
    type: Array,
    default: [],
  },
});
const emits = defineEmits(["change", "update:modelValue", "close"]);
const state = reactive({
  selectedIds: [],
  selectedList: [],
  userList: [],  
});
const relationRef = ref();
async function getInfoByIds(userIds = "") {
	const infoIds = userIds || props.selectedIds; 
	if (infoIds) {
	 const ids = infoIds.split(",");
	 const res = await getRolePage();
	 state.selectedList = res.data.filter((item) => ids.includes(item.id));
	 state.selectedIds = ids;
	}else{
	state.selectedList = []
	state.selectedIds = []
	}
}
async function open() {  
  await getUserList();
  relationRef.value.open();
}
 
function confirm() { 
  emits("change", state.selectedList);
  emits("update:modelValue", state.selectedList);
	relationRef.value.close();
  cancel();
}

function cancel() { 
	emits("close");
}

function checked(user) {
  if (state.selectedIds.includes(user.id)) {
    state.selectedIds.splice(
      state.selectedIds.findIndex((item) => item === user.id),
      1
    );
    state.selectedList.splice(
      state.selectedList.findIndex((item) => item.id === user.id),
      1
    );
  } else {
    state.selectedIds.push(user.id);
    state.selectedList.push(user);
  }
}

async function getUserList() { 
  let res = await getRolePage();
  state.userList = res.data;
} 
defineExpose({
  open, 
	getInfoByIds,
  confirm,
});
</script>

<style lang="scss" scoped>
 
.btn-list {
  .btn {
    height: 48px;
    border-radius: 24px;
    margin: 10px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .text {
      font-size: 16px;
      font-weight: 500;
      color: #ffffff;
    }
  }
  .btn1 {
    background: #5e95ff;
  }
}
</style>
