<template>
  <view class="consult-container">
    <view class="consult-title">团队服务</view>

    <view class="consult-grid">
      <view class="consult-item" v-for="item in consultItems" :class="hideMenus[item.id] ? 'consult-item--hiden' : ''"
        :key="item.id" @click="handleItemClick(item)">
        <view class="relative item-icon">
          <image :src="item.icon" class="icon-img" mode="aspectFill" />
          <view v-if="badgeMap[item.badge]" class="item-dot"></view>
        </view>
        <view class="item-label">{{ item.label }}</view>
      </view>
    </view>

    <!-- 选择咨询人弹窗 -->
    <select-consultant-popup ref="consultantPopup" :customers="customers" :corpId="corpId" :teamId="teamId"
      @confirm="handleConsultantConfirm" @addNew="handleAddNewArchive" />
  </view>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import useAccount from "@/store/account";
import api from "@/utils/api";
import { toast } from "@/utils/widget";
import SelectConsultantPopup from "./select-consultant-popup.vue";

const props = defineProps({
  corpId: {
    type: String,
    default: "",
  },
  team: {
    type: Object,
    default: () => ({})
  },
  teamId: {
    type: String,
    default: "",
  },
  customers: {
    type: Array,
    default: () => [],
  },
});

const { account } = storeToRefs(useAccount());
const consultantPopup = ref(null);
const badgeMap = ref({});
let loading = false;

const consultItems = ref([
  {
    id: "chat",
    label: "聊天咨询",
    icon: "/static/home/chat-consult.png",
    needSelectConsultant: true,
    badge: 'chat'
  },
  {
    id: "education",
    label: "我的宣教",
    icon: "/static/home/my-education.png",
    path: "/pages/article/article-list",
    badge: 'article'
  },
  {
    id: "survey",
    label: "我的问卷",
    icon: "/static/home/my-questionnaire.png",
    path: "/pages/survey/survey-list",
    badge: 'survey'
  },
  {
    id: "rating",
    label: "服务评价",
    icon: "/static/home/service-rating.png",
    path: "/pages/rate/rate-list",
    badge: 'rate'
  },
]);
const hideMenus = computed(() => {
  const result = {};
  // 非医助手团队
  if (!(props.team && props.team.createSource === 'yzs')) {
    result.chat = true;
  }
  return result;
})

function handleItemClick(item) {
  // 聊天咨询需要选择咨询人
  if (item.needSelectConsultant) {
    if (!(props.team && props.team.createSource === 'yzs')) {
      return toast('该团队暂未开放咨询服务')
    }

    if (!props.customers || props.customers.length === 0) {
      toast("请先添加档案");
      // 跳转到档案管理页面
      uni.navigateTo({
        url: `/pages/archive/archive-manage?corpId=${props.corpId}&teamId=${props.teamId}`,
      });
      return;
    }

    // 打开选择咨询人弹窗
    consultantPopup.value?.open();
    return;
  }

  // 其他功能直接跳转
  if (!item.path) {
    toast("功能开发中");
    return;
  }

  uni.navigateTo({
    url: `${item.path}?teamId=${props.teamId}&corpId=${props.corpId}`,
    fail: () => {
      toast("页面跳转失败");
    },
  });
}

// 确认选择咨询人
async function handleConsultantConfirm(customer) {
  const teamIds = customer && Array.isArray(customer.teamId) ? customer.teamId : [];
  if (!teamIds.includes(props.teamId)) {
    const res = await api("authCustomerToTeam", {
      corpId: props.team.corpId,
      teamId: props.team.teamId,
      id: customer._id,
    });
    if (res && res.success) {
      uni.$emit("reloadTeamCustomers");
    } else {
      toast(res?.message || "授权团队失败");
    }
  }
  // 调用创建咨询群组接口
  uni.showLoading({ title: "创建咨询中..." });
  try {
    const res = await api("createConsultGroup", {
      teamId: props.teamId,
      corpId: props.corpId,
      customerId: customer._id,
      customerImUserId: account.value.openid,
    });
    uni.hideLoading();
    if (res && res.success) {
      const { groupId, isExisting } = res.data;
      // 跳转到聊天页面
      uni.navigateTo({
        url: `/pages/message/index?conversationID=GROUP${groupId}&groupID=${groupId}`,
      });
    } else {
      toast(res?.message || "创建咨询失败");
    }
  } catch (error) {
    uni.hideLoading();
    console.error("创建咨询群组失败:", error);
    toast("创建咨询失败");
  }
}

// 新建档案
function handleAddNewArchive() {
  uni.navigateTo({
    url: `/pages/archive/edit-archive?corpId=${props.corpId}&teamId=${props.teamId}`,
  });
}

async function getBadgeCount() {
  if (loading) return;
  loading = true;
  const customerIds = props.customers.map((item) => item._id);
  if (customerIds.length === 0) {
    badgeMap.value = {};
    loading = false
    return
  }
  const res = await api('getMiniAppHomeStats', { corpId: props.corpId, teamId: props.teamId, customerIds }, false)
  const data = res?.data || {};
  const article = typeof data.article === 'number' ? data.article : 0;
  const survey = typeof data.survey === 'number' ? data.survey : 0;
  const rate = typeof data.rate === 'number' ? data.rate : 0;
  badgeMap.value = { article, survey, rate };
  loading = false;
}

watch(() => [props.customers, props.teamId, props.corpId], n => {
  getBadgeCount()
}, { immediate: true })

defineExpose({
  getBadgeCount,
})
</script>

<style lang="scss" scoped>
.consult-container {
  margin: 0 30rpx;
  margin-top: 24rpx;
}

.consult-title {
  color: #000000;
  font-size: 38rpx;
  font-style: normal;
  font-weight: 600;
  line-height: normal;
  margin-bottom: 24rpx;
}

.consult-grid {
  height: 208rpx;
  box-sizing: border-box;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx 30rpx;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  align-items: center;
  gap: 32rpx;
  box-shadow: 0 8rpx 10rpx 0 rgba(60, 169, 145, 0.06);
}

.consult-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
  cursor: pointer;
}

.consult-item--hiden {
  display: none;
}

.item-icon {
  width: 80rpx;
  height: 80;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s;
  overflow: hidden;
}

.item-dot {
  position: absolute;
  right: 0;
  top: 0;
  width: 20rpx;
  height: 20rpx;
  background: red;
  border-radius: 50%;
}

.consult-item:active .item-icon {
  transform: scale(0.95);
}

.icon-img {
  width: 80rpx;
  height: 80rpx;
}

.item-label {
  font-size: 30rpx;
  color: #666d76;
  text-align: center;
  font-weight: 400;
}
</style>
