<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
            class="mline"
            label="直播设备"
            prop="os"
            label-width="130px"
            :rules="[{ required: true, message: '请选择推广类型' }]"
          >
            <el-radio-group v-model="form.os" @input="changeOs">
              <!-- value="rongCloud"></el-option>
              <el-option label="腾讯云" value="tencentCloud" -->
              <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-row>
        <el-row class="row">
          <el-form-item
            class="mline"
            label="直播场景"
            prop="useScene"
            label-width="130px"
            :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-row>
        <el-alert
          title="直播课信息"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        ></el-alert>
        <el-row class="row">
          <el-form-item
            label="直播课标题"
            class="nomb"
            prop="roomTitle"
            :rules="[{ required: true, message: '请输入直播课标题' }]"
          >
            <el-input
              maxlength="10"
              show-word-limit
              placeholder="请输入直播课标题"
              v-model.trim="form.roomTitle"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item
            label="直播方案"
            class="nomb"
            prop="serviceProvider"
            :rules="[{ required: true, message: '请选择直播方案' }]"
          >
            <el-select
              placeholder="请选择直播方案"
              v-model="form.serviceProvider"
              clearable
              @change="
                (value) => {
                  if (value === 'rongCloud') {
                    form.os = 'pc';
                  } else if (value === 'tencentCloud') {
                    form.os = 'client';
                  }
                }
              "
            >
              <el-option label="融云" value="rongCloud"></el-option>
              <el-option label="腾讯云" value="tencentCloud"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item
            label="直播开始时间"
            class="nomb"
            prop="liveStartTime"
            :rules="[{ required: true, message: '请选择直播开始时间' }]"
          >
            <el-date-picker
              v-model="form.liveStartTime"
              :picker-options="pickerOptions"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              placeholder="请选择直播开始时间"
            >
            </el-date-picker>
            <p style="color: red">主讲人可提前30分钟进入直播间准备直播</p>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            label="主讲人身份"
            class="nomb"
            prop="clientType"
            :rules="[{ required: true, message: '请选择直播方案' }]"
          >
            <el-select
              placeholder="请选择主讲人身份"
              v-model="form.clientType"
              :disabled="form.os == 'mobile'"
              clearable
              @change="
                (value) => {
                  form.speakerId = '';
                }
              "
            >
              <el-option label="老师" value="TEACHER"></el-option>
              <el-option label="员工" value="EDUCATION"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="主讲人"
            class="nomb"
            prop="speakerId"
            :rules="[{ required: true, message: '请输入主讲人' }]"
            v-if="form.clientType == 'TEACHER'"
          >
            <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
            v-else
            label="主讲人"
            class="nomb"
            prop="speakerId"
            :rules="[{ required: true, message: '请输入主讲人' }]"
          >
            <el-select
              v-model.trim="form.speakerId"
              collapse-tags
              clearable
              placeholder="请输入主讲人"
              remote
              filterable
              :remote-method="remoteMethodEduc"
              :loading="remoteLoading"
              @change="changeTeacher"
            >
              <el-option
                v-for="item in educationList"
                :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-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
            class="mline"
            label="观看权限信息"
            prop="popularizeType"
            label-width="130px"
            :rules="[{ required: true, message: '请选择推广类型' }]"
          >
            <el-radio-group v-model="form.popularizeType" @change="changeType">
              <el-radio label="ALL">全员</el-radio>
              <el-radio label="PRIVATE">部分</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            v-if="
              form.popularizeType == 'SCHOOL' ||
              form.popularizeType == 'ORGAN' ||
              form.popularizeType == 'TEAM'
            "
            label="分部"
            prop="organIds"
            :rules="[{ required: true, message: '请选择分部' }]"
          >
            <select-all
              v-model.trim="form.organIds"
              filterable
              clearable
              placeholder="请选择分部"
              @change="changeSection"
            >
              <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-row>
        <el-row class="row">
          <el-form-item
            v-if="form.popularizeType == 'SCHOOL'"
            label="合作单位"
            prop="schoolIds"
            :rules="[{ required: true, message: '请选择合作单位' }]"
          >
            <select-all
              v-model.trim="form.schoolIds"
              :disabled="form.organIds.length <= 0"
              filterable
              clearable
              multiple
            >
              <!--   @change="changeSchool" -->
              <el-option
                v-for="(item, index) in cooperationList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </select-all>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            v-if="form.popularizeType == 'TEAM'"
            label="乐团"
            prop="teamIds"
            :rules="[{ required: true, message: '请选择乐团' }]"
          >
            <select-all
              v-model.trim="form.teamIds"
              :disabled="form.organIds.length <= 0"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="(item, index) in teamList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </select-all>
          </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="130px"
            class="mline"
            label="允许点赞"
            :rules="[{ required: true, message: '是否允许点赞' }]"
          >
            <el-radio-group v-model="form.roomConfig.whether_like">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_chat"
            label-width="130px"
            class="mline"
            label="允许聊天互动"
            :rules="[{ required: true, message: '是否允许聊天互动' }]"
          >
            <el-radio-group v-model="form.roomConfig.whether_chat">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_mic"
            label-width="130px"
            class="mline"
            label="允许连麦"
            :rules="[{ required: true, message: '是否允许连麦' }]"
          >
            <el-radio-group v-model="form.roomConfig.whether_mic">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row> -->
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_video"
            label-width="130px"
            class="mline"
            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-row>
        <el-row class="row">
          <el-form-item
            prop="roomConfig.whether_view_shop_cart"
            label-width="130px"
            class="mline"
            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-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,
  getRoomInfo,
  sysTenantConfigAll,
} from "./api";
import { queryByOrganId } from "@/api/systemManage";
import { getTeamList } from "@/api/teamServer";
export default {
  components: { preview },
  data() {
    return {
      name: "新建直播课",
      preLookVisible: false,
      form: {
        organIds: [],
        schoolIds: [],
        teamIds: [],
        roomTitle: "",
        useScene: "NORMAL",
        speakerId: "",
        liveStartTime: "",
        liveRemark: "",
        preTemplate: null,
        popularizeType: "ALL",
        clientType: "TEACHER",
        os: "client",
        roomConfig: {
          whether_like: 0,
          whether_chat: 0,
          whether_video: 0,
          whether_mic: 0,
          whether_view_shop_cart: 0,
        },
        checkList: [],
      },
      serviceProvider: "tencentCloud",
      remoteLoading: false,
      teacherList: [],
      checkList: [],
      cooperationList: [],
      teamList: [],
      isinit: true,
      pickerOptions: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime();
        },
      },
      educationList: [],
    };
  },
  async mounted() {
    this.$store.dispatch("setBranchs");

    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";
          }
        });
      }
    } catch {
      //
    }

    if (this.$route.query.id) {
      // this.name = "修改直播间";
      await this.getDetail();
      // console.log()
      // this.form = {
      //   ...this.$route.query,
      //   organIds: [],
      //   schoolIds: [],
      //   teamIds: [],
      // };
      // this.form.roomConfig = JSON.parse(this.$route.query.roomConfig);

      // if (this.$route.query.popularizeOrgIds) {
      //   this.form.organIds = this.$route.query.popularizeOrgIds
      //     .split(",")
      //     .map((item) => {
      //       return item * 1;
      //     });
      // }
      // this.changeSection(this.form.organIds);
      // if (this.$route.query.popularizeSchoolIds) {
      //   this.form.schoolIds = this.$route.query.popularizeSchoolIds
      //     .split(",")
      //     .map((item) => {
      //       return item * 1;
      //     });
      // }

      // if (this.$route.query.popularizeTeamIds) {
      //   let arr = this.$route.query.popularizeTeamIds.split(",");
      //   this.$set(this.form, "teamIds", arr);
      //   console.log(this.form.teamIds);
      // }

      // // this.form.popularizeType = "SCHOOL";

      // this.remoteMethod(this.$route.query.speakerName);

      // this.checkList.push(this.form.preTemplate * 1);
      // this.isinit = false;
    }

    console.log(this.form, "form");
  },
  methods: {
    changeOs(e) {
      if (e == "mobile") {
        this.form.clientType = "TEACHER";
        this.form.speakerId = "";
      }
    },
    async getDetail() {
      try {
        const res = await getRoomInfo({ roomUid: this.$route.query.roomUid });
        this.name = "修改直播间";
        // console.log()
        this.form = {
          ...res.data,
          organIds: [],
          schoolIds: [],
          teamIds: [],
          catIds: [],
          studentIds: [],
        };
        this.form.roomConfig = JSON.parse(res.data.roomConfig);
        if (res.data.popularizeOrgIds) {
          this.form.organIds = res.data.popularizeOrgIds.split(",").map((item) => {
            return item * 1;
          });
        }

        if (res.data.popularizeSchoolIds) {
          this.form.schoolIds = res.data.popularizeSchoolIds.split(",").map((item) => {
            return item * 1;
          });
        }

        if (res.data.popularizeTeamIds) {
          let arr = res.data.popularizeTeamIds.split(",");
          this.$set(this.form, "teamIds", arr);
        }

        // this.form.popularizeType = "SCHOOL";
        this.changeSection(this.form.organIds);
        if (res.data.clientType == "TEACHER") {
          this.remoteMethod(res.data.speakerName);
        } else {
          this.remoteMethodEduc(res.data.speakerName);
        }

        this.checkList.push(this.form.preTemplate * 1);
        this.isinit = false;
      } catch (e) {
        console.log(e);
      }
    },
    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() {
      this.$refs.form.validate((flag) => {
        if (flag) {
          this.preLookVisible = true;
          console.log("预览", this.form);
        }
      });
    },
    setPreTemplate(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-web/teacher/queryPage";
        const options = {
          method: "get",
          headers: {
            Authorization: getToken(),
            tenantId: getTenantId(),
          },
          params: {
            rows: 9999,
            search: query,
            lockFlag: 0,
            demissionFlag: false,
          },
          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.rows.length > 0) {
              result.data.rows.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");
        //   }
        // });
      }
    },
    remoteMethodEduc(query) {
      this.educationList = [];
      if (query !== "") {
        this.remoteLoading = true;
        // 发请求搜索
        const url = "/api-web/employee/queryEmployByOrganId";
        const options = {
          method: "get",
          headers: {
            Authorization: getToken(),
            tenantId: getTenantId(),
          },
          params: {
            rows: 9999,
            search: query,
            lockFlag: 0,
            demissionFlag: false,
          },
          url,
        };
        this.remoteLoading = true;

        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.rows.length > 0) {
              result.data.rows.forEach((item) => {
                this.educationList.unshift(item);
              });
              this.educationList = this.deweight(this.educationList, "phone");
            }
            // this.studentList = this.studentList.concat(result.data.rows);
          }
        });
      }
    },
    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() {
      this.form.popularizeOrgIds = this.form.organIds.join(",");
      this.form.popularizeSchoolIds = this.form.schoolIds.join(",");
      this.form.popularizeTeamIds = this.form.teamIds.join(",");
      this.$refs.form.validate(async (flag) => {
        if (!flag) return;
        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
    },
    changeType() {
      this.$set(this.form, "organIds", []);
      this.$set(this.form, "schoolIds", []);
      this.$set(this.form, "teamIds", []);
    },
    async changeSection(val) {
      // if (!this.isinit) {
      this.form.schoolIds = [];
      this.form.teamIds = [];
      // }
      if (this.form.popularizeType == "SCHOOL" && val && val.length > 0) {
        let organId = val.join(",");
        try {
          await queryByOrganId({ organId }).then((res) => {
            if (res.code == 200) {
              this.cooperationList = res.data;
            }
          });
        } catch (e) {
          console.log(e);
        }
      }
      if (this.form.popularizeType == "TEAM" && val && val.length > 0) {
        let organId = val.join(",");
        try {
          await getTeamList({ organId, page: 1, rows: 9999 }).then((res) => {
            if (res.code == 200) {
              this.teamList = res.data.rows;
            }
          });
        } catch (e) {
          console.log(e);
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.nomb {
  margin-bottom: 0px !important;
}
::v-deep .mline {
  .el-form-item__content {
    display: inline-block !important;
  }
}
::v-deep .el-form--inline {
  .el-form-item__content {
    display: block;
  }
}
::v-deep .el-select {
  width: 300px !important;
}
::v-deep .el-date-editor {
  width: 300px !important;
}
::v-deep .el-checkbox {
  margin-left: 15px !important;
}
::v-deep .el-input {
  position: relative;
  font-size: 14px;
  display: inline-block;
  width: 300px;
}
.row {
  padding-left: 24px;
}
::v-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 {
        ::v-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>
