<template>
  <div class="team-info-title"> 队伍信息 </div>
  <el-form :model="formData" ref="ruleFormRef" :rules="rules" label-position="top">
    <el-form-item prop="memberCount" label="队伍人数">
      <el-input v-model="formData.memberCount" type="number" width="200" />
    </el-form-item>
    <el-form-item prop="description" label="队伍职责">
      <el-input v-model="formData.description" type="textarea" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import { FormInstance, FormRules, ElMessage } from 'element-plus';
  import { TeamInfoType } from '../../type';
  import useTeamStore from '../../store/userTeam';

  const { teamAndPersonInfo } = storeToRefs(useTeamStore());
  const { setTeamInfo } = useTeamStore();

  const formData = ref<TeamInfoType>({
    memberCount: 0,
    description: '',
  });
  const ruleFormRef = ref<FormInstance>();
  const rules = ref<FormRules<TeamInfoType>>({
    memberCount: [{ required: true, message: '请输入人数', trigger: 'blur' }],
    description: [{ required: true, message: '请输入职责', trigger: 'blur' }],
  });

  async function submitForm() {
    await ruleFormRef.value!.validate(async (valid) => {
      if (valid) {
        const data = {
          id: teamAndPersonInfo.value!.teamId,
          memberCount: formData.value.memberCount,
          description: formData.value.description,
        };
        await setTeamInfo(data);
        ElMessage({
          message: '保存成功',
          type: 'success',
        });
      }
    });
  }

  watch(
    () => teamAndPersonInfo.value,
    () => {
      formData.value.memberCount = teamAndPersonInfo.value?.memberCount || 0;
      formData.value.description = teamAndPersonInfo.value?.description || '';
    },
  );
</script>

<style scoped lang="scss">
  .team-info-title {
    margin-bottom: 16px;
  }
  // 去掉el input右侧的小箭头
  :deep(input::-webkit-outer-spin-button),
  :deep(input::-webkit-inner-spin-button) {
    -webkit-appearance: none;
  }
</style>
