<template>
  <div
    :class="isInline ? 'inline' : 'w-full'"
    @click="show"
    :key="Math.random().toString(36).slice(-8)"
  >
    <div :class="{ inline: isInline }"><slot></slot></div>

    <ModalPanel
      :visible="data.visible"
      :width="1200"
      :title="t('添加角色')"
      @submit="submit"
      @close="close"
    >
      <div class="relative h-full">
        <!-- 已选 -->
        <Selected type="role" :list="data.selectedList" @abolish="abolishChecked" />
        <div class="absolute top-2 right-105px flex items-center"
          ><SearchBox @search="search" /><div
            class="h-6 pr-4"
            style="border-right: 1px solid #ddd"
          ></div
        ></div>
        <div class="list-page-box" v-if="data.list.length > 0">
          <RoleCard
            :class="
              data.selectedIds && data.selectedIds.includes(item.id) ? 'picked' : 'not-picked'
            "
            v-for="(item, index) in data.list"
            :key="index"
            :item="item"
            @click="checked(item)"
          >
            <template #check>
              <a-checkbox
                size="small"
                :checked="data.selectedIds && data.selectedIds.includes(item.id)"
              />
            </template>
          </RoleCard>
        </div>
        <EmptyBox v-if="data.list.length == 0" />
      </div>
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive } from 'vue';
  import RoleCard from './card/RoleCard.vue';
  import Selected from './Selected.vue';
  import { ModalPanel, EmptyBox, SearchBox } from '/@/components/ModalPanel/index';
  import { cloneDeep } from 'lodash-es';
  import { getRoleList, getRoleMulti } from '/@/api/system/role';
  import { RoleInfo } from '/@/api/system/role/model';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emits = defineEmits(['change', 'changeNames']);
  const props = withDefaults(
    defineProps<{
      selectedIds: Array<string> | string;
      multiple?: Boolean;
      isInline?: Boolean;
    }>(),
    {
      selectedIds: () => {
        return [];
      },
      disabledIds: () => {
        return [];
      },
    },
  );
  let data: {
    visible: boolean;
    multiSelect: boolean;
    list: Array<RoleInfo>;
    selectedList: Array<RoleInfo>;
    selectedIds: Array<string>;
    searchConfig: {
      keyword: string;
    };
  } = reactive({
    visible: false,
    multiSelect: false,
    selectedIds: [],
    list: [],
    selectedList: [],
    searchConfig: {
      keyword: '',
    },
  });
  onMounted(() => {
    if (props.selectedIds) {
      data.selectedIds = Array.isArray(props.selectedIds)
        ? cloneDeep(props.selectedIds)
        : props.selectedIds.split(',');
      getSelectedList();
    }
  });
  async function show() {
    data.selectedIds = [];
    if (props.selectedIds) {
      data.selectedIds = Array.isArray(props.selectedIds)
        ? cloneDeep(props.selectedIds)
        : props.selectedIds.split(',');
    }
    await getList();
    await getSelectedList();
    data.visible = true;
  }
  function submit() {
    emits('change', data.selectedIds);
    changeSelectedNames();
    close();
  }
  function close() {
    data.list = [];
    data.selectedIds = [];
    data.selectedList = [];
    data.visible = false;
  }
  function checked(item) {
    if (props.multiple && props.multiple == true) {
      if (data.selectedIds.includes(item.id)) {
        data.selectedIds.splice(
          data.selectedIds.findIndex((itemId) => itemId === item.id),
          1,
        );
        data.selectedList.splice(
          data.selectedList.findIndex((ele) => ele.id === item.id),
          1,
        );
      } else {
        data.selectedIds.push(item.id);
        data.selectedList.push(item);
      }
    } else {
      if (data.selectedIds.includes(item.id)) {
        data.selectedIds = [];
        data.selectedList = [];
      } else {
        data.selectedIds = [item.id];
        data.selectedList = [item];
      }
    }
  }

  async function getList() {
    data.list = [];
    let params = {
      keyword: data.searchConfig.keyword,
    };
    let list = await getRoleList(params);
    if (list.length > 0) {
      list.forEach((ele) => {
        data.list.push({
          name: ele.name,
          id: ele.id,
          code: ele.code,
          count: ele.count, //角色人数
        });
      });
    }
  }
  function search(keyword: string) {
    data.searchConfig.keyword = keyword;
    getList();
  }
  async function getSelectedList() {
    data.selectedList = [];
    let list = await getRoleMulti(data.selectedIds.join(','));
    if (list.length > 0) {
      list.forEach((ele) => {
        data.selectedList.push({
          name: ele.name,
          id: ele.id,
          code: ele.code,
          count: ele.count, //角色人数
        });
      });
    }
    changeSelectedNames();
  }
  function abolishChecked(id: string) {
    data.selectedList = data.selectedList.filter((ele) => {
      return ele.id != id;
    });
    data.selectedIds.splice(
      data.selectedIds.findIndex((itemId) => itemId === id),
      1,
    );
  }
  function changeSelectedNames() {
    let userNames = data.selectedList
      .map((ele) => {
        return ele.name;
      })
      .join(',');
    emits('changeNames', userNames);
  }
</script>
<style lang="less" scoped>
  .list-page-box {
    height: calc(100% - 50px);
    padding-bottom: 16px;
  }
</style>
