<template>
  <view class="page">
    <scroll-view scroll-y class="scroll">
      <view v-for="(group, idx) in tagGroups" :key="group.id || idx" class="group">
        <view class="group-title">
          <text>{{ group.groupName || '标签' }}</text>
          <text v-if="group.createType === 'corpAsync'" class="hint">(企微标签)</text>
        </view>
        <view class="tags">
          <view
            v-for="tag in group.tag"
            :key="tag.id"
            class="tag"
            :class="selectedMap[tag.id] ? 'active' : ''"
            @click="toggle(tag.id)"
          >
            {{ tag.name }}
          </view>
        </view>
      </view>
      <view class="spacer" />
    </scroll-view>

    <view class="footer">
      <view class="btn plain" @click="cancel">取消</view>
      <view class="btn primary" @click="save">确定</view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

import api from '@/utils/api';
import useAccountStore from '@/store/account';
import { hideLoading, loading, toast } from '@/utils/widget';

const accountStore = useAccountStore();
const account = computed(() => accountStore.account);
const doctorInfo = computed(() => accountStore.doctorInfo);

const eventName = ref('change-tag-list');
const selections = ref([]);
const tagGroups = ref([]);

const selectedMap = computed(() =>
  selections.value.reduce((m, id) => {
    m[String(id)] = true;
    return m;
  }, {})
);

function unwrapListPayload(res) {
  const root = res && typeof res === 'object' ? res : {};
  const d = root.data && typeof root.data === 'object' ? root.data : root;
  if (!d) return [];
  if (Array.isArray(d)) return d;
  if (Array.isArray(d.list)) return d.list;
  if (Array.isArray(d.data)) return d.data;
  if (d.data && typeof d.data === 'object') {
    if (Array.isArray(d.data.list)) return d.data.list;
    if (Array.isArray(d.data.data)) return d.data.data;
  }
  return [];
}

function normalizeGroups(list) {
  const groups = Array.isArray(list) ? list : [];
  return groups
    .map((g) => {
      const tag = Array.isArray(g?.tag) ? g.tag : Array.isArray(g?.tags) ? g.tags : [];
      return {
        id: g?.id || g?._id || g?.groupId || '',
        groupName: g?.groupName || g?.name || '',
        createType: g?.createType || '',
        tag: (Array.isArray(tag) ? tag : [])
          .map((t) => ({
            id: String(t?.id || t?._id || t?.tagId || ''),
            name: String(t?.name || t?.label || ''),
          }))
          .filter((t) => t.id && t.name),
      };
    })
    .filter((g) => g.tag.length > 0);
}

function getCorpId() {
  const env = __VITE_ENV__;
  return String(account.value?.corpId || doctorInfo.value?.corpId || env.MP_CORP_ID || '');
}

async function loadTags() {
  const corpId = getCorpId();
  if (!corpId) return;

  loading('加载中...');
  const res = await api('getCorpTags', { corpId });
  hideLoading();
  if (!res?.success) {
    toast(res?.message || '获取标签失败');
    tagGroups.value = [];
    return;
  }
  const list = unwrapListPayload(res);
  tagGroups.value = normalizeGroups(list);
}

function toggle(id) {
  const key = String(id);
  if (!key) return;
  if (selectedMap.value[key]) {
    selections.value = selections.value.filter((i) => String(i) !== key);
  } else {
    selections.value = [...selections.value, key];
  }
}

function cancel() {
  uni.navigateBack();
}

function save() {
  const list = selections.value.map(String).filter(Boolean);
  uni.$emit(eventName.value, list);
  uni.navigateBack();
}

onLoad(async (query) => {
  if (query?.eventName) eventName.value = String(query.eventName);
  const cached = uni.getStorageSync('ykt_tag_list_selections');
  uni.removeStorageSync('ykt_tag_list_selections');
  selections.value = Array.isArray(cached) ? cached.map(String).filter(Boolean) : [];
  await loadTags();
});
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.scroll {
  flex: 1;
  min-height: 0;
}

.group {
  padding: 30rpx;
}

.group-title {
  font-size: 30rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.hint {
  font-size: 24rpx;
  color: #5d8aff;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag {
  max-width: 100%;
  padding: 12rpx 20rpx;
  border: 1px solid #ddd;
  border-radius: 16rpx;
  font-size: 26rpx;
  line-height: 1.2em;
  color: #333;
  background: #fff;
  word-break: break-all;
}

.tag.active {
  color: #fff;
  border-color: #5d8aff;
  background: #5d8aff;
}

.spacer {
  height: 120rpx;
}

.footer {
  padding: 24rpx 30rpx calc(24rpx + env(safe-area-inset-bottom));
  display: flex;
  gap: 20rpx;
  border-top: 1px solid #eee;
  background: #fff;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  text-align: center;
}

.btn.plain {
  background: #fff;
  color: #666;
  border: 1px solid #ddd;
}

.btn.primary {
  background: #5d8aff;
  color: #fff;
}
</style>
