<template>
  <view class="group-manage-page">
    <view class="navbox">
      <view class="status_bar"></view>
      <uni-nav-bar
      left-icon="left"
      title="分组管理"
      @clickLeft="goBack"
      color="#8B2316"
      :border="false"
      backgroundColor="#eee"
    >
      <template #right>
        <view class="save-text" @click="saveGroups">保存</view>
      </template>
    </uni-nav-bar>
    </view>

    <view class="content-box">
      <!-- 已选中的分组 -->
    <view class="selected-section">
      <view class="tag-list">
        <view
          class="tag-item selected"
          v-for="(group, index) in selectedGroups"
          :key="group.uuid"
        >
          <text class="tag-text">{{ group.name }}</text>
        </view>
      </view>
    </view>

    <!-- 所有分组 -->
    <view class="all-groups-section">
      <view class="section-title"><text calss="red">所有分组</text>(选择分组)</view>
      <view class="tag-list">
        <view
          class="tag-item"
          :class="{ selected: isGroupSelected(group) }"
          v-for="group in allGroups"
          :key="group.uuid"
          @click="selectGroup(group)"
        >
          <text class="tag-text">{{ group.name }}</text>
        </view>
      </view>
    </view>
    </view>

    <!-- 底部添加按钮 -->
    <view class="bottom-bar">
      <button class="add-btn" @click="show=true">添加分组</button>
    </view>
  </view>
  <up-modal :show="show" :title="'添加分组'" showCancelButton confirmColor="#8B2316" @confirm="addGroup" @cancel="show=false">
    <view class="slot-content">
        <input class="input" v-model="groupName" placeholder="请输入分组名称" />
    </view>
  </up-modal>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import api from "@/api/api.js";

 const selectedGroups = ref([]);
 const allGroups = ref([]);
 const groupName = ref('');
 const show = ref(false);
 const patientUuid = ref('');
onLoad((options) => {
  patientUuid.value = options.uuid 
});

onShow(() => {
  loadAllGroups();
});

const goBack = () => uni.navigateBack();

const loadAllGroups = async () => {
  try {
    const res = await api.groupList();
    if (res.code === 200) {
      const hiddenGroupNames = new Set(['待分组患者', '肝系一生非患教组', '肝系一生患教组']);
      const arr = (res.data || []).filter((item) => !hiddenGroupNames.has(String(item?.name || '').trim()));
      allGroups.value = arr;
    }
  } catch (e) {
    console.error("加载分组列表失败:", e);
  }
};

const selectGroup = (group) => {
  // 检查是否已经选中
  const isSelected = selectedGroups.value.some((g) => g.uuid === group.uuid);
  if (isSelected) {
    // 如果已选中，则取消选中
    const index = selectedGroups.value.findIndex((g) => g.uuid === group.uuid);
    selectedGroups.value.splice(index, 1);
    return;
  }
  // 限制最多选择三个
  if (selectedGroups.value.length >= 3) {
    uni.showToast({ title: '最多选择三个分组', icon: 'none' });
    return;
  }
  // 如果未选中，则选中
  selectedGroups.value.push(group);
};

const removeSelectedGroup = (index) => {
  selectedGroups.value.splice(index, 1);
};

const isGroupSelected = (group) => {
  return selectedGroups.value.some((g) => g.uuid === group.uuid);
};

const addGroup = () => {
    if(!groupName.value){
        uni.showToast({ title: '请输入分组名称', icon: 'none' })
        return;
    }
    let userInfo=uni.getStorageSync('userInfo')
  api.groupAdd({
    patient_uuid:patientUuid.value,
    name: groupName.value,
    expert_uuid:userInfo.uuid,
  }).then(res => {
    if(res.code == 200){
        loadAllGroups();
        show.value = false;
        groupName.value = '';
    }
  })
};

const saveGroups = () => {
    api.patientCardUpdateGroup({
        name:selectedGroups.value.map(g => g.name).join(','),
        group_uuid: selectedGroups.value.map(g => g.uuid).join(','),
        patient_uuid: patientUuid.value
    }).then(res => {
        if(res.code == 200){
            uni.showToast({ title: '保存成功', icon: 'none' })
            setTimeout(() => goBack(), 700);
        }
    })
};
</script>

<style lang="scss" scoped>
.group-manage-page {
  min-height: 100vh;
  background: #fff;
  padding-bottom: 160rpx;
}

.save-text {
  color: #8b2316;
  font-size: 30rpx;
}
.input{
    width:450rpx;
    background: #f8f8f8;
			border-radius: 12rpx;
			padding: 16rpx 24rpx;
			font-size: 30rpx;
			color: #333;
}
.content-box{
  position: fixed;
  left: 0;
  right: 0;
  top: calc(var(--status-bar-height) + 44px);
  bottom: 140rpx;
  overflow-y: scroll;
  z-index: 1;
}
.selected-section {
  
  min-height: 300rpx;
  padding: 30rpx;
  border-bottom: 20rpx solid #f0f0f0;
}

.all-groups-section {
  padding: 30rpx;
}

.section-title {
  font-size: 30rpx;
  color: #999;
  margin-bottom: 20rpx;
  .red{
    color: #8b2316;
  }
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag-item {
  display: flex;
  align-items: center;
  background: #fff;
  border: 2rpx solid #999;
  border-radius: 40rpx;
  padding: 12rpx 20rpx;
  position: relative;
  &.selected {
    border-color: #8b2316;
    .tag-text {
      color: #8b2316;
    }
  }
}

.tag-text {
  font-size: 28rpx;
  color: #999;
  margin-right: 8rpx;
}

.tag-close {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background: #8b2316;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8rpx;
}

.close-icon {
  font-size: 20rpx;
  color: #fff;
  font-weight: bold;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding: 20rpx 30rpx 20rpx;
}

.add-btn {
  width: 100%;
  height: 88rpx;
  background: #20b2aa;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
