<template>
  <div>
    <el-alert title="资格信息" :closable="false" class="alert" type="info" />
    <el-form :inline="true" :model="topForm" label-width="110px" ref="form">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="付费课资格："
            prop="paySeniorNum"
            style="width: 100%"
            :rules="[
              { required: true, message: '请输入资格数', trigger: 'blur' },
              {
                pattern: /^(0|\+?[1-9][0-9]*)$/,
                message: '请输入正确的资格数',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="topForm.paySeniorNum"
              style="width: 370px"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="赠课资格："
            v-if="hasGive"
            :rules="[
              { required: true, message: '请输入赠课资格数', trigger: 'blur' },
              {
                pattern: /^(0|\+?[1-9][0-9]*)$/,
                message: '请输入正确的赠课资格数',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="topForm.giveSeniorNum"
              style="width: 370px"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item
          label="备注:"
          prop="memo"
          :rules="[{ required: true, message: '请输入备注', trigger: 'blur' }]"
        >
          <el-input
            type="textarea"
            :rows="3"
            v-model="topForm.memo"
            style="width: 370px"
             maxlength="50"
              show-word-limit
          ></el-input>
        </el-form-item>
      </el-row>
      <!-- <p style="color: red; margin-bottom: 20px">
        资格调整不影响该活动学员购买次数
      </p> -->
    </el-form>
    <el-alert title="添加学员" :closable="false" class="alert" type="info" />
    <el-form
      :inline="true"
      @submit="search"
      ref="searchForm"
      :model="searchForm"
    >
      <el-form-item prop="search">
        <el-input
          class="search"
          type="text"
          clearable
          v-model="searchForm.search"
          placeholder="学员名称/编号/手机号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="organId">
        <el-select
          class="multiple"
          filterable
          style="width: 180px !important"
          v-model.trim="searchForm.organId"
          clearable
          multiple
          placeholder="请选择分部"
        >
          <el-option
            v-for="(item, index) in organList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="subjectId">
        <el-select
          clearable
          v-model="searchForm.subjectId"
          filterable
          placeholder="声部"
        >
          <el-option
            v-for="item in selects.subjects"
            :value="item.id"
            :label="item.name"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="hasMusicCourse">
        <el-select
          clearable
          v-model="searchForm.hasMusicCourse"
          filterable
          placeholder="是否乐团在读"
        >
          <el-option value="1" label="是"></el-option>
          <el-option value="0" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="hasVipCourse">
        <el-select
          clearable
          v-model="searchForm.hasVipCourse"
          filterable
          placeholder="是否vip在读"
        >
          <el-option value="1" label="是"></el-option>
          <el-option value="0" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="hasPracticeCourse">
        <el-select
          clearable
          v-model="searchForm.hasPracticeCourse"
          filterable
          placeholder="是否网管课在读"
        >
          <el-option value="1" label="是"></el-option>
          <el-option value="0" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="hasMember">
        <el-select
          clearable
          v-model="searchForm.hasMember"
          filterable
          placeholder="是否会员"
        >
          <el-option value="1" label="是"></el-option>
          <el-option value="0" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="search">搜索</el-button>
        <el-button native-type="reset" type="primary" @click="onReSet"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="tableWrap">
      <el-table
        style="width: 100%"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        :data="tableList"
        ref="tableList"
        @selection-change="handleSelectionChange"
        @select="onTableSelect"
        row-key="userId"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          align="center"
          prop="organName"
          label="分部"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="userId"
          label="学员编号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="username"
          label="学员姓名"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="phone"
          label="手机号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="subjectNames"
          label="声部"
        ></el-table-column>
      </el-table>
      <pagination
        :total.sync="rules.total"
        :page.sync="rules.page"
        :limit.sync="rules.limit"
        :page-sizes.sync="rules.page_size"
        @pagination="getList"
      />
    </div>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import { getStudentList, addActivityUserMapperStudents } from "@/api/vipSeting";

export default {
  components: { pagination },
  props: ["organList", "hasGive"],
  data() {
    return {
      topForm: {
        paySeniorNum: null,
        giveSeniorNum: null,
        memo: "",
      },
      searchForm: {
        search: null,
        organId: this.organList.map((organ) => {
          return organ.id;
        }),
        subjectId: null,
        hasMember: null,
        hasMusicCourse: null,
        hasPracticeCourse: null,
        hasVipCourse: null,
      },
      tableList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      isDetele: false,
      deleteList: [],
    };
  },
  async mounted() {
    await this.$store.dispatch("setSubjects");
    this.getList();
  },
  methods: {
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.$refs.searchForm.resetFields();
      this.search();
    },
    async getList() {
      try {
        let { organId, ...rest } = this.searchForm;
        let params = {
          ...rest,
          page: this.rules.page,
          rows: this.rules.limit,
          organId: organId.join(","),
        };
        const res = await getStudentList(params);
        this.tableList = res.data.rows;
        this.rules.total = res.data.total;
        let idList = this.deleteList.map((course) => {
          return course.userId;
        });
        this.isDetele = true;
        this.$nextTick(() => {
          this.tableList.forEach((course) => {
            if (idList.indexOf(course.userId) != -1) {
              console.log(course);
              this.$refs.tableList.toggleRowSelection(course, true);
            }
          });
          this.isDetele = false;
        });
      } catch (e) {
        console.log(e);
      }

      /**
       *
       */
    },
    handleSelectionChange(arr) {
      // this.deleteList = arr;
      if (arr.length > 0) {
        // 有可能加 有可能减
        this.deleteList = this.deleteList.concat(arr);
        // 去重
        this.deleteList = this.$helpers.lodash.uniqBy(
          this.deleteList,
          "userId"
        );
      }
      // else if(){}
      else {
        if (this.isDetele) return;
        // 有2种 1是新页
        // 2是点击反选
        let idList = this.deleteList.map((course) => {
          return course.userId;
        });
        this.$nextTick(() => {
          let tableIdList = [];
          this.tableList.forEach((course) => {
            tableIdList.push(course.userId);
            if (idList.indexOf(course.userId) != -1) {
              this.$refs.tableList.toggleRowSelection(course, false);
              // 删除这个元素
            }
          });
          this.deleteList = this.$helpers.lodash.remove(
            this.deleteList,
            function (item) {
              return tableIdList.indexOf(item.userId) == -1;
            }
          );
          if (this.deleteList.length <= 0) {
            this.clearCom();
          }
        });
      }
    },
    onTableSelect(rows, row) {
      let idList = this.deleteList.map((course) => {
        return course.userId;
      });
      if (idList.indexOf(row.userId) != -1) {
        this.deleteList.splice(idList.indexOf(row.userId), 1);
        if (this.deleteList.length <= 0) {
          this.clearCom();
        }
      }
    },
    clearCom() {
      // this.deleteList = [];
      this.$set(this, "deleteList", []);
      this.$refs.tableList.clearSelection();
    },
    async submit() {
      this.$refs.form.validate(async (flag) => {
        if (flag) {
          let obj = {
            activityId: this.$route.query.id,
            memo: this.topForm.memo,
          };
          let activityStudentAdjustDtos = this.deleteList.map((stu) => {
            return {
              userId: stu.userId,
              courseNum: this.topForm.paySeniorNum,
              giveCourseNum: this.topForm.giveSeniorNum,
            };
          });
          obj.activityStudentAdjustDtos = activityStudentAdjustDtos;
          try {
            const res = await addActivityUserMapperStudents(obj);
            this.$message.success("添加成功");
            this.$emit("getList");
            this.$emit("close");
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.submitP {
  margin-bottom: 20px;
}
.alert {
  margin-bottom: 20px;
}
::v-deep .el-form--inline .el-form-item {
  margin-right: 0;
}

.search {
  ::v-deep .el-input__inner {
    width: 200px !important;
  }
}
</style>
