<template>
  <view class="add-player-page">
    <!-- 表单 -->
    <view class="form-container">
      <view class="form-item" @click="showIdTypePicker = true">
        <view class="form-label">证件类型</view>
        <view class="form-value">
          <text :class="{ placeholder: !formData.idType }">{{ formData.idType || '身份证' }}</text>
          <text class="arrow">›</text>
        </view>
      </view>

      <view class="form-item">
        <view class="form-label">姓名</view>
        <view class="form-value">
          <input
            class="form-input"
            v-model="formData.name"
            placeholder="请输入姓名"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <view class="form-item">
        <view class="form-label">证件号码</view>
        <view class="form-value">
          <input
            class="form-input"
            v-model="formData.idCard"
            placeholder="请输入身份证号码"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <view class="form-item">
        <view class="form-label">队伍</view>
        <view class="form-value">
          <input
            class="form-input"
            v-model="formData.team"
            placeholder="请输入队伍名称"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <view class="form-item">
        <view class="form-label">所属单位</view>
        <view class="form-value">
          <input
            class="form-input"
            v-model="formData.organization"
            placeholder="请输入所属单位"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <view class="form-item">
        <view class="form-label">联系电话</view>
        <view class="form-value">
          <input
            class="form-input"
            v-model="formData.phone"
            type="number"
            placeholder="请输入联系电话"
            placeholder-class="placeholder"
          />
        </view>
      </view>
    </view>

    <!-- 错误提示 - 只在有具体错误时显示 -->
    <view class="error-hints" v-if="validationErrors.length > 0">
      <view class="error-item" v-for="(error, index) in validationErrors" :key="index">
        <text class="error-text">{{ error }}</text>
      </view>
    </view>

    <!-- 按钮 -->
    <view class="btn-wrapper">
      <view class="btn save-btn" :class="{ disabled: !isFormValid }" @click="handleSave">保存</view>
    </view>

    <!-- 证件类型选择器 -->
    <picker-view
      class="picker-view"
      v-if="showIdTypePicker"
      :value="[0]"
      @change="handleIdTypeChange"
      @cancel="showIdTypePicker = false"
    >
      <picker-view-column>
        <view class="picker-item">身份证</view>
      </picker-view-column>
    </picker-view>
  </view>
</template>

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

export default {
  data() {
    return {
      formData: {
        idType: '身份证',
        name: '',
        idCard: '',
        team: '',
        organization: '',
        phone: ''
      },
      competitionId: '',
      projectIds: [],
      validationErrors: [],
      showIdTypePicker: false
    };
  },
  onLoad(options) {
    if (options.competitionId) {
      this.competitionId = options.competitionId
    }
    if (options.projectIds) {
      this.projectIds = options.projectIds.split(',')
    }
  },
  computed: {
    isFormValid() {
      return (
        this.formData.name &&
        this.formData.idCard &&
        this.formData.team &&
        this.formData.organization &&
        this.formData.phone &&
        this.validateIdCard(this.formData.idCard) &&
        this.validatePhone(this.formData.phone)
      );
    }
  },
  watch: {
    'formData.idCard'(val) {
      this.updateValidationErrors();
    },
    'formData.phone'(val) {
      this.updateValidationErrors();
    }
  },
  methods: {
    validateIdCard(idCard) {
      if (!idCard) return false;
      if (!/^\d{17}[\dXx]$/.test(idCard)) return false;
      
      const year = parseInt(idCard.substring(6, 10))
      const month = parseInt(idCard.substring(10, 12))
      const day = parseInt(idCard.substring(12, 14))
      
      if (month < 1 || month > 12) return false;
      if (day < 1 || day > 31) return false;
      
      const currentYear = new Date().getFullYear()
      if (year < 1900 || year > currentYear) return false;
      
      const date = new Date(year, month - 1, day)
      if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
        return false;
      }
      
      return true;
    },
    validatePhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone);
    },
    updateValidationErrors() {
      this.validationErrors = [];
      
      if (this.formData.idCard && !this.validateIdCard(this.formData.idCard)) {
        this.validationErrors.push('身份证号码格式不正确');
      }
      
      if (this.formData.phone && !this.validatePhone(this.formData.phone)) {
        this.validationErrors.push('手机号格式不正确');
      }
    },
    handleIdTypeChange(e) {
      this.formData.idType = '身份证';
      this.showIdTypePicker = false;
    },
    extractInfoFromIdCard(idCard) {
      if (!idCard || idCard.length !== 18) {
        return { gender: null, age: null, birthDate: null }
      }

      const year = idCard.substring(6, 10)
      const month = idCard.substring(10, 12)
      const day = idCard.substring(12, 14)
      const birthDate = `${year}-${month}-${day}`

      const birthYear = parseInt(year)
      const currentYear = new Date().getFullYear()
      const age = currentYear - birthYear

      const genderCode = parseInt(idCard.substring(16, 17))
      const gender = genderCode % 2 === 1 ? 1 : 2

      return { gender, age, birthDate }
    },

    async handleSave() {
      if (!this.isFormValid) {
        uni.showToast({
          title: '请完善信息',
          icon: 'none'
        })
        return;
      }

      // Check login status
      const token = getToken()
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
        return;
      }

      try {
        const info = this.extractInfoFromIdCard(this.formData.idCard)

        const userInfo = getUserInfo()
        const submitData = {
          playerName: this.formData.name,
          idCard: this.formData.idCard,
          teamName: this.formData.team,
          organization: this.formData.organization,
          contactPhone: this.formData.phone,
          idCardType: 1,
          gender: info.gender,
          age: info.age,
          birthDate: info.birthDate,
          createUser: userInfo ? userInfo.userId : null
        }

        if (this.competitionId) {
          submitData.competitionId = this.competitionId
        }
        if (this.projectIds && this.projectIds.length > 0) {
          submitData.projectId = this.projectIds[0]
        }

        console.log('提交选手数据:', submitData)
        await athleteAPI.submitAthlete(submitData)

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

        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (err) {
        console.error('保存选手失败:', err)
        uni.showToast({
          title: err.message || '保存失败，请重试',
          icon: 'none'
        })
      }
    }
  }
};
</script>

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

.form-container {
  background-color: #fff;
  margin: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 35rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 180rpx;
  font-size: 30rpx;
  color: #333333;
}

.form-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form-input {
  flex: 1;
  font-size: 30rpx;
  color: #333333;
}

.placeholder {
  color: #cccccc;
}

.arrow {
  font-size: 40rpx;
  color: #cccccc;
  margin-left: 10rpx;
}

.error-hints {
  margin: 0 30rpx;
  padding: 20rpx;
  background-color: #fff3f3;
  border-radius: 8rpx;
}

.error-item {
  margin-bottom: 10rpx;
}

.error-item:last-child {
  margin-bottom: 0;
}

.error-text {
  font-size: 26rpx;
  color: #C93639;
}

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

.btn {
  width: 100%;
  text-align: center;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 30rpx;
  font-weight: bold;
}

.save-btn {
  background-color: #C93639;
  color: #fff;
}

.save-btn.disabled {
  background-color: rgba(201, 54, 57, 0.5);
}

.picker-view {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 500rpx;
  background-color: #fff;
  z-index: 9999;
}

.picker-item {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 30rpx;
}
</style>
