<template>
  <JCollapse :data="[
    { title: '域名集合', id: '1' },
  ]" @update="(item) => domainEditOpen = true" @delete="(item) => domainDeletable = !domainDeletable"
    :deleteText="domainDeletable ? t('common.cancelButtonText') : t('marketingApps.delete')" :updateText="t('marketingApps.add')" :activeNames="['1']">
    <template #default>
      <div class="p-2 items-center flex flex-wrap">
        <template v-for="item in domains" >
          <!-- 具体域名 -->
            <el-tag v-if="item.sourceType == SourceType.DOMAIN" effect="light" :closable="domainDeletable"
            @close="handleDeleteDomain(item, SourceType.DOMAIN)" color="#f4f4f4" round class="mr-1 mb-1 cursor-pointer">
              <span class="ellipsis">{{ item.domain }}</span>
          </el-tag>
          <!-- 分组域名 -->
          <el-popover v-else width="200" trigger="hover" placement="top" @show="onLoadDetail(item)">
            <div class="flex flex-wrap break-all">
              {{ item.domains && item.domains.length ? item.domains.map(i=>i.domain).join(',') : t('marketingApps.noData') }}
            </div>
            <template #reference>
              <el-tag effect="light" :closable="domainDeletable"
                @close="handleDeleteDomain(item, SourceType.GROUP)" color="#f4f4f4" round class="mr-1 mb-1 cursor-pointer">
                <span class="ellipsis">{{ item.groupName }}</span>
              </el-tag>
            </template>
          </el-popover>
        </template>
        <div class="text-gray-400" v-if="domains.length <= 0">
          --
        </div>
      </div>
    </template>
  </JCollapse>
  <DomainEdit v-model:open="domainEditOpen" @onsuccess="addDomain" />
</template>

<script setup lang="ts" name="domainCollapse">
const JCollapse = defineAsyncComponent(() => import('/@/components/JCollapse/index.vue'));
const DomainEdit = defineAsyncComponent(() => import('./domainEdit.vue'));
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { getGroupDetail } from '/@/api/marketing/config';
import { SourceType, DomainItem } from '../types'

const props = defineProps(['data']);

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh','domains', 'delDomains']);
const { t } = useI18n();

// 定义变量内容
const domainDeletable = ref(false);// 控制域名列表项是否可删除
const domainEditOpen = ref(false);
const delDomains = ref<string[]>([]);
const domains = ref<DomainItem[]>([]);

watch(() => props.data, (newVal = []) => {
  domains.value = [];
  newVal.forEach((item: DomainItem) => {
    item.modify = false;
    domains.value = [...domains.value, item];
  })
}, { immediate: true });

// 监听domains变化，emit给父组件
watch(domains, (newVal) => {
  emit('domains', newVal);
}, { deep: true, immediate: true });
watch(delDomains, (newVal) => {
  emit('delDomains', newVal);
}, { deep: true, immediate: true });

// 删除域名
const handleDeleteDomain = (deleteItem: DomainItem, sourceType: SourceType) => {
  domains.value = domains.value.filter(i=>{
    if(!i.modify && i.id == deleteItem.id && !delDomains.value.includes(i.id as string)) {
      delDomains.value = [...delDomains.value, i.id as string];
    }
    if(sourceType == SourceType.GROUP) {
      return i.groupId != deleteItem.groupId
    }else{
      return i.domain != deleteItem.domain
    }
  });
}

// 分组去重
function addGroupsUnique(newGroups: DomainItem[]) {
  const existIds = new Set([
    ...domains.value.map(item => item.groupId),
  ]);
  const filtered:DomainItem[] = newGroups.filter(item => !existIds.has(item.id as string))
    .map(item=>{
      return {
        "sourceType": SourceType.GROUP,
        "modify": true,
        "groupId": item.id?.toString() || '',
        "groupName": item.groupName,
        "domains": item.domains,
        "domain": "",
      }
    });
  if(filtered.length) {
    domains.value = [...domains.value, ...filtered];
    console.log(filtered);
		useMessage().success(t('common.addSuccessText'));
  }else{
    useMessage().warning(t('marketingApps.addDomainTip'));
  }
}

// 域名去重
function addSinglesUnique(newSingles: DomainItem[]) {
  const existDomains = new Set([
    ...domains.value.map(item => item.domain),
  ]);
  const filtered = newSingles.filter(item => !existDomains.has(item.domain));
  if(filtered.length) {
    filtered.forEach(item => {
      Object.assign(item, {
        "groupId": "",
        "groupName": "",
        "domains": [],
        "domain": item.domain,
        "sourceType": SourceType.DOMAIN,
        "modify": true,
      })
    })
    domains.value = [...domains.value, ...filtered];
    console.log('去重后的域名：', filtered);
		useMessage().success(t('common.addSuccessText'));
  }else{
    useMessage().warning(t('marketingApps.addDomainTip2'));
  }
}

const addDomain = (data: DomainItem[], type: 'group' | 'domain') => {
  if (type === 'domain') {
    data.length && addSinglesUnique(data);
  } else {
    data.length && addGroupsUnique(data);
  }
}

const onLoadDetail = async (item: any) => {
  item.loading = true;
	if (item?.domains && item?.domains?.length !== 0) return;
	await getGroupDetail({ id: item.groupId }).then((val) => {
		item.domains = val.data.domains
	});
  item.loading = false;
};

</script>
<style lang="scss">
@import '/@/theme/mixins/index.scss';

.el-collapse-item__content {
  padding: 0;
}
.ellipsis {
  @include text-ellipsis(1);
}
</style>