<template>
  <full-page pageClass="bg-white">
    <view class="pt-40 p-15">
      <view class="text-base font-semibold text-dark">团队名称:</view>
      <view class="mt-12 p-10 border rounded-sm">
        <input v-model="team.name" class="w-full text-base" placeholder="请输入团队名称" />
      </view>
      <view class="mt-15 text-base font-semibold text-dark">团队名称:</view>
      <view class="mt-12 p-10 border rounded-sm">
        <textarea v-model="team.teamTroduce" class="w-full text-base leading-normal" placeholder-class="text-base"
          placeholder="请输入团队介绍" />
      </view>
    </view>
    <template #footer>
      <button-footer confirmText="保存" :showCancel="false" @confirm="save()" />
    </template>
  </full-page>
</template>
<script setup>
import { computed, ref } from "vue";
import { storeToRefs } from "pinia";
import { onLoad } from "@dcloudio/uni-app";
import useGuard from "@/hooks/useGuard.js";
import useAccountStore from "@/store/account.js";
import api from "@/utils/api.js";
import { toast } from "@/utils/widget";

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

const { useLoad } = useGuard();
const { doctorInfo, account } = storeToRefs(useAccountStore());
const team = ref({ name: '', teamTroduce: '' });

function save() {
  if (team.value.name.trim() === '') {
    return toast('请输入团队名称')
  }
  team.value.teamId ? updateTeam() : createTeam();
}

async function createTeam() {
  const data = {
    corpId: account.value.corpId,
    id: doctorInfo.value._id,
    userid: doctorInfo.value.userid,
    teamName: team.value.name,
    teamTroduce: team.value.teamTroduce
  }
  const res = await api('createOwnTeam', data);
  if (res && res.success) {
    await toast('保存成功');
    uni.navigateBack();
  } else {
    toast(res.message || '保存失败')
  }
}

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

async function updateTeam() {
  const data = {
    corpId: account.value.corpId,
    id: team.value._id,
    teamId: team.value.teamId,
    name: team.value.name,
    teamTroduce: team.value.teamTroduce
  }
  const res = await api('updateTeamInfo', data);
  if (res && res.success) {
    await toast('保存成功');
    uni.navigateBack();
  } else {
    toast(res.message || '保存失败')
  }
}

onLoad(opts => {
  if (opts.teamId) {
    team.value.teamId = opts.teamId;
  }
  uni.setNavigationBarTitle({ title: opts.teamId ? '修改团队信息' : '创建团队' })
})

useLoad(opts => {
  if (opts.teamId) {
    getTeamDetail();
  }
})

</script>
<style>
.pt-40 {
  padding-top: 80rpx;
}
</style>