<template>
  <full-page v-if="team" pageClass="bg-white">
    <view class="p-15">
      <view class="flex items-center h-30 mb-10">
        <view class="mr-5 text-dark text-lg font-semibold truncate">{{ team.name }}</view>
        <view v-if="isLeader" class="edit-sub flex-shrink-0 flex items-center justify-center rounded-full bg-primary"
          @click="toEdit()">
          <image class="edit-icon" src="/static/work/pen.svg" mode="aspectFill" />
        </view>
      </view>
      <view class="text-base text-dark leading-normal break-all" :class="expand ? '' : 'line-clamp-3'"
        @click="expand = !expand">
        {{ team.teamTroduce || '暂无简介' }}
      </view>
      <view class="mt-12 py-12 flex items-center justify-between">
        <view class="text-lg text-dark">团队成员</view>
        <view class="flex items-center text-primary text-base" @click="invite()">
          邀请成员
        </view>
      </view>
      <view v-for="i in teammates" :key="i._id" class="mb-10 p-10 border rounded flex">
        <image class="flex-shrink-0 mr-10 avatar" :src="i.avatar || '/static/default-avatar.png'" />
        <view class="w-0 flex-grow">
          <view class="flex items-center">
            <view class="mr-5 text-lg font-semibold text-dark truncate">{{ i.anotherName }}</view>
            <!-- <view v-if="i.isCreator"
              class="mr-5 px-10 flex-shrink-0 border-auto text-sm leading-normal text-primary rounded-full">
              创建人
            </view> -->
            <view v-if="i.isLeader"
              class="px-10 flex-shrink-0 border-auto text-sm leading-normal text-primary rounded-full">
              团队负责人
            </view>
            <view class="flex-grow"></view>
            <view v-if="isLeader && doctorInfo && i.userid !== doctorInfo.userid && !i.isCreator" class="px-5"
              @click="showActions(i)">
              <uni-icons type="more-filled" size="20" color="#999"></uni-icons>
            </view>
          </view>
          <view class="text-base text-dark leading-normal break-all line-clamp-2 mt-5">
            {{ i.memberTroduce || '暂无简介' }}
          </view>
        </view>
      </view>
      <view class="safe-bottom-padding"></view>
    </view>
    <template #footer>
      <button-footer v-if="canQuit" cancelText="退出当前团队" :showConfirm="false" @cancel="quit()" />
    </template>
  </full-page>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { storeToRefs } from "pinia";
import useGuard from "@/hooks/useGuard.js";
import useAccountStore from "@/store/account.js";
import api from '@/utils/api';
import { confirm, toast } from "@/utils/widget";

import buttonFooter from '@/components/button-footer.vue';
import fullPage from '@/components/full-page.vue';

const { useLoad, useShow } = useGuard();
const { doctorInfo, account } = storeToRefs(useAccountStore());
const teamId = ref('');
const team = ref(null);
const expand = ref(false);

const canQuit = computed(() => team.value && doctorInfo.value && team.value.creator !== doctorInfo.value.userid);
const isLeader = computed(() => {
  const userid = doctorInfo.value?.userid;
  const member = teammates.value.find(i => i.userid === userid);
  return member?.isLeader || member?.isCreator;
})
const memberList = computed(() => team.value && Array.isArray(team.value.memberList) ? team.value.memberList : [])
const teammates = computed(() => {
  const memberLeaderList = team.value && Array.isArray(team.value.memberLeaderList) ? team.value.memberLeaderList : [];
  const res = memberList.value.reduce((data, item) => {
    if (item.userid && item.userid === team.value.creator) {
      data.creator.push(item)
    } else if (memberLeaderList.includes(item.userid)) {
      data.leaders.push(item)
    } else {
      data.members.push(item)
    }
    return data
  }, { creator: [], leaders: [], members: [] });
  console.log(res)
  return [
    ...res.creator.map(i => ({ ...i, isCreator: true, isLeader: true })),
    ...res.leaders.map(i => ({ ...i, isLeader: true })),
    ...res.members
  ]
})

function invite() {
  uni.navigateTo({
    url: `/pages/work/team/invite/invite-teammate?teamId=${teamId.value}`
  })
}

function showActions(i) {
  uni.showActionSheet({
    itemList: [i.isLeader ? '取消负责人' : '设为负责人', '移出团队'],
    success: (res) => {
      if (res.tapIndex === 0) {
        toggleLeaderRole(i.isLeader ? 'cancel' : 'set', i.userid)
      } else {
        removeTeammate(i.userid);
      }
    }
  })
}

function toEdit() {
  uni.navigateTo({
    url: `/pages/work/team/edit/team-edit?teamId=${teamId.value}`
  })
}

async function getTeam() {
  const res = await api('getTeamData', { teamId: teamId.value, corpId: account.value.corpId });
  if (res && res.data) {
    team.value = res.data;
  } else {
    toast(res?.message || '获取团队信息失败')
  }
}

async function quit() {
  await confirm('确定退出当前团队吗？');
  removeTeammate(doctorInfo.value.userid);
}

async function toggleLeaderRole(toggleType, mateId) {
  await confirm(toggleType === 'set' ? '确定设为负责人吗？' : '确定取消负责人吗？');
  const data = {
    corpId: account.value.corpId,
    teamId: teamId.value,
    mateId,
    operatorId: doctorInfo.value.userid,
    toggleType
  }
  const res = await api('toggleTeamLeaderRole', data);
  if (res && res.success) {
    await toast('操作成功');
    getTeam();
  } else {
    toast(res?.message || '操作失败')
  }
}

async function removeTeammate(mateId) {
  if (mateId !== doctorInfo.value.userid) {
    await confirm('确定移出该成员吗？');
  }
  const data = {
    corpId: account.value.corpId,
    teamId: teamId.value,
    operatorId: doctorInfo.value.userid,
    mateId,
  }
  const res = await api('removeTeammate', data);
  if (res && res.success) {
    await toast('操作成功');
    getTeam();
  } else {
    toast(res?.message || '操作失败')
  }
}

useLoad(options => {
  teamId.value = options.teamId;
})

useShow(() => {
  getTeam()
});

</script>
<style>
.min-w-100 {
  min-width: 200rpx;
}

.avatar {
  width: 120rpx;
  height: 128rpx;
}

.edit-sub {
  width: 36rpx;
  height: 36rpx;
}

.edit-icon {
  width: 16rpx;
  height: 16rpx;
}


.line-clamp-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

</style>