<template>
  <div class="group-tab">
    <div>
      <el-button v-if="isCreator" class="tabs-function-button"
                 plain type="primary" :disabled="isRuleExisted"
                 @click="ruleFormDialog=true">
        {{ isRuleExisted === null ? null : (isRuleExisted ? "已开放组队" : "开放组队") }}
      </el-button>
      <div v-else>
        <el-button v-if="!groupData" class="tabs-function-button"
                   :disabled="!isRuleExisted"
                   plain type="primary" @click="createGroupDialog=true">
          创建队伍
        </el-button>
          <div v-else>
              <el-button class="tabs-function-button"
                         plain type="primary" @click="addMemberDialog=true">
                  邀请成员
              </el-button>
              <el-button class="tabs-function-button"
                         plain type="primary" @click="deleteGroup=true">
                  解散团队
              </el-button>
          </div>

      </div>
    </div>
    <el-table v-if="isRuleExisted" :data="groupTableData" style="width: 100%">
      <el-table-column label="组名">
        <template #default="scope">
        <span
            :style="groupData && scope.row['groupVO'].id===groupData['groupVO'].id ? 'color: var(--el-color-primary)':''">
          {{ scope.row["groupVO"].name }}
        </span>
        </template>
      </el-table-column>
      <el-table-column label="组员">
        <template #default="scope">
          <div style="display:flex;">
            <div v-for="item of scope.row.members"
                 :key="'member'+item.id"
                 style="margin-right: 10px"
                 :style="groupData && scope.row['groupVO'].id===groupData['groupVO'].id ? 'color: var(--el-color-primary)':''">
              {{ item.username }}
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--小组规则-->
  <el-dialog v-model="ruleFormDialog" :before-close="beforeRuleFormClose" :title="ruleForm.dialogTitle">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="ruleFormRule" label-position="right" label-width="150px">
      <el-form-item label="小组最大人数" prop="maxSize">
        <el-input v-model="ruleForm.maxSize" type="number" min="1" max="5" placeholder="输入小组最大人数（1～5）" maxlength="1"
                  onkeypress='return( /[1-5]/.test(String.fromCharCode(event.keyCode)))'></el-input>
      </el-form-item>
      <el-form-item label="组名最大长度" prop="maxNameLen">
        <el-input v-model="ruleForm.maxNameLen" type="number" min="1" max="9" placeholder="输入组名最大长度(1~9)"
                  maxlength="1" onkeypress='return( /[1-9]/.test(String.fromCharCode(event.keyCode)))'></el-input>
      </el-form-item>
    </el-form>
    <div style="margin: auto;width: fit-content">
      <el-button plain type="primary" @click="handleCreateRuleConfirm">确认</el-button>
    </div>
  </el-dialog>
  <!--组队信息-->
  <el-dialog v-model="createGroupDialog" :before-close="beforeGroupFormClose" :title="createGroupForm.dialogTitle">
    <el-form ref="createGroupFormRef" :model="createGroupForm" label-position="right">
      <el-form-item label="组名" prop="name">
        <el-input v-model="createGroupForm.name" placeholder="输入组名"></el-input>
      </el-form-item>
    </el-form>
    <div style="margin: auto;width: fit-content">
      <el-button plain type="primary" @click="handleCreateGroupConfirm">确认</el-button>
    </div>
  </el-dialog>
  <!-- 添加组员-->
  <el-dialog v-model="addMemberDialog" :before-close="beforeGroupMemberFormClose" :title="addMemberForm.dialogTitle">
    <el-form ref="addMemberFormRef" :model="addMemberForm" :rules="addMemberRule" label-position="right">
      <el-form-item label="组员手机号" prop="phone">
        <el-input ref="phone" v-model="addMemberForm.phone" placeholder="输入组员手机号"></el-input>
      </el-form-item>
    </el-form>
    <div style="margin: auto;width: fit-content">
      <el-button plain type="primary" @click="handleAddMemberConfirm">确认</el-button>
    </div>
  </el-dialog>

    <el-dialog v-model="deleteGroup">
        <div style="margin: 10px;position: relative;left: 280px">确定要解散团队吗？</div>
        <el-button type="primary" style="margin: 10px;position: relative;left: 220px" @click="deleteUserGroup">确认</el-button>
        <el-button style="margin: 10px;position: relative;left: 300px" @click="beforeDeleteGroup">取消</el-button>
    </el-dialog>
</template>

<script>
import {ElMessage} from "element-plus";

export default {
  name: "GroupTab",
  props: {
    courseId: {
      required: true,
    },
    teacherId: {
      required: true,
    },
  },
  data() {
    return {
      groupTableData: [],
      groupData: null,
      deleteGroup:false,
      isRuleExisted: false,
      ruleFormDialog: false,
      maxNameLen:10,
      ruleForm: {
        dialogTitle: "制定组队规则",
        courseVO: null,
        id: null,
        maxSize: null,
        maxNameLen: null,
      },
      ruleFormRule: {
        maxSize: {
          required: true, message: "请选择小组最大成员人数", trigger: "change",
        },
        maxNameLen: {
          required: true, message: "请选择组名最大长度", trigger: "change",
        }
      },
      addMemberRule: {
        phone: [{required: true, message: "手机号不能为空"},
          {
            type: "number",
            message: "手机号格式不正确",
            trigger: "blur",
            transform(value) {
              var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/;
              if (!phonereg.test(value)) {
                return false;
              } else {
                return Number(value);
              }
            }
          }],
      },

      createGroupDialog: false,
      createGroupForm: {
        dialogTitle: "队伍信息",
        courseId: null,
        name: null,
      },

      addMemberDialog: false,
      addMemberForm: {
        dialogTitle: "组员信息",
        phone: null,
      },
    };
  },
  computed: {
    isCreator() {
      return Number(this.teacherId) === Number(this.$store.state.user.id);
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      const _this = this;
      _this.groupTableData = []; // init前置空
      const ruleRes = (await _this.$apis.findGroupRule(_this.courseId)).data;
      _this.isRuleExisted = !ruleRes.code;
      if (_this.isRuleExisted) {
        _this.maxNameLen=ruleRes.data.maxNameLen;
        const groupsRes = (await _this.$apis.findAllGroupsByCourse(_this.courseId)).data;
        if (!groupsRes.code) {
          _this.groupTableData = groupsRes.data;
        }
        const groupRes = (await _this.$apis.findGroup(_this.courseId)).data;
        if (!groupRes.code) {
          _this.groupData = groupRes.data;
        }
      }
    },

    beforeRuleFormClose() {
      const _this = this;
      _this.ruleFormDialog = false;
      _this.$refs.ruleFormRef.resetFields();
    },

    handleCreateRuleConfirm() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          let RuleVO = {
            courseVO: {id: this.courseId},
            maxSize: this.ruleForm.maxSize,
            maxNameLen: this.ruleForm.maxNameLen,
          };
          this.$apis.createGroupRule(RuleVO)
              .then(res => {
                if (res.data.code) {
                  ElMessage.error(res.data.message);
                } else {
                  this.isRuleExisted = true;
                  this.ruleFormDialog = false;
                  this.$refs.ruleFormRef.resetFields();
                  ElMessage.success("创建规则成功");
                }
              });
        }
      });
    },

    beforeDeleteGroup(){
        this.deleteGroup=false;
    },

    deleteUserGroup(){
       this.$apis.deleteGroup(this.$store.state.user.id,this.courseId).then(res=>{
           console.log(res);
           this.$router.go(0);
       });
       this.beforeDeleteGroup();
    } ,
    beforeGroupFormClose() {
      this.createGroupDialog = false;
      this.$refs.createGroupFormRef.resetFields();
    },

    handleCreateGroupConfirm() {
      if (this.createGroupForm.name.length===0){
        return ;
      }
      if (this.createGroupForm.name.length>this.maxNameLen){
        this.createGroupForm.name="";
        ElMessage.error("创建队伍失败！队伍名称长度不能超过"+this.maxNameLen+"!");
      }
      this.$refs.createGroupFormRef.validate((valid) => {
        if (valid) {
          let GroupVO = {
            courseId: this.courseId,
            name: this.createGroupForm.name,
          };
          this.$apis.createGroup(GroupVO)
              .then(res => {
                if (res.data.code) {
                  ElMessage.error(res.data.message);
                } else {
                  this.groupData = res.data.data;
                  this.groupTableData.push(res.data.data);
                  this.createGroupDialog = false;
                  this.$refs.createGroupFormRef.resetFields();
                  ElMessage.success("创建队伍成功");
                }
              });
        }
      });
    },

    beforeGroupMemberFormClose() {
      this.addMemberDialog = false;
      this.$refs.addMemberFormRef.resetFields();
    },

    handleAddMemberConfirm() {
      const _this = this;
      this.$refs.addMemberFormRef.validate(async (valid) => {
        if (valid) {
          const userIdRes = (await _this.$apis.findUserIdByPhone(_this.addMemberForm.phone)).data;
          if (userIdRes.code) {
            ElMessage.error(userIdRes.message);
            return;
          }
          let groupMemberVO = {
            userId: userIdRes.data,
            groupId: _this.groupData["groupVO"].id,
            courseId: _this.courseId,
          };
          this.$apis.sendInvitation(groupMemberVO)
              .then(res => {
                if (res.data.code) {
                  ElMessage.error(res.data.message);
                } else {
                  ElMessage.success("已发送邀请，请等候其同意。");
                }
              });
        }
      });
    this.addMemberDialog=false;
    },

  },
};
</script>

<style scoped>
@import "tabs.css";
</style>