<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel" :content="name"></el-page-header>
    </h2>
    <div class="m-core">
      <el-form
        :model="form"
        ref="form"
        label-width="300px"
        :inline="true"
        label-position="left"
      >
        <el-alert
          title="直播课信息"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        ></el-alert>
        <el-row class="row">
          <el-form-item
            label="直播课标题"
            maxlength="12"
            show-word-limit
            prop="roomTitle"
            :rules="[{ required: true, message: '请输入直播课标题' }]"
          >
            <el-input
              placeholder="请输入直播课标题"
              v-model.trim="form.roomTitle"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="主讲人"
            prop="speakerId"
            :rules="[{ required: true, message: '请输入主讲人' }]"
          >
            <el-select
              v-model.trim="form.speakerId"
              collapse-tags
              clearable
              placeholder="请输入主讲人"
              remote
              filterable
              :remote-method="remoteMethod"
              :loading="remoteLoading"
              @change="changeTeacher"
            >
              <el-option
                v-for="item in teacherList"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              >
                <span style="float: left">{{ item.realName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.phone
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="直播开始时间"
            prop="liveStartTime"
            :rules="[{ required: true, message: '请选择直播开始时间' }]"
          >
            <el-date-picker
              v-model="form.liveStartTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              placeholder="请选择直播开始时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            label="直播课内容"
            prop="liveRemark"
            :rules="[{ required: true, message: '请输入直播课内容' }]"
          >
            <el-input
              :rows="3"
              placeholder="请输入直播课内容"
              v-model.trim="form.liveRemark"
              type="textarea"
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            label="预热模板（模板使用与分享宣传图片）"
            prop="preTemplate"
            :rules="[{ required: true, message: '请选择预热模板' }]"
          >
            <el-checkbox-group v-model="checkList" @change="bindCheckBox">
              <div class="chioseWrap">
                <div class="chioseItem" @click="setPreTemplate(1)">
                  <img src="./images/img1.png" alt="" />
                  <!--        v-model="form.preTemplate" -->
                  <div class="remberBox">
                    <div class="wrap"></div>
                    <el-checkbox
                      class="chioseBox"
                      :label="1"
                      :checked="form.preTemplate == 1"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.preTemplate == 1 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
                <div class="chioseItem" @click="setPreTemplate(2)">
                  <img src="./images/img2.png" alt="" />
                  <div class="remberBox">
                    <!--  v-model="form.preTemplate" -->
                      <div class="wrap"></div>
                    <el-checkbox
                      name="2"
                      class="chioseBox"
                      :label="2"
                      :checked="form.preTemplate == 2"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.preTemplate == 2 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
                <div class="chioseItem" @click="setPreTemplate(3)">
                  <img src="./images/img3.png" alt="" />
                  <div class="remberBox">
                      <div class="wrap"></div>
                    <el-checkbox
                      class="chioseBox"
                      :label="3"
                      :checked="form.preTemplate == 3"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.preTemplate == 3 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <el-alert
          title="直播间信息"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        ></el-alert>
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_like"
            label-width="120px"
            class="mline"
            label="允许点赞"
            :rules="[{ required: true, message: '是否允许点赞' }]"
          >
            <el-radio-group v-model="form.roomConfig.whether_like">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_chat"
            label-width="120px"
            class="mline"
            label="允许聊天互动"
            :rules="[{ required: true, message: '是否允许聊天互动' }]"
          >
            <el-radio-group v-model="form.roomConfig.whether_chat">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_video"
            label-width="120px"
            class="mline"
            label="保存直播回放"
            :rules="[{ required: true, message: '是否保存直播回放' }]"
          >
            <el-radio-group v-model="form.roomConfig.whether_video">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <el-row class="row">
        <el-button type="primary" @click="preLook">预览</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-row>
    </div>

    <el-dialog
      title="预览"
      width="415px"
      :close-on-click-modal="false"
      append-to-body
      :visible.sync="preLookVisible"
    >
      <preview :form="form" />
    </el-dialog>
  </div>
</template>
<script>
import preview from "./modals/preview.vue";
import axios from "axios";
import { getToken, getTenantId } from "@/utils/auth";
import { createLiveBroadcast,resetLiveBroadcastRoomList } from "./api";
export default {
  components: { preview },
  data() {
    return {
      name: "新建直播课",
      preLookVisible: false,
      form: {
        roomTitle: "",
        speakerId: "",
        liveStartTime: "",
        liveRemark: "",
        preTemplate: null,
        roomConfig: { whether_like: 1, whether_chat: 1, whether_video: 1 },
        checkList: [],
      },
      remoteLoading: false,
      teacherList: [],
      checkList: [],
    };
  },
  mounted() {
    if (this.$route.query.id) {
      this.name = "修改直播间";
      // console.log()
      this.form = { ...this.$route.query };
      this.form.roomConfig = JSON.parse(this.$route.query.roomConfig);
      console.log(this.form.roomConfig)
      this.remoteMethod(this.$route.query.speakerName);
      this.checkList.push(this.form.preTemplate * 1);
    }
  },
  methods: {
    onCancel() {
      this.$store.dispatch("delVisitedViews", this.$route);
      this.$router.push("/liveClassManager");
    },
    changeTeacher(val){
      this.teacherList.forEach(item=>{
        if(val == item.id){
          this.form.speakerName = item.realName
        }
      })
    },
    preLook() {
      console.log(this.form);
      this.$refs.form.validate((flag) => {
        if (flag) {
          this.preLookVisible = true;
          console.log("预览", this.form);
        }
      });
    },
    setPreTemplate(index) {
      console.log('调用',index)
      this.$set(this.form, "preTemplate", index);
      if (this.checkList.indexOf(index) == -1) {
        this.checkList.push(index);
      } else {
        this.checkList.splice(this.checkList.indexOf(index), 1);
      }
       console.log('调用结束',index)
      this.bindCheckBox();
    },
    remoteMethod(query) {
      this.teacherList = [];
      if (query !== "") {
        this.remoteLoading = true;
        // 发请求搜索
        const url = "/api-auth/user/queryLike";
        const options = {
          method: "get",
          headers: {
            Authorization: getToken(),
            tenantId: getTenantId(),
          },
          params: {
            rows: 9999,
            search: query,
          },
          url,
        };
        this.remoteLoading = true;
        // this.studentList = []
        axios(options).then((res) => {
          this.remoteLoading = false;
          let result = res.data;
          if (result.code == 200) {
            // Array.prototype.splice.apply(this.studentList, result.data.rows);
            if (result.data && result.data.length > 0) {
              result.data.forEach((item) => {
                this.teacherList.unshift(item);
              });
              this.teacherList = this.deweight(this.teacherList, "phone");
            }
            // this.studentList = this.studentList.concat(result.data.rows);
          }
        });
        // queryStudentList({ rows: 100, search: query }).then(res => {
        //   if (res.code == 200) {
        //     this.remoteLoading = false;
        //     this.studentList = this.studentList.concat(res.data.rows);
        //     this.unique(this.studentList, "userId");
        //   }
        // });
      }
    },
    deweight(arr, key) {
      let res = [];
      arr.forEach((item) => {
        let list = [];
        res.forEach((resitem) => {
          list.push(resitem[key]);
        });
        if (list.indexOf(item[key]) === -1) {
          res.push(item);
        }
      });
      return res;
    },
    bindCheckBox() {
      if (this.checkList.length > 1) {
        this.checkList.splice(0, 1);
      }
      this.$set(this.form, "preTemplate", this.checkList[0] || null);
    },
    async submit() {
      if (this.$route.query.id) {
        // 修改
            try {
          const res = await resetLiveBroadcastRoomList(this.form);
          this.$message.success("修改成功");
          this.$store.dispatch("delVisitedViews", this.$route);
          this.$router.push("/liveClassManager");
        } catch (e) {
          console.log(e);
        }
      } else {
        try {
          const res = await createLiveBroadcast(this.form);
          this.$message.success("创建成功");
          this.$store.dispatch("delVisitedViews", this.$route);
          this.$router.push("/liveClassManager");
        } catch (e) {
          console.log(e);
        }
      }
      // createLiveBroadcast
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/.mline {
  .el-form-item__content {
    display: inline-block !important;
  }
}
/deep/.el-form--inline {
  .el-form-item__content {
    display: block;
  }
}
/deep/.el-select {
  width: 300px !important;
}
/deep/.el-date-editor {
  width: 300px !important;
}
/deep/.el-checkbox {
  margin-left: 15px !important;
}
/deep/.el-input {
  position: relative;
  font-size: 14px;
  display: inline-block;
  width: 300px;
}
.row {
  padding-left: 24px;
}
/deep/.el-textarea__inner {
  width: 600px;
}
.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;
    .remberBox {
      .wrap {
        width: 100px;
        height: 100px;
        z-index: 100;
        position: absolute;
        // background-color: red;
      }
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      margin-bottom: 30px;
      padding-top: 10px;
      align-items: center;
      position: relative;
      color: #6d7278;
      font-size: 16px;
      position: absolute;
      top: 1px;
      right: 1px;
      .chioseBox {
        /deep/.el-checkbox__inner {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          &::after {
            height: 8px;
            left: 6px;
            position: absolute;
            top: 3px;
            width: 4px;
          }
        }
      }
      .dotWrap {
        width: 21px;
        height: 21px;
        background: url("../../assets/images/icon_checkbox_default.png")
          no-repeat center;
        background-size: contain;
        margin-right: 8px;
        position: relative;
        overflow: hidden;
        &.checked {
          background: url("../../assets/images/icon_checkbox.png") no-repeat
            center;
          background-size: contain;
        }
      }
    }
  }
}
</style>
