<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel" :content="name"></el-page-header>
    </h2>
    <div class="m-core">
      <el-form ref="liveForm" :model="form" label-position="top">
        <el-alert
          title="课程规划"
          :closable="false"
          type="info"
          style="margin: 0 0 20px"
        />
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item
              label="直播课标题"
              prop="roomTitle"
              :rules="[{ required: true, message: '请输入直播课标题' }]"
            >
              <el-input
                v-model="form.roomTitle"
                placeholder="请输入直播课标题"
                maxlength="20"
                show-word-limit
                :disabled="![0, 1].includes(status)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="直播课内容"
              prop="liveRemark"
              :rules="[{ required: true, message: '请输入直播课内容' }]"
            >
              <el-input
                type="textarea"
                v-model="form.liveRemark"
                placeholder="请输入直播课内容"
                maxlength="200"
                show-word-limit
                :disabled="![0, 1].includes(status)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="分部"
              prop="organIds"
              :rules="[{ required: true, message: '请选择分部' }]"
            >
              <select-all
                v-model.trim="form.organIds"
                filterable
                placeholder="请选择分部"
                multiple
                clearable
                :disabled="isDisabled"
              >
                <el-option
                  v-for="(item, index) in selects.branchs"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </select-all>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="声部"
              prop="subjectIdList"
              :rules="[{ required: true, message: '请选择声部' }]"
            >
              <el-select
                v-model.trim="form.subjectIdList"
                filterable
                clearable
                @change="onChangeSubject"
                placeholder="请选择声部"
                style="width: 100% !important"
                :disabled="isDisabled"
              >
                <el-option
                  v-for="(item, index) in subjectList"
                  :key="index"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="指导老师"
              prop="teacher"
              :rules="[{ required: true, message: '请选择指导老师' }]"
            >
              <el-select
                v-model.trim="form.teacher"
                filterable
                clearable
                placeholder="请选择指导老师"
                style="width: 100% !important"
                :disabled="!form.subjectIdList"
              >
                <el-option
                  v-for="(item, index) in teacherList"
                  :key="index"
                  :label="item.realName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="乐团主管"
              prop="educationalTeacherId"
              :rules="[{ required: true, message: '请选择乐团主管' }]"
            >
              <el-select
                v-model.trim="form.educationalTeacherId"
                filterable
                clearable
                style="width: 100% !important"
                :rules="[{ required: true, message: '请选择乐团主管' }]"
              >
                <el-option
                  v-for="(item, key) in educationList"
                  :key="key"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="课程购买开始时间"
              prop="signUpStart"
              :rules="[{ required: true, message: '请选择课程购买开始时间' }]"
            >
              <!-- <el-date-picker style="width: 100%" v-model="form.signUpTimeList" :picker-options="pickerOptions"
                type="daterange" :default-time="['00:00:00', '23:59:59']" range-separator="-" start-placeholder="购买开始日期"
                end-placeholder="购买结束日期">
              </el-date-picker> -->
              <el-date-picker
                v-model="form.signUpStart"
                :picker-options="startBigin()"
                type="date"
                style="width: 100% !important"
                placeholder="购买开始日期"
                @change="
                  () => {
                    form.signUpEnd = '';
                    form.timeTable = []; // 课表重置
                  }
                "
                :disabled="isDisabled"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="课程购买结束时间"
              prop="signUpEnd"
              :rules="[{ required: true, message: '请选择课程购买结束时间' }]"
            >
              <el-date-picker
                v-model="form.signUpEnd"
                type="date"
                :picker-options="beginDate()"
                style="width: 100% !important"
                placeholder="购买结束日期"
                @change="
                  () => {
                    if (status == 0) {
                      form.timeTable = []; // 课表重置
                    }
                  }
                "
                :disabled="type === 'update' && status === 2"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="课时数"
              prop="onlineClassesNum"
              :rules="[
                {
                  required: true,
                  validator: validStock,
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model="form.onlineClassesNum"
                placeholder="请输入课时数"
                maxlength="2"
                @input="
                  val => {
                    form.onlineClassesNum = val.replace(/[^\d]/g, '');
                  }
                "
                @change="
                  () => {
                    form.timeTable = []; // 课表重置
                  }
                "
                :disabled="isDisabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="课程时长"
              prop="singleClassMinuteId"
              :rules="[{ required: true, message: '请选择课程时长' }]"
            >
              <el-select
                v-model.trim="form.singleClassMinuteId"
                filterable
                clearable
                style="width: 100% !important"
                placeholder="请选择课程时长"
                @change="onSingleClassChange"
                :disabled="isDisabled"
              >
                <el-option
                  v-for="(item, key) in liveGroupList"
                  :key="key"
                  :label="item.singleClassMinutes"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="现单价"
              prop="onlineClassesUnitPrice"
              :rules="[
                {
                  required: true,
                  message: '请输入正确的现单价',
                  trigger: 'blur',
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                }
              ]"
            >
              <el-input
                v-model="form.onlineClassesUnitPrice"
                placeholder="请输入现单价"
                maxlength="9"
                :disabled="isDisabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="原单价"
              prop="offlineClassesUnitPrice"
              :rules="[
                {
                  required: true,
                  message: '请输入正确的原单价',
                  trigger: 'blur',
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                }
              ]"
            >
              <el-input
                v-model="form.offlineClassesUnitPrice"
                placeholder="请输入原单价"
                maxlength="9"
                :disabled="isDisabled"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="总现价" prop="countOnlineClassesUnitPrice">
              <el-input
                v-model="countOnlineClassesUnitPrice"
                placeholder="请输入总现价"
                maxlength="9"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="总原价" prop="countOfflineClassesUnitPrice">
              <el-input
                v-model="countOfflineClassesUnitPrice"
                placeholder="请输入总原价"
                maxlength="9"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-button type="danger" @click="onTimeTable" :disabled="isDisabled"
          >点击排课</el-button
        >
        <el-table
          :key="studentRefKey"
          v-if="showTable"
          style="width: 100%; margin-top: 20px"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="form.timeTable"
        >
          <el-table-column align="center" label="课时">
            <template slot-scope="scope">
              第{{ scope.$index + 1 }}课
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="内容"
            width="300px"
            prop="teachingContent"
            key="teachingContent"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'timeTable.' + scope.$index + '.teachingContent'"
                :rules="[{ required: true, message: '请输入内容' }]"
                style="margin-bottom: 0"
              >
                <el-input
                  v-model="scope.row.teachingContent"
                  placeholder="请输入内容"
                  maxlength="100"
                  show-word-limit
                  type="textarea"
                  :rows="3"
                >
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="技能/知识点掌握"
            width="300px"
            prop="teachingPoint"
            key="teachingPoint"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'timeTable.' + scope.$index + '.teachingPoint'"
                :rules="[{ required: true, message: '请输入技能/知识点掌握' }]"
                style="margin-bottom: 0"
              >
                <el-input
                  v-model="form.timeTable[scope.$index].teachingPoint"
                  placeholder="请输入技能/知识点掌握"
                  show-word-limit
                  maxlength="100"
                  type="textarea"
                  :rows="3"
                >
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="singleClassMinutes"
            label="时长"
          ></el-table-column>
          <el-table-column align="center" label="课程日期">
            <template slot-scope="scope">
              <div>{{ scope.row.classDate | formatTimer }}</div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="startClassTimeStr"
            label="开始时间"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="endClassTimeStr"
            label="结束时间"
          ></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="resetCourse(scope.row, scope.$index)"
                :disabled="isDisabled"
                >调整</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <el-alert
          title="直播课信息"
          :closable="false"
          type="info"
          style="margin: 20px 0"
        />
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item
              label="直播设备"
              prop="os"
              :rules="[{ required: true, message: '请选择推广类型' }]"
            >
              <el-radio-group v-model="form.os" :disabled="isDisabled">
                <!-- 根据不同的模式，显示不同的直播设备 -->
                <el-radio v-if="serviceProvider === 'rongCloud'" label="pc"
                  >web</el-radio
                >
                <el-radio
                  v-if="serviceProvider === 'tencentCloud'"
                  label="client"
                  >乐直播</el-radio
                >
                <el-radio label="mobile">手机</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="直播场景"
              prop="useScene"
              :rules="[{ required: true, message: '请选择直播场景' }]"
            >
              <el-radio-group v-model="form.useScene" :disabled="isDisabled">
                <el-radio label="NORMAL">普通场景</el-radio>
                <el-radio label="MUSIC">音乐场景</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              prop="roomConfig.whether_video"
              label="保存直播回放"
              :rules="[{ required: true, message: '是否保存直播回放' }]"
            >
              <el-radio-group
                v-model="form.roomConfig.whether_video"
                :disabled="isDisabled"
              >
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              prop="roomConfig.whether_view_shop_cart"
              label="是否展示购物车"
              :rules="[{ required: true, message: '是否展示购物车' }]"
            >
              <el-radio-group
                v-model="form.roomConfig.whether_view_shop_cart"
                :disabled="isDisabled"
              >
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
              label="预热模板（模板使用于分享宣传图片）"
              prop="preTemplate"
              :rules="[{ required: true, message: '请选择预热模板' }]"
            >
              <el-radio-group v-model="form.preTemplate" :disabled="isDisabled">
                <div class="chioseWrap">
                  <div class="chioseItem" @click="setPreTemplate(1)">
                    <img src="./images/img1.png" alt="" />
                    <i
                      class="dotWrap"
                      :class="[
                        form.preTemplate == 1 ? 'checked' : '',
                        isDisabled ? 'disabled' : ''
                      ]"
                    ></i>
                  </div>
                  <div class="chioseItem" @click="setPreTemplate(2)">
                    <img src="./images/img2.png" alt="" />
                    <i
                      class="dotWrap"
                      :class="[
                        form.preTemplate == 2 ? 'checked' : '',
                        isDisabled ? 'disabled' : ''
                      ]"
                    ></i>
                  </div>
                  <div class="chioseItem" @click="setPreTemplate(3)">
                    <img src="./images/img3.png" alt="" />
                    <i
                      class="dotWrap"
                      :class="[
                        form.preTemplate == 3 ? 'checked' : '',
                        isDisabled ? 'disabled' : ''
                      ]"
                    ></i>
                  </div>
                </div>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-button
              type="primary"
              @click="onReset"
              v-if="[0, 1].includes(status)"
              >重置</el-button
            >
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog
      title="排课"
      ref="maskForm"
      width="500px"
      :visible.sync="dialogFormVisible"
    >
      <addLiveCourse
        :singleClassMinutes="form.singleClassMinutes"
        :signUpEnd="form.signUpEnd"
        :status="status"
        :onlineCourseNum="form.onlineClassesNum"
        @close="dialogFormVisible = false"
        @confirm="onConfirm"
      />
    </el-dialog>

    <el-dialog
      title="课程调整"
      width="400px"
      :before-close="handleClose"
      :visible.sync="courseVisible"
    >
      <el-form
        :model="maskForm"
        class="maskForm"
        ref="maskForm"
        :rules="maskRules"
        label-position="right"
        label-width="80px"
        :inline="true"
      >
        <el-form-item label="上课日期" prop="date">
          <el-date-picker
            v-model.trim="maskForm.date"
            type="date"
            :picker-options="coursesDate()"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            placeholder="起始时间"
            v-model.trim="startTime"
            @change="changeStartTime"
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{
              selectableRange: `${nowTime} - 23:30:00`
            }"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            v-model="maskForm.endTime"
            disabled
          >
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="courseVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitResetClass">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import dayjs from "dayjs";
import deepClone from "@/helpers/deep-clone";
import preview from "./modals/preview.vue";
import addLiveCourse from "./modals/addLiveCourse.vue";
import { diffTimerFormMinute, addTimerFormMinute } from "@/utils/date";
import {
  sysTenantConfigAll,
  findTeacherByTenantId,
  liveGroupDetail,
  updateLiveGroup
} from "./api";
import { getSubject, getOrganRole } from "@/api/buildTeam";
import { vipGroupCategory, createVip } from "@/api/vipSeting";
export default {
  components: { preview, addLiveCourse },
  data() {
    const query = this.$route.query;
    return {
      name: query.type == "update" ? "修改直播课" : "新建直播课",
      id: query.id,
      type: query.type,
      dialogFormVisible: false,
      form: {
        roomTitle: "", //
        liveRemark: "", // 内容
        organIds: [],
        subjectIdList: null, // 声部
        teacher: "", // 指导老师列表
        educationalTeacherId: null, // 乐团主管
        preTemplate: 1, // 模板
        signUpStart: null, // 开始时间
        signUpEnd: null, // 结束时间
        signUpTimeList: [], // 课程购买时间
        onlineClassesNum: null,
        singleClassMinuteId: null, //时长编号
        singleClassMinutes: null, // 时长
        onlineClassesUnitPrice: null, // 售价
        offlineClassesUnitPrice: null, // 原价
        os: "client", // 直播设备
        useScene: "NORMAL", // 直播场景
        popularizeType: "ALL", // 观看权限信息
        viewMode: "LOGIN",
        roomConfig: {
          whether_like: 0,
          whether_chat: 0,
          whether_video: 0,
          whether_mic: 0,
          whether_view_shop_cart: 1
        },
        timeTable: [], // 排课
        clientType: "TEACHER" // 主讲人身份 默认[老师]
      },
      status: 0, // 直播课状态
      auditStatus: null, // 审核状态
      courseStartDate: null, // 课程开始时间
      serviceProvider: "tencentCloud", // 直播模式
      subjectList: [], // 声部列表
      teacherList: [], // 指导老师
      educationList: [], // 乐团主管
      liveGroupList: [], // 课时列表

      activeRow: null,
      actvieIndex: 0,
      maskForm: {
        date: "",
        startTime: "",
        endTime: "",
        id: "",
        teachMode: ""
      },
      maskRules: {
        date: [{ required: true, message: "请选择上课时间", trigger: "blur" }]
      },
      courseVisible: false,
      startTime: "",
      courseTime: "",
      studentRefKey: "12321321",
      showTable: true
    };
  },
  async mounted() {
    this.$store.dispatch("setBranchs");
    await this.__init();
  },
  methods: {
    async onChangeSubject(val) {
      try {
        // 判断声部，如果为MUSIC_THEORY则为乐理，显示普通
        let subjectItem = {};
        this.subjectList.forEach(item => {
          if (val == item.id) {
            subjectItem = item;
          }
        });
        if (subjectItem.code !== "MUSIC_THEORY") {
          this.form.useScene = "MUSIC";
        } else {
          this.form.useScene = "NORMAL";
        }

        this.form.teacher = ""; // 重置指导老师
        // 根据科目id获取相应的老师
        await findTeacherByTenantId({
          subjectIds: subjectItem.code == "MUSIC_THEORY" ? null : val
        }).then(res => {
          this.teacherList = res.data;
        });
      } catch {}
    },
    onCancel() {
      this.$store.dispatch("delVisitedViews", this.$route);
      this.$router.push("/liveClassManager?tabrouter=2");
    },
    coursesDate(dateStr) {
      let self = this;
      return {
        firstDayOfWeek: 1,
        disabledDate: time => {
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      };
    },
    pickerOptions(dateStr) {
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      };
    },
    resetCourse(row, index) {
      /**
       * maskForm.startTime
       */
      this.activeRow = row;
      this.actvieIndex = index;
      this.maskForm.date = row.classDate;
      this.startTime = row.startClassTimeStr;
      this.maskForm.endTime = row.endClassTimeStr;
      this.courseTime = row.singleClassMinutes;
      // this.maskForm.endTime = row.endClassTimeStr;
      console.log(this.startTime, "this.startTime");
      this.maskForm.id = index;

      this.maskForm.teachMode = row.teachMode;
      // 修改课时
      this.courseVisible = true;
    },
    handleClose() {
      this.courseVisible = false;
      this.startTime = "";
      this.maskForm = {
        date: "",
        startTime: "",
        endTime: "",
        id: "",
        address: "",
        teachMode: ""
      };
      this.actvieRow = null;
      this.actvieIndex = 0;
      this.$refs["maskForm"].resetFields();
    },
    submitResetClass() {
      console.log(this.activeRow, "activeRow");
      console.log(this.maskForm, "maskForm");

      this.form.timeTable[
        this.actvieIndex
      ].actualTeacherId = this.activeRow.actualTeacherId;
      this.form.timeTable[this.actvieIndex].classDate = this.maskForm.date;
      this.form.timeTable[
        this.actvieIndex
      ].endClassTimeStr = this.maskForm.endTime;
      this.form.timeTable[
        this.actvieIndex
      ].singleClassMinutes = this.courseTime;
      this.form.timeTable[this.actvieIndex].startClassTimeStr = this.startTime;
      this.form.timeTable[
        this.actvieIndex
      ].teachMode = this.activeRow.teachMode;
      this.form.timeTable[
        this.actvieIndex
      ].teachingContent = this.activeRow.teachingContent;
      this.form.timeTable[
        this.actvieIndex
      ].teachingPoint = this.activeRow.teachingPoint;

      console.log(
        " this.form.timeTable[this.actvieIndex]",
        this.form.timeTable[this.actvieIndex]
      );
      this.form.timeTable.sort((a, b) => {
        const aTime = dayjs(
          dayjs(a.classDate).format("YYYY-MM-DD") +
            " " +
            a.startClassTimeStr +
            ":00"
        ).valueOf();
        const bTime = dayjs(
          dayjs(b.classDate).format("YYYY-MM-DD") +
            " " +
            b.startClassTimeStr +
            ":00"
        ).valueOf();
        return aTime - bTime;
      });
      this.showTable = false;
      this.handleClose();
      this.studentRefKey = Math.random();
      this.$nextTick(() => {
        this.showTable = true;
      });
    },
    changeStartTime(val) {
      this.$nextTick(res => {
        if (val) {
          this.$set(
            this.maskForm,
            "endTime",
            addTimerFormMinute(
              dayjs(this.maskForm.date).format("YYYY-MM-DD"),
              val,
              this.courseTime
            )
          );
          console.log(
            addTimerFormMinute(
              dayjs(this.maskForm.date).format("YYYY-MM-DD"),
              val,
              this.courseTime
            ),
            "addTimerFormMinute"
          );
        } else {
          this.$set(this.maskForm, "endTime", "");
        }
        if (!this.maskForm.endTime) {
          this.$set(this, "startTime", "");
        }
      });
    },
    validStock(rule, value, callback) {
      if ((value == "" && typeof value == "string") || value == null) {
        callback(new Error("请输入课时数"));
      } else if (value <= 0) {
        callback(new Error("课时数必须大于0"));
      } else {
        callback();
      }
    },

    setPreTemplate(index) {
      if (this.isDisabled) return;
      this.form.preTemplate = index;
    },
    async onSubmit() {
      this.$refs.liveForm.validate(async flag => {
        if (!flag) {
          this.onScrollError();
          return false;
        }

        try {
          const form = this.form;
          if (form.timeTable.length <= 0) {
            this.$message.error("请点击排课");
            return;
          }
          const timeTable = [];
          form.timeTable.forEach(item => {
            timeTable.push({
              classDate: item.classDate,
              actualTeacherId: form.teacher,
              startClassTimeStr: item.startClassTimeStr,
              endClassTimeStr: item.endClassTimeStr,
              teachMode: item.teachMode,
              id: item.id,
              teachingContent: item.teachingContent,
              teachingPoint: item.teachingPoint
            });
          });

          let obj = {
            courseSchedules: timeTable,
            vipGroupApplyBaseInfo: {
              groupType: "LIVE",
              vipGroupStudentCoursePrices: [],
              // coursesExpireDate: this.leftForm.courseEnd,
              // teacherSchoolId: this.leftForm.section,
              studentIdList: "",
              offlineClassesNum: 0,
              onlineClassesNum: form.onlineClassesNum || 0,
              offlineClassesUnitPrice: form.offlineClassesUnitPrice || 0,
              onlineClassesUnitPrice: form.onlineClassesUnitPrice || 0,
              registrationStartTime: dayjs(form.signUpStart).format(
                "YYYY-MM-DD"
              ),
              paymentExpireDate: dayjs(form.signUpEnd).format("YYYY-MM-DD"),
              singleClassMinutes: form.singleClassMinutes,
              userId: form.teacher,
              // vipGroupActivityId: form.singleClassMinuteId,
              vipGroupCategoryId: form.singleClassMinuteId,
              onlineTeacherSalary: 0,
              offlineTeacherSalary: 0,
              giveTeachMode: "ONLINE",
              subjectIdList: form.subjectIdList,
              educationalTeacherId: form.educationalTeacherId,
              organId: -1,
              organIdList: form.organIds.join(",")
            },
            liveBroadcastRoom: {
              speakerId: form.teacher,
              clientType: "TEACHER",
              roomTitle: form.roomTitle,
              liveRemark: form.liveRemark,
              preTemplate: form.preTemplate,
              useScene: form.useScene,
              os: form.os,
              serviceProvider: form.serviceProvider,
              viewMode: form.viewMode,
              popularizeType: form.popularizeType,
              roomConfig: {
                ...form.roomConfig,
                subjectId: form.subjectIdList,
                groupType: "LIVE"
              }
            }
          };
          console.log(obj, "obj");
          if (this.type === "update") {
            obj.vipGroupApplyBaseInfo.id = this.id;
            obj.vipGroupApplyBaseInfo.auditStatus = this.auditStatus;
            await updateLiveGroup(obj);
            this.$message.success("修改成功");
            this.$store.dispatch("delVisitedViews", this.$route);
            this.$router.push({
              path: "/liveClassManager",
              query: {
                tabrouter: 2
              }
            });
          } else {
            createVip(obj).then(res => {
              if (res.code == 200) {
                this.$message.success("创建成功");
                this.$store.dispatch("delVisitedViews", this.$route);
                this.$router.push({
                  path: "/liveClassManager",
                  query: {
                    tabrouter: 2
                  }
                });
              }
            });
          }
        } catch (e) {
          console.log(e);
        }
      });
    },
    onReset() {
      // 重置
      this.form.timeTable = [];
      this.$refs.liveForm.resetFields();
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("el-alert");
        isError[0].scrollIntoView({
          block: "center",
          behavior: "smooth"
        });
      });
    },
    // 点击排课
    async onTimeTable() {
      let count = 0;
      this.$refs.liveForm.validateField(
        ["signUpStart", "signUPEnd", "onlineClassesNum", "singleClassMinuteId"],
        valid => {
          count += 1;
          if (valid) {
            this.onScrollError();
            return;
          }

          if (count >= 3) {
            this.dialogFormVisible = true;
          }
        }
      );
    },
    beginDate() {
      const timer = this.form.signUpStart || "";
      const courseTimer = this.courseStartDate
        ? dayjs(this.courseStartDate).format("YYYY-MM-DD")
        : "";
      const type = this.type;
      const status = this.status;
      // console.log(type, courseTimer, 'courseTimer')
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          if (timer) {
            if (courseTimer && type === "update" && status != 0) {
              // console.log(new Date(timer).getTime(), time.getTime(), new Date(timer).getTime() >= time.getTime(), dayjs(time).format('YYYY-MM-DD'), new Date(courseTimer + ' 00:00:00').getTime(), time.getTime() >= new Date(courseTimer + ' 00:00:00').getTime(), courseTimer)
              return (
                new Date(timer).getTime() > time.getTime() ||
                time.getTime() >= new Date(courseTimer + " 00:00:00").getTime()
              );
            } else {
              return new Date(timer).getTime() > time.getTime();
            }
          } else {
            return time.getTime() + 86400000 <= new Date().getTime();
          }
        }
      };
    },
    startBigin() {
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          // return time.getTime() >= Date.now();
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      };
    },
    onScrollError() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("is-error");
        isError[0].scrollIntoView({
          block: "center",
          behavior: "smooth"
        });
      });
    },
    onSingleClassChange(val) {
      // 设置 - 课程时长切换时
      let onlinePrice = null;
      let offLinePrice = null;
      let minus = null;
      this.liveGroupList.forEach(item => {
        if (item.id === val) {
          onlinePrice = item.onlineClassesUnitPrice;
          offLinePrice = item.offlineClassesUnitPrice;
          minus = item.singleClassMinutes;
        }
      });
      this.form.onlineClassesUnitPrice = onlinePrice;
      this.form.offlineClassesUnitPrice = offLinePrice;
      this.form.singleClassMinutes = minus;

      this.form.timeTable = []; // 课表重置
    },
    onConfirm(val) {
      let tempVal = deepClone(val || []);
      tempVal.forEach(item => {
        item.teachingContent = "";
        item.teachingPoint = "";
        item.singleClassMinutes = this.form.singleClassMinutes;
      });
      this.form.timeTable = tempVal;
      console.log(this.form.timeTable, "time table");
      this.$forceUpdate();
    },
    async __init() {
      try {
        const findName = await sysTenantConfigAll({
          group: "LIVE_CLIENT"
        });
        if (findName.data && findName.data.length > 0) {
          findName.data.forEach(item => {
            if (item.paramName == "live_client") {
              this.serviceProvider = item.paranValue;
              this.form.os =
                this.serviceProvider == "tencentCloud" ? "client" : "pc";
            }
          });
        }

        // 获取 指导老师列表
        await getSubject({
          tenantId: 1
        }).then(res => {
          if (res.code == 200) {
            this.subjectList = [...res.data];
          }
        });

        // 获取乐团主管
        await getOrganRole({ all: true }).then(ruselt => {
          this.educationList = ruselt?.data?.EDUCATION;
        });

        // 获取课时数
        // 获取默认左边参数
        await vipGroupCategory({
          groupType: "live"
        }).then(res => {
          if (res.code == 200) {
            this.liveGroupList = res.data;
          }
        });

        // 获取详情
        if (this.id) {
          const query = this.$route.query;
          const { data } = await liveGroupDetail({ id: query.id });
          const liveBroadcastRoom = data.liveBroadcastRoom || {};
          const vipGroupApplyBaseInfo = data.vipGroupApplyBaseInfo || {};
          const courseSchedules = data.courseSchedules || [];
          const tempCourse = [];
          courseSchedules.forEach(item => {
            tempCourse.push({
              classDate: item.classDate,
              actualTeacherId: item.teacherId,
              startClassTimeStr: dayjs(item.startClassTime).format("HH:mm"),
              endClassTimeStr: dayjs(item.endClassTime).format("HH:mm"),
              teachMode: "ONLINE",
              id: item.id,
              singleClassMinutes: vipGroupApplyBaseInfo.singleClassMinutes,
              teachingContent: item.teachingContent,
              teachingPoint: item.teachingPoint
            });
          });

          const subjectId = vipGroupApplyBaseInfo.subjectIdList
            ? Number(vipGroupApplyBaseInfo.subjectIdList)
            : "";
          await this.onChangeSubject(subjectId);

          // 初始化数据
          this.form = {
            roomTitle: liveBroadcastRoom.roomTitle, //
            liveRemark: liveBroadcastRoom.liveRemark, // 内容
            organIds: vipGroupApplyBaseInfo.organIdList
              ? vipGroupApplyBaseInfo.organIdList
                  .split(",")
                  .map(item => Number(item))
              : [],
            subjectIdList: subjectId, // 声部
            teacher: liveBroadcastRoom.speakerId, // 指导老师列表
            educationalTeacherId: vipGroupApplyBaseInfo.educationalTeacherId, // 乐团主管
            preTemplate: liveBroadcastRoom.preTemplate, // 模板
            signUpStart: vipGroupApplyBaseInfo.registrationStartTime, // 开始时间
            signUpEnd: vipGroupApplyBaseInfo.paymentExpireDate, // 结束时间
            // signUpTimeList: [
            //   vipGroupApplyBaseInfo.registrationStartTime,
            //   vipGroupApplyBaseInfo.paymentExpireDate
            // ], // 课程购买时间
            onlineClassesNum: vipGroupApplyBaseInfo.onlineClassesNum,
            singleClassMinuteId: vipGroupApplyBaseInfo.vipGroupCategoryId, //时长编号
            singleClassMinutes: vipGroupApplyBaseInfo.singleClassMinutes, // 时长
            onlineClassesUnitPrice:
              vipGroupApplyBaseInfo.onlineClassesUnitPrice, // 售价
            offlineClassesUnitPrice:
              vipGroupApplyBaseInfo.offlineClassesUnitPrice, // 原价
            os: liveBroadcastRoom.os, // 直播设备
            useScene: liveBroadcastRoom.useScene, // 直播场景
            popularizeType: liveBroadcastRoom.popularizeType, // 观看权限信息
            viewMode: liveBroadcastRoom.viewMode,
            roomConfig: liveBroadcastRoom.roomConfig || {
              whether_like: 0,
              whether_chat: 0,
              whether_video: 0,
              whether_mic: 0,
              whether_view_shop_cart: 0
            },
            timeTable: tempCourse, // 排课
            clientType: "TEACHER" // 主讲人身份 默认[老师]
          };

          this.status = data.vipGroupApplyBaseInfo.status;
          this.courseStartDate = data.vipGroupApplyBaseInfo.courseStartDate;
          this.auditStatus = data.vipGroupApplyBaseInfo.auditStatus;
        }
      } catch (e) {
        //
        console.log(e, "e info");
      }
    }
  },
  computed: {
    nowTime() {
      // console.log(that.maskForm.date)
      let str = "06:00:00";
      if (this.maskForm.date == dayjs(new Date()).format("YYYY-MM-DD")) {
        str = dayjs(new Date()).format("HH:mm:ss");
      }

      return str;
    },

    countOnlineClassesUnitPrice() {
      return (
        Math.ceil(
          this.form.onlineClassesNum * this.form.onlineClassesUnitPrice
        ) || 0
      );
    },
    countOfflineClassesUnitPrice() {
      return (
        Math.ceil(
          this.form.onlineClassesNum * this.form.offlineClassesUnitPrice
        ) || 0
      );
    },
    isDisabled() {
      console.log(this.status, this.type, "isDisabled");
      return this.type === "update" && [1, 2].includes(this.status)
        ? true
        : false;
    }
  }
};
</script>
<style lang="scss" scoped>
.chioseWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;

  .chioseItem {
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    margin-right: 10px;
    width: 188px;
    height: 188px;
    cursor: pointer;

    .dotWrap {
      width: 21px;
      height: 21px;
      background: url("../../assets/images/icon_checkbox_default.png") no-repeat
        center;
      background-size: contain;
      display: block;
      position: absolute;
      top: 10px;
      right: 12px;
      overflow: hidden;

      &.checked {
        background: url("../../assets/images/icon_checkbox.png") no-repeat
          center;
        background-size: contain;
      }

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}

::v-deep .el-select > .el-input {
  height: 36px !important;
}

::v-deep .el-input__inner {
  height: 36px !important;
}

::v-deep .el-col-10 .el-form-item__content {
  height: 36px !important;
}

::v-deep .select-all {
  .select {
    .el-input__inner {
      height: 36px !important;
      min-height: 36px !important;
    }
  }

  .btn {
    height: 36px !important;
    min-height: 36px !important;
  }
}
</style>
