<template>
  <view class="add-team-page">
    <view class="form-section">
      <view class="form-item">
        <view class="form-label required">集体名称</view>
        <input
          class="form-input"
          type="text"
          v-model="formData.name"
          placeholder="请输入集体名称"
        />
      </view>

      <view class="form-item">
        <view class="form-label">备注</view>
        <textarea
          class="form-textarea"
          v-model="formData.remark"
          placeholder="请输入备注信息"
        ></textarea>
      </view>
    </view>

    <!-- 成员列表 -->
    <view class="member-section">
      <view class="section-header">
        <text class="section-title">成员列表</text>
        <view class="add-member-btn" @click="showMemberPicker = true">
          <text>+ 添加成员</text>
        </view>
      </view>

      <view class="member-list" v-if="formData.members.length > 0">
        <view class="member-item" v-for="(member, index) in formData.members" :key="index">
          <view class="member-info">
            <text class="member-name">{{ member.name }}</text>
          </view>
          <view class="remove-btn" @click="removeMember(index)">移除</view>
        </view>
      </view>

      <view class="empty-members" v-else>
        <text>暂无成员，请添加</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn-wrapper">
      <view class="submit-btn" @click="handleSubmit">保存</view>
    </view>

    <!-- 成员选择弹窗 -->
    <view class="member-picker-mask" v-if="showMemberPicker" @click="showMemberPicker = false">
      <view class="member-picker" @click.stop>
        <view class="picker-header">
          <text class="picker-title">选择成员</text>
          <text class="picker-close" @click="showMemberPicker = false">×</text>
        </view>
        <view class="picker-list">
          <view
            class="picker-item"
            v-for="(player, index) in availablePlayers"
            :key="index"
            @click="addMember(player)"
          >
            <text>{{ player.name }}</text>
            <text class="add-icon">+</text>
          </view>
          <view class="empty-picker" v-if="availablePlayers.length === 0">
            <text>暂无可选成员</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import athleteAPI from '@/api/athlete.js';
import { getUserInfo } from '@/utils/auth.js';

export default {
  data() {
    return {
      formData: {
        name: '',
        remark: '',
        members: []
      },
      playerList: [],
      showMemberPicker: false
    };
  },
  computed: {
    availablePlayers() {
      const memberIds = this.formData.members.map(m => m.id)
      return this.playerList.filter(p => !memberIds.includes(p.id))
    }
  },
  onLoad() {
    this.loadPlayerList()
  },
  methods: {
    async loadPlayerList() {
      try {
        const userInfo = getUserInfo()
        if (!userInfo || !userInfo.userId) return

        const res = await athleteAPI.getAthleteList({
          current: 1,
          size: 100,
          createUser: userInfo.userId
        })

        let list = []
        if (res.records) {
          list = res.records
        } else if (Array.isArray(res)) {
          list = res
        }

        this.playerList = list.map(item => ({
          id: item.id,
          name: item.name || item.playerName
        }))
      } catch (err) {
        console.error('加载选手列表失败:', err)
      }
    },

    addMember(player) {
      this.formData.members.push({
        id: player.id,
        name: player.name
      })
      this.showMemberPicker = false
    },

    removeMember(index) {
      this.formData.members.splice(index, 1)
    },

    async handleSubmit() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入集体名称',
          icon: 'none'
        })
        return
      }

      if (this.formData.members.length === 0) {
        uni.showToast({
          title: '请添加至少一名成员',
          icon: 'none'
        })
        return
      }

      try {
        const userInfo = getUserInfo()
        
        const data = {
          teamName: this.formData.name,
          remark: this.formData.remark,
          memberIds: this.formData.members.map(m => m.id),
          createUser: userInfo?.userId
        }

        if (athleteAPI.saveTeam) {
          await athleteAPI.saveTeam(data)
        }

        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })

        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (err) {
        console.error('保存失败:', err)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.add-team-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 150rpx;
}

.form-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.form-label.required::before {
  content: '*';
  color: #C93639;
  margin-right: 5rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
}

.member-section {
  background-color: #fff;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.add-member-btn {
  color: #C93639;
  font-size: 28rpx;
}

.member-list {
  margin-top: 20rpx;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
}

.member-name {
  font-size: 28rpx;
  color: #333;
}

.remove-btn {
  color: #C93639;
  font-size: 26rpx;
}

.empty-members {
  text-align: center;
  padding: 50rpx;
  color: #999;
  font-size: 28rpx;
}

.submit-btn-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background-color: #fff;
}

.submit-btn {
  background-color: #C93639;
  color: #fff;
  text-align: center;
  padding: 30rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.member-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.member-picker {
  width: 100%;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 70vh;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
}

.picker-close {
  font-size: 40rpx;
  color: #999;
}

.picker-list {
  max-height: 60vh;
  overflow-y: auto;
}

.picker-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.add-icon {
  color: #C93639;
  font-size: 36rpx;
}

.empty-picker {
  text-align: center;
  padding: 50rpx;
  color: #999;
}
</style>
