<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="25"></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></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>
                <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">
                <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="signUpTimeList" :rules="[{ required: true, message: '请选择课程购买时间' }]">
              <el-date-picker style="width: 100%" v-model="form.signUpTimeList" :picker-options="pickerOptions"
                type="datetimerange" :default-time="['00:00:00', '23:59:59']" range-separator="-"
                start-placeholder="购买开始日期" end-placeholder="购买结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="课时数" prop="onlineClassesNum" :rules="[{ required: true, message: '请输入课时数' }]">
              <el-input v-model="form.onlineClassesNum" placeholder="请输入课时数" maxlength="2" @input="val => {
                  form.val = val.replace(/^[+]{0,1}(\d+)$/g, '');
                }
                " @change="() => {
      form.timeTable = []; // 课表重置
    }
    "></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">
                <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: '请输入现价' }]">
              <el-input v-model="form.onlineClassesUnitPrice" placeholder="请输入现价"
                @keyup.native="keyupEvent($event)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="原价" prop="offlineClassesUnitPrice" :rules="[{ required: true, message: '请输入原价' }]">
              <el-input v-model="form.offlineClassesUnitPrice" placeholder="请输入原价"
                @keyup.native="keyupEvent($event)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-button type="danger" @click="onTimeTable">点击排课</el-button>
        <el-table 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="150px" prop="teachingContent" key="teachingContent">
            <template slot-scope="scope">
              <!-- v-model="form.eclass[scope.$index].courseCurrentPrice" -->
              <el-form-item :prop="'timeTable.' + scope.$index + '.teachingContent'"
                :rules="[{ required: true, message: '请输入内容' }]" style="margin-bottom: 0;">
                <el-input v-model="scope.row.teachingContent" placeholder="请输入内容">
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="技能/知识点掌握" width="220px" prop="teachingPoint" key="teachingPoint">
            <template slot-scope="scope">
              <el-form-item :prop="'timeTable.' + scope.$index + '.teachingPoint'"
                :rules="[{ required: true, message: '请输入技能/知识点掌握' }]" style="margin-bottom: 0;">
                <!-- v-model="scope.row.teachingPoint" -->
                <el-input v-model="form.timeTable[scope.$index].teachingPoint" placeholder="请输入技能/知识点掌握">
                </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">
              <div>{{ scope.row.teachMode | teachMode }}</div>
            </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">
                <!-- 根据不同的模式，显示不同的直播设备 -->
                <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">
                <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">
                <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">
                <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">
                <div class="chioseWrap">
                  <div class="chioseItem" @click="setPreTemplate(1)">
                    <img src="./images/img1.png" alt="" />
                    <i class="dotWrap" :class="form.preTemplate == 1 ? 'checked' : ''"></i>
                  </div>
                  <div class="chioseItem" @click="setPreTemplate(2)">
                    <img src="./images/img2.png" alt="" />
                    <i class="dotWrap" :class="form.preTemplate == 2 ? 'checked' : ''"></i>
                  </div>
                  <div class="chioseItem" @click="setPreTemplate(3)">
                    <img src="./images/img3.png" alt="" />
                    <i class="dotWrap" :class="form.preTemplate == 3 ? 'checked' : ''"></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">重置</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" :signUpTimeList="form.signUpTimeList"
        :onlineCourseNum="form.onlineClassesNum" @close="dialogFormVisible = false" @confirm="onConfirm" />
    </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 { sysTenantConfigAll } from "./api";
import {
  getSubject,
  findTeacherByOrganId,
  getOrganRole
} from "@/api/buildTeam";
import { vipGroupCategory, createVip } from "@/api/vipSeting";
export default {
  components: { preview, addLiveCourse },
  data() {
    return {
      name: "新建直播课",
      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" // 主讲人身份 默认[老师]
      },

      serviceProvider: "tencentCloud", // 直播模式
      subjectList: [], // 声部列表
      teacherList: [], // 指导老师
      educationList: [], // 乐团主管
      liveGroupList: [], // 课时列表
      pickerOptions: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      }
    };
  },
  async mounted() {
    this.$store.dispatch("setBranchs");
    await this.__init();
  },
  methods: {
    async onChangeSubject(val) {
      try {
        this.form.teacher = ""; // 重置指导老师
        // 根据科目id获取相应的老师
        await findTeacherByOrganId({
          subjectIds: val <= 0 ? null : val
        }).then(res => {
          if (res.code == 200) {
            this.teacherList = res.data;
          }
        });
      } catch { }
    },
    onCancel() {
      this.$store.dispatch("delVisitedViews", this.$route);
      this.$router.push("/liveClassManager?tabrouter=2");
    },
    setPreTemplate(index) {
      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,
              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.signUpTimeList[0]).format(
                "YYYY-MM-DD"
              ),
              paymentExpireDate: dayjs(form.signUpTimeList[0]).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");
          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(
        ["signUpTimeList", "onlineClassesNum", "singleClassMinuteId"],
        valid => {
          count += 1;
          if (valid) {
            this.onScrollError();
            return;
          }

          if (count >= 3) {
            this.dialogFormVisible = true;
          }
        }
      );
    },
    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 = [
              {
                id: -1,
                name: "乐理"
              },
              ...res.data
            ];
          }
        });

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

        // 获取课时数
        // 获取默认左边参数
        await vipGroupCategory({
          groupType: "live"
        }).then(res => {
          if (res.code == 200) {
            this.liveGroupList = res.data;
          }
        });
      } catch (e) {
        //
        console.log(e, "e info");
      }
    }
  }
};
</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;
      }
    }
  }
}

::v-deep .el-select>.el-input {
  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>
