<template>
  <div>
    <div class="btnWrap">
      <el-button
        v-permission="'vipGroupManage/addVipGroupStudents'"
        @click="addStudentList"
        type="primary"
      >
        新增学员
      </el-button>
      <el-button v-permission="'vipGroupManage/update'" @click="expireVisible = true"  type="primary">
        有效期调整
      </el-button>
    </div>

    <div class="tableWrap">
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
      >
        <el-table-column
          label="学员姓名"
          prop="userName"
          align="center"
          width="180"
        >
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phone" width="180">
        </el-table-column>
        <el-table-column prop="studentStatus" align="center" label="学员状态">
          <template slot-scope="scope">
            <div>
              {{ scope.row.studentStatus | studentStatus }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="courseSalary" align="center" label="课程余额">
          <template slot-scope="scope">
            <div>
              {{ scope.row.courseSalary | moneyFormat }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="applyDate" align="center" label="报名时间">
          <template slot-scope="scope">
            <div>
              {{ scope.row.applyDate | formatTimer }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="refundDate" align="center" label="退课时间">
          <template slot-scope="scope">
            <div>
              {{ scope.row.refundDate | formatTimer }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div>
              <el-button
                type="text"
                v-if="
                  scope.row.studentStatus == 0 || scope.row.studentStatus == 3
                "
                v-permission="'vipGroupManage/applyRefundForStudent'"
                @click="lookFee(scope)"
                >退学</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.studentStatus == 0"
                @click="stopCourse(scope)"
                >休学</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.studentStatus == 3"
                @click="recoveryCourse(scope)"
                >恢复</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="学员列表" width="70%" :visible.sync="maskVisible">
      <el-form :model="maskForm" :inline="true">
        <el-form-item>
          <el-input
            placeholder="请输入学生姓名或手机号"
            @keyup.enter.native="search"
            v-model.trim="maskForm.search"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="search">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="maskStudentList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
      >
        <el-table-column label="" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model.trim="activeStudent"
              :label="scope.row.id"
              @change.native="getTemplateRow(scope.$index, scope.row)"
              >&nbsp</el-radio
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          align="center"
          label="学生姓名"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="phone"
          align="center"
          label="手机号"
          width="200"
        ></el-table-column>
        <el-table-column prop="courseSalary" label="课程余额"></el-table-column>
      </el-table>
      <pagination
        save-key="vipDetail-vipStudentList"
        sync
        :total.sync="rules.total"
        :page.sync="rules.page"
        :limit.sync="rules.limit"
        :page-sizes="rules.page_size"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="maskVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStudent">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="学员复学" width="800px" :visible.sync="adjustmentVisible">
      <el-form
        :model="adjustmentForm"
        label-position="right"
        label-width="120px"
        ref="adjustmentForm"
        :rules="adjustmentRules"
        :inline="true"
      >
        <el-form-item label="剩余课时">
          <el-input
            disabled
            v-model.trim="adjustmentForm.count"
            style="width: 200px !important"
          ></el-input>
        </el-form-item>
        <el-form-item label="任课老师" prop="teacher">
          <el-select
            v-model.trim="adjustmentForm.teacher"
            clearable
            filterable
            style="width: 200px !important"
          >
            <el-option
              v-for="(item, index) in teacherList"
              :key="index"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <br /> -->
        <el-form-item label="排课起始时间" prop="courseTime">
          <el-date-picker
            v-model.trim="adjustmentForm.courseTime"
            :picker-options="pickerOptions"
            style="width: 200px !important"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="有效期截止" prop="expireDate">
          <el-date-picker
            :disabled="true"
            v-model.trim="adjustmentForm.expireDate"
            :picker-options="pickerOptions"
            style="width: 200px !important"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-checkbox
            style="margin-left: 10px"
            v-model.trim="adjustmentForm.checked"
            >是否跳过节假日</el-checkbox
          >
        </el-form-item>
      </el-form>
      <div class="WeekWrap">
        <h3 style="margin-bottom: 20px">
          循环次数
          <el-button type="text" style="margin-left: 10px" @click="addWeek"
            >添加</el-button
          >
        </h3>
        <div class="countWrap" style="margin-bottom: 10px">
          <div
            class="countItem"
            style="margin-bottom: 20px"
            v-for="(item, index) in weekList"
            :key="index"
          >
            <span class="title">循环周期: </span>
            <el-select
              v-model.trim="item.dayOfWeek"
              filterable
              clearable
              style="width: 200px !important"
            >
              <el-option
                v-for="(item, index) in weekDateList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <span style="margin-left: 10px">开始时间</span>
            <el-time-select
              style="margin-left: 10px; width: 100px"
              placeholder=""
              v-model.trim="item.startClassTime"
              :picker-options="{
                start: '04:30',
                step: '00:05',
                end: '23:55',
              }"
            >
            </el-time-select>
            <el-button
              style="margin-left: 10px"
              type="danger"
              @click="removeWeek(item)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adjustmentVisible = false">取 消</el-button>
        <el-button type="primary" @click="submieRecover">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 有效期调整 -->
    <el-dialog title="有效期调整" width="400px" :visible.sync="expireVisible">
      <el-form
        :model="expireForm"
        ref="expireForm"
        :rules="expireRules"
        label-position="right"
        label-width="80px;"
        :inline="true"
      >
        <el-form-item label="课程结束时间" prop="coursesExpireDate">
          <el-date-picker
            v-model.trim="expireForm.coursesExpireDate"
            style="width: 200px !important"
            type="date"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <!-- <div style="padding-left: 15px; color: red;">课程结束时间不得晚于，{{ expireForm.tempCoursesExpireDate }}</div> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="expireVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitExpireDate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import dayjs from "dayjs";
import {
  findVipGroupStudents,
  leaveSchool,
  getStudentSurplusCourseFee,
  getHaveCourseBalanceStudents,
  addVipGroupStudents,
  vipPauseForStudent,
  getStudentPauseInfo,
  recoverForStudent,
  findTeacherWithVipGroupOrganAndSubject,
  vipGroupManageUpdate,
} from "@/api/vipSeting";
import { permission } from "@/utils/directivePage";
export default {
  components: { pagination },
  data() {
    return {
      expireVisible: false,
      expireForm: {
        coursesExpireDate: "",
      },
      expireRules: {
        coursesExpireDate: [
          { required: true, message: "请选择课程结束时间", trigger: "blur" },
        ],
      },
      adjustmentVisible: false,
      tableList: [],
      id: "",
      maskStudentList: [],
      maskVisible: false,
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      activeStudent: "",
      maskForm: {
        search: "",
      },
      adjustmentForm: {
        count: "",
        courseTime: "",
        checked: false,
        addCount: "",
        courseType: "",
        fee: "",
        teacher: "",

        expireDate: "",
      },
      adjustmentRules: {
        courseTime: [{ required: true, message: "请选择开始时间" }],
        addCount: [{ required: true, message: "请输入加课次数" }],
        courseType: [{ required: true, message: "请选择课程类型" }],
        fee: [{ required: true, message: "请输入费用" }],
        teacher: [{ required: true, message: "请选择老师" }],

        expireDate: [{ required: true, message: "请输入有效期截止" }],
      },
      weekDateList: [
        { value: "1", label: "星期一" },
        { value: "2", label: "星期二" },
        { value: "3", label: "星期三" },
        { value: "4", label: "星期四" },
        { value: "5", label: "星期五" },
        { value: "6", label: "星期六" },
        { value: "7", label: "星期日" },
      ],
      weekList: [
        {
          dayOfWeek: "",
          startTime: "",
          endTime: "",
          moid: new Date().getTime(),
        },
      ],
      pickerOptions: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime();
        },
      },
      teacherList: [],
    };
  },
  mounted() {
    this.__init();
  },
  activated() {
    this.__init();
  },
  methods: {
    permission(str) {
      console.log(permission(str));
      return permission(str);
    },
    __init() {
      let id = this.$route.query.id;
      this.id = id;
      this.rules.page = 1;
      this.getStudents();
      findTeacherWithVipGroupOrganAndSubject({ vipGroupId: this.id }).then(
        (res) => {
          if (res.code == 200) {
            this.teacherList = res.data;
          }
        }
      );
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    reset() {
      this.rules.page = 1;
      this.maskForm.search = null;
      this.activeStudent = "";
      this.getList();
    },
    getStudents() {
      findVipGroupStudents({ vipGroupId: this.id }).then((res) => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          for (let i in this.tableList) {
            this.tableList[i].fee = 0;
            this.tableList[i].visible = false;
          }
        }
      });
    },
    // 删除循环周
    removeWeek(item) {
      for (let i in this.weekList) {
        if (this.weekList[i].id == item.id) {
          this.weekList.splice(i, 1);
        }
      }
    },
    leaveSchool(scope) {
      let studentId = scope.row.id;
      let vipGroupId = this.id;
      let amount = scope.row.fee;
      leaveSchool({ studentId, vipGroupId, amount }).then((res) => {
        if (res.code == 200) {
          this.$message.success("退学成功");
          this.getStudents();
        }
      });
    },
    lookFee(scope) {
      this.$confirm(`确定是否退学?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = scope.row.id;
          if (scope.row.studentStatus == 3) {
            this.leaveSchool(scope);
          } else {
            getStudentSurplusCourseFee({
              studentId: id,
              vipGroupId: this.id,
            }).then((res) => {
              if (res.code == 200) {
                // scope.row.fee =
                this.$prompt("请输入退课金额", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  inputValue: res.data.suplusCourseFee,
                })
                  .then(({ value }) => {
                    scope.row.fee = value;
                    this.leaveSchool(scope);
                  })
                  .catch((res) => {});
              }
            });
          }
        })
        .catch(() => {});
    },
    addStudentList() {
      // 发请求 搜索学生
      if (this.tableList.length <= 0) {
        this.$confirm(
          "添加学员后，该课程组将无法通过购买途径加入,是否确认该操作?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.getList();
          })
          .catch(() => {});
      } else {
        this.getList();
      }
    },
    getList() {
      let search = this.maskForm.search || null;
      getHaveCourseBalanceStudents({
        organId: null,
        page: this.rules.page,
        rows: this.rules.limit,
        search,
      }).then((res) => {
        if (res.code == 200) {
          this.rules.total = res.data.total;
          this.maskStudentList = res.data.rows;
          this.maskVisible = true;
        }
      });
    },
    getTemplateRow(index, row) {
      this.activeStudent = row.id;
    },
    addStudent() {
      if (!this.activeStudent) {
        this.$message.error("请选择一名学生");
        return;
      }
      addVipGroupStudents({
        vipGroupId: this.id,
        studentIds: this.activeStudent,
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success("添加成功");
          this.getStudents();
        }
      });
    },
    stopCourse(scope) {
      this.$confirm("是否休学?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 发请求 申请休学
          vipPauseForStudent({
            vipGroupId: this.id,
            studentId: scope.row.id,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("休学成功");
              this.getStudents();
            }
          });
        })
        .catch(() => {});
    },
    recoveryCourse(scope) {
      getStudentPauseInfo({
        studentId: scope.row.id,
        vipGroupId: this.id,
      }).then((res) => {
        if (res.code == 200) {
          if (res.data.isPause == 0) {
            // vip状态没暂停 不需要排课
            // 课程编号  学生编号
            const h = this.$createElement;
            this.$msgbox({
              title: "提示",
              message: h("p", null, [
                h("p", null, "将按照当前剩余课时安排上课"),
                // h("span", null, `排课截至时间:`),
                // h("span", { style: "color: red" }, `${res.data.expireDate}`), 辜经理同意注释
              ]),
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              showCancelButton: true,
            })
              .then(() => {
                // 发请求 恢复上课
                recoverForStudent({
                  vipGroupId: this.id,
                  userId: scope.row.id,
                }).then((res) => {
                  if (res.code == 200) {
                    this.adjustmentVisible = false;
                    this.getStudents();
                  }
                });
              })
              .catch(() => {});
          } else {
            this.activeStudent = res.data.studentId;
            this.adjustmentVisible = true;
            this.adjustmentForm.teacher = res.data.teacherId;
            this.adjustmentForm.count = `${res.data.totalCourseTimes}+${res.data.giveCourseTimes}`;
            this.adjustmentForm.expireDate = res.data.expireDate;
          }
        }
      });

      // this.$confirm('是否休学?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   // 发请求 申请休学
      //   vipPauseForStudent({ vipGroupId: this.id, studentId: scope.row.id }).then(res => {
      //     if (res.code == 200) {
      //       this.$message.success('休学成功')
      //       this.getList()
      //     }
      //   })
      // }).catch(() => {
      // });
    },
    addWeek() {
      // 添加循环周期
      this.weekList.push({
        dayOfWeek: "",
        startClassTime: "",
        endClassTime: "",
        id: new Date(),
      });
    },
    submieRecover() {
      if (this.weekList.length <= 0) {
        this.$message.error("排课循环次数不能为空");
        return;
      }
      this.$refs["adjustmentForm"].validate((res) => {
        if (res) {
          // 发请求
          let obj = {};
          obj.courseCreateStartTime = this.adjustmentForm.courseTime;
          obj.skipHoliday = this.adjustmentForm.checked;
          obj.teacherId = this.adjustmentForm.teacher;
          obj.userId = this.activeStudent;
          obj.courseTimes = [];
          obj.courseTimes = this.weekList;
          obj.vipGroupId = this.id;
          obj.expireDate = this.adjustmentForm.expireDate;
          recoverForStudent(obj).then((res) => {
            if (res.code == 200) {
              this.adjustmentVisible = false;
              this.getStudents();
            }
          });
        } else {
          this.$message.error("请填写必要参数");
        }
      });
      this.activeStudent;
    },
    submitExpireDate() {
      this.$refs.expireForm.validate((some) => {
        if (some) {
          vipGroupManageUpdate({
            id: this.id,
            coursesExpireDate: this.expireForm.coursesExpireDate,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("有效期修改成功");
              this.expireVisible = false;
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  display: inline-block;
  width: 108px;
  text-align: right;
  margin-right: 10px;
}

/deep/.el-input-number .el-input__inner {
  text-align: left !important;
}
.btnWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-bottom: 15px;
}
</style>
