<template>
  <!-- 报名人员 -->
  <div class="page-content" style="padding: 24px">
    <div class="tool">
      <ul class="filter">
        <li>
          <label>搜索：</label>
          <el-input
            :placeholder="'请输入姓名、手机号、' + (info.completeCompetitionSetup.competitionType ? '团队名称、' : '') + '学号、学校'"
            prefix-icon="el-icon-search" v-model="keyword" clearable size="mini" style="width: 350px"></el-input>
        </li>
        <li v-if="info.releaseType">
          <label>参赛人员状态：</label>
          <el-select v-model="isDisable" @change="initData">
            <el-option v-for="(item, i) in statusList" :key="i" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </li>
      </ul>
      <div>
        <el-button type="primary" round :loading="exporting" @click="exportAll">批量导出</el-button>
        <el-button type="primary" @click="batchDel" round>批量删除</el-button>
      </div>
    </div>

    <el-table ref="table" :data="listData" class="table" stripe header-align="center"
      @selection-change="handleSelectionChange" row-key="id" v-loading="loading" @sort-change="sortChange">
      <el-table-column type="selection" width="80" align="center" :reserve-selection="true"></el-table-column>
      <el-table-column type="index" width="60" label="序号" align="center">
        <template slot-scope="scope">
          {{ scope.$index + (page - 1) * pageSize + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="school" label="学生账号归属" sortable="custom" min-width="180" align="center"></el-table-column>
      <el-table-column prop="realSchool" label="学生所在院校" min-width="180" align="center"></el-table-column>
      <el-table-column v-if="info.completeCompetitionSetup.competitionType" prop="teamName" label="团队名称"
        sortable="custom" min-width="140" align="center">
      </el-table-column>
      <el-table-column prop="username" label="队长" min-width="140" align="center">
      </el-table-column>
      <el-table-column prop="workNumber" label="队长学号" min-width="140" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="队长手机号" min-width="140" align="center">
      </el-table-column>
      <el-table-column prop="captain" label="是否为队长" min-width="90" align="center"></el-table-column>
      <el-table-column prop="teachers" label="指导老师" min-width="200" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <template v-if="scope.row.teachers">
            <el-tooltip placement="top">
              <div slot="content" style="line-height: 1.8">
                <div v-for="(item, i) in scope.row.teachers" :key="i">
                  {{ item.name }}{{ item.phone ? '，' + item.phone : '' }}{{ item.position ? '，' + item.position : '' }}
                </div>
              </div>
              <p>{{ scope.row.teachers[0].name }}{{ scope.row.teachers[0].phone ? '，' + scope.row.teachers[0].phone : ''
                }}{{ scope.row.teachers[0].position ? '，' + scope.row.teachers[0].position : '' }}</p>
            </el-tooltip>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="captain" label="团队状态" min-width="80" align="center">
        <template slot-scope="scope">
          <el-link type="danger" style="font-size: 16px" @click="toInfo(scope.row)">异常</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="270">
        <template slot-scope="scope">
          <el-button type="text" @click="edit(scope.row)">编辑</el-button>
          <el-button type="text" @click="del(scope.row)">删除</el-button>
          <template v-if="info.releaseType">
            <el-button type="text" @click="toInfo(scope.row)">参赛信息与成绩</el-button>
            <el-switch v-model="scope.row.isDisable" :active-text="scope.row.isDisable ? '禁用' : '启用'" :active-value="0"
              :inactive-value="1" style="margin: 0 10px 0 5px"
              @change="switchOff($event, scope.row, scope.$index)"></el-switch>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange"
        :current-page="page">
      </el-pagination>
    </div>

    <el-dialog :title="(!isAdd ? '编辑' : '新增') + '参赛人员'" :visible.sync="addVisible" width="440px" class="dialog"
      :close-on-click-modal="false" @close="closeAdd">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" style='margin-right: 10px;'>
        <el-form-item v-if="!schoolDisable" prop="schoolId" label="学生账号归属">
          <el-select v-model="form.schoolId" filterable :disabled="!isAdd" @change="schoolChange" style="width: 100%">
            <el-option v-for="(item, i) in clients" :key="i" :label="item.schoolName"
              :value="item.schoolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="studentAffiliatedInstitutionId" label="学生所在院校">
          <el-select v-model="form.studentAffiliatedInstitutionId" filterable style="width: 100%">
            <el-option v-for="(item, i) in schools" :key="i" :label="item.schoolName"
              :value="item.schoolId"></el-option>
          </el-select>
          <p style="margin-top: 10px;line-height: 1.4;font-size: 12px;">学生所属院校为学生实际院校</p>
        </el-form-item>
        <el-form-item prop="workNumber" label="学生学号">
          <el-input v-model="form.workNumber" placeholder="请输入学生学号" @change="workNumberChange"></el-input>
        </el-form-item>
        <el-form-item prop="userName" label="学生姓名">
          <el-input v-model="form.userName" placeholder="请输入学生姓名" :disabled="isAdd"></el-input>
        </el-form-item>
        <el-form-item label="账号角色">
          学生
        </el-form-item>
        <el-form-item v-if="info.completeCompetitionSetup.competitionType" prop="teamId" label="所属团队">
          <div style="display: flex;align-items: center">
            <el-select v-model="form.teamId" :disabled="formEnable && isAdd" filterable
              style="width: 240px;margin-right: 10px">
              <el-option v-for="(item, i) in teams" :key="i" :label="item.teamName" :value="item.teamId"></el-option>
            </el-select>
            <el-button v-if="isAdd && !formEnable" type="text" @click="createTeam">创建团队</el-button>
          </div>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="form.phone" maxlength="11" placeholder="请输入手机号" :disabled="isAdd"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱" :disabled="isAdd"></el-input>
        </el-form-item>
      </el-form>
      <p v-if="!isAdd" class="tips" style="margin-left: 13px">当前页面信息修改会同步修改掉学生账号信息</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="创建团队" :visible.sync="teamVisible" :close-on-click-modal="false" width="300px">
      <el-form class="dia-form">
        <el-form-item>
          <el-input placeholder="请输入团队名称" maxlength="10" v-model="teamForm.teamName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请设置团队邀请码" maxlength="6" v-model="teamForm.invitationCode"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="teamSubmit">确定并使用</el-button>
        <el-button size="small" @click="teamVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import util from "@/libs/util";
import axios from 'axios'
import Setting from "@/setting";
export default {
  data () {
    return {
      token: util.local.get(Setting.tokenKey),
      id: +this.$route.query.id,
      info: {
        completeCompetitionSetup: {}
      },
      isDisable: this.$route.query.isDisable ? +this.$route.query.isDisable : '',
      statusList: [
        {
          id: '',
          name: '不限'
        },
        {
          id: 1,
          name: '已禁用'
        },
        {
          id: 0,
          name: '未禁用'
        }
      ],
      keyword: this.$route.query.keyword || '',
      listData: [],
      multipleSelection: [],
      page: +this.$route.query.page || 1,
      pageSize: 10,
      total: 0,
      schoolOrder: '',
      teamOrder: '',
      clients: [],
      schools: [],
      addVisible: false,
      formEnable: true,
      isAdd: false,
      form: {
        captain: 0,
        competitionId: this.$route.query.id,
        userName: '',
        workNumber: '',
        schoolId: '',
        studentAffiliatedInstitutionId: '',
        teamId: '',
        whetherSignUp: 0,
        phone: '',
        email: '',
        identification: 1,
        uniqueIdentification: Date.now(),
        password: Setting.initialPassword
      },
      rules: {
        schoolId: [
          { required: true, message: "请选择所属院校", trigger: "change" }
        ],
        workNumber: [
          { required: true, message: "请输入学号", trigger: "blur" }
        ],
        teamId: [
          { required: true, message: "请选择所属团队", trigger: "change" }
        ]
      },
      submiting: false,

      teamVisible: false,
      teams: [],
      teamNameRepeat: false,
      teamForm: {
        competitionId: this.$route.query.id,
        registrationInvitationCode: '',
        teamName: '',
        invitationCode: '',
        whetherSignUp: 1,
        identification: 1
      },
      originForm: {},
      exitMember: 0,
      notExit: 0,
      schoolDisable: false,

      importVisible: false,
      uploadList: [],
      uploadFaild: false,
      uploadTips: '',
      exportCode: '',
      headers: {
        token: util.local.get(Setting.tokenKey)
      },
      uploading: false,
      isBackstage: 0,
      exporting: false,
      loading: false,
    };
  },
  watch: {
    keyword: function (val) {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.initData();
      }, 500);
    }
  },
  mounted () {
    this.getData()
    this.getInfo()
    this.getTeam()
  },
  methods: {
    init () {
      this.initData()
      this.getTeam()
      this.getClient()
    },
    async getData () {
      this.loading = true
      const { data } = await this.$post(this.api.queryAbnormalTeam, {
        pageNum: this.page,
        pageSize: this.pageSize,
        competitionId: this.id,
        keyWord: this.keyword,
        isDisable: this.isDisable,
        schoolOrder: this.schoolOrder,
        teamOrder: this.teamOrder,
      })
      const list = data.records;
      list.map(e => {
        if (e.teacherDetails) {
          e.teachers = JSON.parse(e.teacherDetails)
        }
      })
      this.listData = list
      this.total = data.total;
      this.$refs.table.clearSelection();
      this.loading = false
    },
    // 获取赛事信息
    getInfo () {
      this.$post(`${this.api.getCompetition}?competitionId=${this.id}`).then(({ competition }) => {
        this.info = competition
        this.getSchool()
        // 非本校内则查询接口获取学校列表
        if (competition.competitionScope) {
          this.getClient()
        } else {
          this.schoolDisable = true
          this.form.schoolId = competition.schoolId
        }
      }).catch(err => { })
    },
    initData () {
      this.page = 1
      this.getData()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    handleCurrentChange (val) {
      this.page = val;
      this.getData();
    },
    switchOff (val, row, index) {
      this.$put(`${this.api.disableRegistration}?competitionRegistrationId=${row.id}&isDisable=${val}`).then(res => { }).catch(err => { });
    },
    // 排序回调
    sortChange (column) {
      // 1上2下
      if (column.prop === 'school') this.schoolOrder = column.order ? column.order === 'ascending' ? 2 : 1 : ''
      if (column.prop === 'teamName') this.teamOrder = column.order ? column.order === 'ascending' ? 2 : 1 : ''
      this.getData()
    },
    // 编辑
    edit (row) {
      this.notExit = 0
      this.isAdd = false
      this.addVisible = true
      row.userName = row.username
      this.exitMember = 0
      row.id = row.accountId
      this.originForm = JSON.parse(JSON.stringify(row))
      this.form = JSON.parse(JSON.stringify(row))
    },
    del (row) {
      this.$confirm(!this.info.completeCompetitionSetup.competitionType || row.captain === '否' ? '删除后该参赛人员已有的成绩会一并删除，成绩排名将会受影响，是否确定要删除？' : '删除队长后，该团队下所有成员都会同步移除报名，已有的成绩也会一并删除，成绩排名将会受影响，是否确认删除？', "提示", {
        type: "warning"
      }).then(() => {
        this.$post(this.api.batchDeleteApplicants, { registrationVOS: [row] }).then(res => {
          util.successMsg("删除成功");
          this.init()
        }).catch(res => { });
      }).catch(() => { });
    },
    // 学校选择回调
    schoolChange () {
      if (!this.form.studentAffiliatedInstitutionId) this.form.studentAffiliatedInstitutionId = this.form.schoolId
    },
    // 学号输入完回调。学校和学号都输入完后，调这个接口查询是否有存在的学生，如果有，才能继续输入，如果不能，不让添加
    workNumberChange () {
      const { form } = this
      if (this.originForm.workNumber !== form.workNumber) {
        form.schoolId && form.workNumber && this.$get(`${this.api.enquireAboutSchoolStudents}?schoolId=${form.schoolId}&workNumber=${form.workNumber}${this.isAdd ? '' : '&applyFor=1'}`).then(({ account }) => {
          this.notExit = 0
          this.exitMember = 0
          if (account) {
            const { studentAffiliatedInstitutionId } = form
            account.studentAffiliatedInstitutionId = studentAffiliatedInstitutionId
            this.form = account
          }
          this.formEnable = !account
        }).catch(res => {
          if (res.message === '学生不存在') this.notExit = 1
          if (!this.isAdd) this.exitMember = 1
        })
      } else {
        this.exitMember = 0
      }
    },
    // 新增编辑人员
    submitForm () {
      const { form } = this
      if (!this.isAdd) { // 编辑
        this.$post(this.api.updateUser, {
          hrUserAccount: {
            ...form,
            id: form.id,
            lastTimeInstitutionId: this.originForm.studentAffiliatedInstitutionId
          },
          hrUserInfo: {
            userId: form.userId,
            schoolId: form.schoolId,
            email: form.email,
            userName: form.userName
          }
        }).then(res => {
          // 团队有更换，则调加入团队的接口
          if (this.originForm.teamId !== form.teamId) {
            this.$post(this.api.joinCompetitionTeam, {
              schoolId: form.schoolId,
              studentAffiliatedInstitutionId: form.studentAffiliatedInstitutionId,
              accountId: form.id,
              competitionId: this.id,
              teamId: form.teamId,
              identification: 1,
              whetherSignUp: 1
            }).then(res => {
              this.addVisible = false
              this.init()
              this.submiting = false
              util.successMsg('编辑成功！')
            }).catch(res => {
              this.submiting = false
            })
          } else {
            this.addVisible = false
            this.init()
            this.submiting = false
            util.successMsg('编辑成功！')
          }
        }).catch(res => {
          this.submiting = false
        })
      } else {
        // 新增人员后再调加入团队的接口
        this.$post(this.api[this.info.completeCompetitionSetup.competitionType ? 'joinCompetitionTeam' : 'addCompetitionRegistration'], {
          schoolId: form.schoolId,
          studentAffiliatedInstitutionId: form.studentAffiliatedInstitutionId,
          accountId: form.id,
          competitionId: this.id,
          teamId: this.form.teamId,
          identification: 1,
          whetherSignUp: 1
        }).then(res => {
          this.addVisible = false
          this.init()
          this.submiting = false
          util.successMsg('报名成功！')
        }).catch(res => {
          this.submiting = false
        })
      }
    },
    // 新增人员
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.submiting) return false
          const { form } = this
          const team = this.teams.find(e => e.teamId == form.teamId)
          if (team && team.invitationCode) form.invitationCode = team.invitationCode
          // 平台id-端id-schoolId-workNumber组成账号
          form.account = `${Setting.platformId}-3-${form.schoolId}-${form.workNumber}`
          const { phone, email } = form
          if (phone && !/^1[3456789]\d{9}$/.test(phone)) {
            return util.errorMsg("请输入正确的手机号")
          } else if (email && !/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(email)) {
            return util.errorMsg("请输入正确的邮箱")
          } else if (this.notExit) {
            return util.errorMsg('学生不存在，无法添加！')
          } else if (this.exitMember) {
            return util.errorMsg('学生已存在')
          } else {
            this.submiting = true
            this.submitForm()
          }
        }
      })
    },
    // 关闭新增员工对话框
    closeAdd () {
      this.form = {
        captain: 0,
        competitionId: this.id,
        userName: '',
        workNumber: '',
        schoolId: '',
        teamId: '',
        whetherSignUp: 0,
        phone: '',
        email: '',
        identification: 1,
        uniqueIdentification: Date.now(),
        password: Setting.initialPassword
      }
    },
    // 创建团队
    createTeam () {
      this.teamForm = {
        competitionId: this.id,
        registrationInvitationCode: '',
        teamName: '',
        invitationCode: '',
        whetherSignUp: 1,
        identification: 1
      }
      this.teamVisible = true
    },
    // 学生所属院校固定查询所有学校
    async getSchool () {
      const { list } = await this.$get(this.api.querySchoolData)
      this.schools = list
    },
    // 获取客户
    async getClient () {
      if (this.info.competitionScope === 2) {
        // 选择了指定范围则查询该赛事指定范围的学校
        this.$get(`${this.api.schoolsInCompetitionArea}?competitionId=${this.id}`).then(({ schools }) => {
          this.clients = schools
        }).catch(res => { })
      } else {
        // 选了全平台则查询客户列表
        this.$post(this.api.queryCustomer, {
          customerType: '',
          page: 1,
          size: 10000,
          supplierId: ''
        }).then(res => {
          const { list } = res.message
          list.map(e => {
            e.schoolName = e.customerName
          })
          this.clients = list
        }).catch(res => { })
      }
    },
    // 获取团队列表
    getTeam () {
      this.$get(this.api.searchTeam, {
        teamName: '',
        competitionId: this.id
      }).then(({ teamList }) => {
        this.teams = teamList
      }).catch(res => { })
    },
    // 团队提交
    teamSubmit () {
      const form = this.teamForm
      if (!form.teamName) return util.errorMsg('请输入团队名称')
      if (form.invitationCode.length !== 6) return util.errorMsg('请输入6位数团队邀请码')
      form.accountId = this.form.id
      form.schoolId = this.form.schoolId
      form.studentAffiliatedInstitutionId = this.form.studentAffiliatedInstitutionId
      this.$post(this.api.addCompetitionTeam, form).then(res => {
        this.teamVisible = false
        this.addVisible = false
        this.init()
        util.successMsg('报名成功！')
      }).catch(res => { })
    },
    // 参赛信息
    toInfo (row) {
      this.$store.commit('setInnerReferrer', `${this.$route.path}?id=${this.id}&tab=tab6&name=${this.$route.query.name}&keyword=${this.keyword}&page=${this.page}&isDisable=${this.isDisable}`)
      this.$router.push(`info?id=${this.id}&accountId=${row.accountId}`)
    },
    exportAll () {
      if (this.listData.length) {
        this.exporting = true
        const data = this.multipleSelection
        if (data.length) {
          data.map((e, i) => e.id = i + 1)
          axios.post(this.api.exportDataInBatches, data, {
            headers: {
              token: this.token
            },
            responseType: 'blob'
          }).then((res) => {
            const name = res.headers['content-disposition']
            util.downloadFileDirect(name ? decodeURI(name) : '报名人员.xlsx', new Blob([res.data]))
            this.exporting = false
          }).catch(res => {
            this.exporting = false
          })
        } else {
          axios.get(`${this.api.exportAbnormalData}?competitionId=${this.id}`, {
            headers: {
              token: this.token
            },
            responseType: 'blob'
          }).then((res) => {
            const name = res.headers['content-disposition']
            util.downloadFileDirect(name ? decodeURI(name) : '报名人员.xlsx', new Blob([res.data]))
            this.exporting = false
          }).catch(res => {
            this.exporting = false
          })
        }
      }
    },
    // 批量删除
    async batchDel () {
      const list = this.multipleSelection
      const tips = list.length ? (this.info.completeCompetitionSetup.competitionType && list.find(e => e.captain === '是') ? '删除队长后，该团队下所有成员都会同步移除报名，已有的成绩也会一并删除，成绩排名将会受影响，是否确认删除？' : '删除后该参赛人员已有的成绩会一并删除，成绩排名将会受影响，是否确定要删除？') : '删除后参赛人员已有的成绩会一并删除，成绩排名将会受影响，<span style="font-size: 15px;color: #f00">是否确定删除全部报名人员？</span>'
      this.$confirm(tips, "提示", {
        type: "warning",
        dangerouslyUseHTMLString: true
      }).then(async () => {
        if (list.length) {
          await this.$post(this.api.batchDeleteApplicants, { registrationVOS: list })
        } else {
          await this.$post(`${this.api.deleteAllData}?competitionId=${this.id}`)
        }
        this.init()
        this.$message.success("删除成功");
        this.$refs.table.clearSelection()
      }).catch(() => { });
    },
  }
};
</script>

<style lang="scss" scoped>
/deep/.dia-form {
  .w-100 {
    width: 100%;
  }

  .tips {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.tips {
  font-size: 12px;
  color: #e90000;
}

/deep/.import-file {
  .el-progress__text,
  .el-progress,
  .el-upload-list__item-status-label {
    display: none !important;
  }
}
</style>