<template>
  <view class="flex flex-col justify-center h-full bg-white">
    <view v-if="list.length === 0" class="w-full">
      <empty-data text="暂无团队" />
      <view class="mt-10 mx-auto w-100 text-base text-primary border-auto leading-normal py-5 text-center rounded">
        创建团队
      </view>
    </view>
    <view v-else>
      <view class="flex items-center">
        <view class="flex-shrink-0 p-15 flex items-center" :class="list.length > 1 ? '' : 'opacity-0'"
          @click="toggle(-1)">
          <uni-icons type="left" size="32" :color="indicator.prev ? '#0074ff' : '#999'"></uni-icons>
        </view>
        <view class="w-0 flex-grow text-white overflow-hidden">
          <view v-if="list.length > 1" class="py-5 text-center text-lg font-semibold text-dark">
            ({{ current + 1 }} / {{ list.length }})
          </view>
          <swiper class="swiper" :current="current">
            <swiper-item v-for="(i, idx) in list" :key="i.teamId">
              <view class="flex items-center justify-center h-30 mb-10">
                <view class="mr-5 text-dark text-lg font-semibold truncate">{{ i.name }}</view>
                <view class="edit-sub flex-shrink-0 flex items-center justify-center rounded-full bg-primary"
                  @click="visible = true">
                  <image class="edit-icon" src="/static/work/pen.svg" mode="aspectFill" />
                </view>
              </view>
              <view v-if="i.qrcode" class="flex justify-center overflow-hidden">
                <uqrcode ref="qrcodes" :canvasId="`qrcode-${idx}`" :value="i.qrcode" :options="options">
                </uqrcode>
              </view>
            </swiper-item>
          </swiper>
        </view>
        <view class="flex-shrink-0 p-15 flex items-center" :class="list.length > 1 ? '' : 'opacity-0'"
          @click="toggle(1)">
          <uni-icons type="right" size="32" :color="indicator.next ? '#0074ff' : '#999'"></uni-icons>
        </view>
      </view>
      <view class="mt-10 px-15 text-base text-gray leading-normal text-center">
        微信扫一扫上面的二维码
      </view>
      <view class="px-15 text-base text-gray leading-normal text-center">进入团队首页，即可发起线上咨询、建档授权等服务</view>
      <view class="mt-10 flex px-15 leading-normal text-center">
        <button class="mr-10 border-auto rounded py-5 text-base text-primary flex-grow" @click="saveImage('save')">
          保存图片
        </button>
        <button class="bg-primary rounded py-5 text-base text-white flex-grow" @click="saveImage('share')">分享微信</button>
      </view>
    </view>
    <view class="canvas-box">
      <l-painter ref="painterRef" :board="poster" />
    </view>
  </view>
  <rename-popup :team="team" :visible="visible" @close="visible = false" @change="change" />
</template>
<script setup>
import { computed, ref } from "vue";
import { storeToRefs } from "pinia";
import dayjs from "dayjs";
import { onLoad } from "@dcloudio/uni-app";
import useAccountStore from "@/store/account.js";
import useGuard from '@/hooks/useGuard';
import api from "@/utils/api.js";
import { toast, shareToWeChat } from "@/utils/widget";
import { getInvitePatientPoster } from './base-poster-data';

import emptyData from "@/components/empty-data.vue";
import renamePopup from "./rename-popup.vue";

const env = __VITE_ENV__;
const inviteQrcode = env.MP_INVITE_PATIENT_QRCODE;

const options = { margin: 10 }
const painterRef = ref()
const poster = ref({})

const { useShow } = useGuard();
const { doctorInfo, account } = storeToRefs(useAccountStore());
const current = ref(0);
const list = ref([]);
const visible = ref(false);
const teamId = ref('')
const indicator = computed(() => ({
  prev: current.value > 0,
  next: current.value < list.value.length - 1
}))
const team = computed(() => list.value[current.value] || null);

function toggle(val) {
  const num = current.value + val;
  if (num > 0) {
    current.value = Math.min(num, list.value.length - 1);
  } else {
    current.value = Math.max(num, 0);
  }
}

async function getTeams() {
  const res = await api('getJoinedTeams', { corpId: account.value?.corpId, mateId: doctorInfo.value?.userid });
  const arr = res && Array.isArray(res.data) ? res.data.map(i => ({
    id: i._id,
    teamId: i.teamId,
    name: i.name,
    qrcode: `${inviteQrcode}?teamId=${i.teamId}&corpId=${i.corpId}`
    // qrcode: i.qrcodes && i.qrcodes[0] && i.qrcodes[0].qrcode ? i.qrcodes[0].qrcode : ''

  })) : [];
  if (teamId.value) {
    const idx = arr.findIndex(i => i.teamId === teamId.value);
    if (idx > -1) {
      current.value = idx
    }
    teamId.value = '';
  }
  list.value = arr;
}

async function change(name) {
  const res = await api('updateTeamInfo', { teamId: team.value.teamId, name, corpId: account.value.corpId, id: team.value.id });
  if (res && res.success) {
    await toast('保存成功');
    list.value[current.value].name = name;
    visible.value = false
  } else {
    toast('保存失败');
  }
}

// 保存二维码图片
/**
 * 
 * @param action  save | share 
 */
async function saveImage(action = 'save') {
  const team = list.value[current.value] || null;
  if (!team) return;
  const data = getInvitePatientPoster(team.name, team.qrcode)
  try {
    await painterRef.value.render(data);
    painterRef.value.canvasToTempFilePathSync({
      fileType: "jpg",
      // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
      pathType: 'url',
      quality: 1,
      success: (res) => {
        console.log(res.tempFilePath);
        if (action === 'save') {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function () {
              console.log('save success');
            }
          });
        } else if (action === 'share') {
          wx.showShareImageMenu({
            path: res.tempFilePath,
            needShowEntrance: false
          })
        }
      },
    });
  } catch (e) {
    toast(e?.message)
  }
}

onLoad(opts => {
  teamId.value = opts.teamId || '';
})

useShow(() => {
  getTeams()
})

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

.opacity-0 {
  opacity: 0;
}

.swiper {
  height: 500rpx;
}

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

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

.h-30 {
  height: 60rpx;
}

.share-btn {
  border: none;
  padding: 0;
  line-height: normal;
  background: transparent;
}

.share-btn::after {
  border: none;
}

.canvas-box {
  top: 10000rpx;
  position: absolute;
  z-index: -1;
  width: 0;
  height: 0;
  overflow: hidden;
}
</style>