<template>
  <div class="yqrange-index-wrapper">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond" :curmbThird="curmbThird":jumPathThird="jumPathThird"></bread-crumb>
    <div class="yqrange-index-content screenSet" id="screenSet">
      <el-row class="step-content">
        <el-col :span="12">
          <div style="color:#666666;font-size:14px;">{{curmbThird}}</div>
          <!--<el-steps :active="active" simple class>-->
            <!--<span class="step-num" :class="{ 'on-step': stepData[0] }">1</span>-->
            <!--<el-step title="基础信息"></el-step>-->
            <!--<span class="step-num" :class="{ 'on-step': stepData[1] }">2</span>-->
            <!--<el-step title="选择范围">2</el-step>-->
          <!--</el-steps>-->
        </el-col>
        <el-col :span="6" :offset="5">
          <el-button size="small" type="primary" @click="complete('formData')">完成</el-button>
        </el-col>
      </el-row>
      <div class="first-step">

        <!--<p class="p-title">基础信息</p>-->
        <el-form  ref="formData"
                  :model="formData"
                  :rules="rules"
                  label-width="150px"
                  label-suffix="："
                  class="basic-form">
          <el-form-item label="直播标题" prop="name">
            <el-col :span="18">
              <el-input
                  size="small"
                  v-model="formData.name"
                  maxlength="20"
                  placeholder="请输入直播标题"
                  style="width:70%;"
              ></el-input>
              <span class="word-num">{{(formData.name).replace(/\s+/g,"").length}}/20</span>
            </el-col>
          </el-form-item>
          <el-form-item label="是否公开" prop="scope">
            <el-radio-group v-model="formData.scope" size="small" @change="changeScope">
              <el-radio label="1">否（仅限圈内人观看）</el-radio>
              <el-radio label="2">是（任何人可观看）</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否收集用户信息" prop="infoCollect" v-if="isCollectShow">
            <el-radio-group v-model="formData.infoCollect" size="small">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是（收集姓名等信息）</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="直播方式" prop="streamType">
            <el-radio-group v-model="formData.streamType" size="small" @change="changeStreamType">
              <el-radio label="1" :disabled="styleEditFlag">网页直播</el-radio>
              <el-radio label="2" :disabled="styleEditFlag">拉流直播</el-radio>
            </el-radio-group>

          </el-form-item>

          <el-form-item label="拉流地址" v-if="pullFlag" class="required-label">
            <el-col :span="18">
            <el-input
              size="small"
              v-model="formData.pullStreamRtmp"
              placeholder="请输入拉流地址"
              style="width:70%;"
              :disabled="styleEditFlag">
              <template slot="prepend">APP</template>
            </el-input>
            </el-col>
            <el-col :span="18">
              <el-input
                size="small"
                v-model="formData.pullStreamHttp"
                placeholder="请输入拉流地址"
                style="width:70%;"
                :disabled="styleEditFlag">
                <template slot="prepend">H5&nbsp;&nbsp;&nbsp;</template>
              </el-input>
            </el-col>

          </el-form-item>


          <el-form-item label="直播开始时间" prop="openTime">
            <el-col :span="6">
            <el-date-picker
              v-model="formData.openTime"
              size="small"
              type="datetime"
              placeholder="请选择直播开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions0"
              :disabled="formData.liveStatus == 2 || formData.liveStatus == 4"
              style="width: 100%;"
            ></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="直播简介"  class="required-label">
              <el-col :span="16">
            <div style="color:#666666;font-size:10px;">直播图片可选择仅文字版，仅图片版或文字版+图片版</div>
            <el-input type="textarea" v-model="formData.textContent" placeholder="请输入直播简介" maxlength="300" rows="4" style="width:80%;"></el-input>
                <span class="word-num">{{(formData.textContent).replace(/\s+/g,"").length }}/300</span>
                <div style="color:#666666;font-size:12px;">文字版</div>
              </el-col>
          <!--<el-col :span="12" class="basic-item-icon" style="margin-top:35px;">-->
              <!--<el-upload-->
                <!--v-model="formData.imageContent"-->
                <!--class="bg-uploader"-->
                <!--action="#"-->
                <!--:show-file-list="false"-->
                <!--:before-upload="beforeUploadPic1"-->
              <!--&gt;-->
                <!--<img-->
                  <!--v-if="formData.imageContent"-->
                  <!--:src="formData.imageContent"-->
                  <!--@mouseover.stop="imgMouseOver1=true"-->
                  <!--class="bg-img"-->
                <!--/>-->
                <!--<img-->
                  <!--v-if="!formData.imageContent"-->
                  <!--class="bg-img"-->
                  <!--src="../../assets/image/small.png"-->
                <!--/>-->
                <!--<div-->
                  <!--class="img-delete"-->
                  <!--v-show="imgMouseOver1"-->
                  <!--@click.stop="deleteImg(1)"-->
                  <!--@mouseout.stop="imgMouseOver1=false"-->
                <!--&gt;-->
                  <!--<i class="el-icon-delete"></i>-->
                <!--</div>-->
                <!--<div class="limit-text">-->
                  <!--<p>限制大小: 2mb</p>-->
                  <!--<p>尺寸：750*（不限高度）</p>-->
                  <!--<p>支持jpeg, png格式</p>-->
                <!--</div>-->
              <!--</el-upload>-->
            <!--<div style="color:#666666;font-size:12px;">图片版</div>-->
          <!--</el-col>-->
          </el-form-item>
          <div class="basic-item-icon">
            <el-form-item label="图片">
              <el-row>
                <el-col :span="24">
                <el-button size="small" type="info" @click="addIntroImage()">+新增图片（可上传5张）</el-button>
                </el-col>
              <el-col :span="16">
                <!--<div v-for="(item, index) in formData.rtcIntroduces.filter(obj=> obj.type === 2)" :key="index" style="margin-left:0px;min-width: 380px;display: flex;align-items: center">-->
                <div v-for="(item, index) in rtcIntroducesImages" :key="index" style="margin-left:0px;min-width: 380px;display: flex;align-items: center">
                <el-upload
                class="bg-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeUploadPic1">
                <img
                  v-if="item.content"
                  :src="item.content"
                  class="bg-img"
                  @click="getIndexIntroduce(index)"/>
                <img
                  v-if="!item.content"
                  class="bg-img"
                  src="../../assets/image/small.png"
                  @click="getIndexIntroduce(index)"/>
              </el-upload>
                <div class="limit-text" style="font-size: 12px;color: #999;margin-left: 10px;margin-top: -10px;">
                  <p>限制大小: 2Mb</p>
                  <p>尺寸:750*（高度<3000）</p>
                  <p>支持jpeg, png格式</p>
                </div>
                  <!--<img-->
                    <!--@click="addIntroImage(index)"-->
                    <!--class="edit-img"-->
                    <!--src="../../assets/image/plus.png"-->
                    <!--v-if="isPreview!=1"-->
                  <!--/>-->
                  <!--<img-->
                    <!--@click="delIntroImage(index)"-->
                    <!--v-if="index >= 1 && isPreview!=1"-->
                    <!--class="edit-img"-->
                    <!--src="../../assets/image/trash.png"-->
                  <!--/>-->
                  <el-button size="danger" @click="delIntroImage(index, item)">删除</el-button>

                </div>
              </el-col>
              </el-row>

            </el-form-item>
            <p class="upload-message" v-if="uploadImgMessage2">请选择直播封面</p>
          </div>

          <div class="basic-item-icon">
            <el-form-item label="直播封面" class="required-label">
              <el-upload
                  v-model="formData.cover"
                  class="bg-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeUploadPic2"
              >
                <img
                    v-if="formData.cover"
                    :src="formData.cover"
                    @mouseover.stop="imgMouseOver2=true"
                    class="bg-img"
                />
                <img
                    v-if="!formData.cover"
                    class="bg-img"
                    src="../../assets/image/small.png"
                />
                <div
                    class="img-delete"
                    v-show="imgMouseOver2"
                    @click.stop="deleteImg(2)"
                    @mouseout.stop="imgMouseOver2=false"
                >
                  <i class="el-icon-delete"></i>
                </div>
                <div class="limit-text">
                  <p>限制大小: 200kb</p>
                  <p>尺寸:160*120</p>
                  <p>支持jpeg, png格式</p>
                </div>
              </el-upload>
            </el-form-item>
            <p class="upload-message" v-if="uploadImgMessage2">请选择直播封面</p>
          </div>
          <div class="basic-item-icon">
            <el-form-item label="直播预告图" class="required-label">
              <el-upload
                  v-model="formData.preImage"
                  class="bg-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeUploadPic3"
              >
                <img
                    v-if="formData.preImage"
                    :src="formData.preImage"
                    @mouseover.stop="imgMouseOver3=true"
                    class="bg-img"
                />
                <img
                    v-if="!formData.preImage"
                    class="bg-img"
                    src="../../assets/image/small.png"
                />
                <div
                    class="img-delete"
                    v-show="imgMouseOver3"
                    @click.stop="deleteImg(3)"
                    @mouseout.stop="imgMouseOver3=false"
                >
                  <i class="el-icon-delete"></i>
                </div>
                <div class="limit-text">
                  <p>限制大小: 500kb</p>
                  <p>尺寸:750*420</p>
                  <p>支持jpeg, png格式</p>
                </div>
              </el-upload>
            </el-form-item>
            <p class="upload-message" v-if="uploadImgMessage3">请选择直播预告图</p>
          </div>
          <el-form-item label="直播角色" v-if="formData.streamType == 1">
            <div style="color:#666666;font-size:10px;">讲师（必填）</div>
            <el-row>
              <el-col :span="10">
                <el-form-item label="姓名" prop="lecturesUserName" label-width="80px">
                  <el-input
                      size="small"
                      v-model="formData.lecturesUserName"
                      placeholder="请输入姓名"
                      style="width:85%;"
                      :disabled="liveEditFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <img style="vertical-align: middle" src="../../assets/image/lianjie_icon.png" />
              </el-col>
              <el-col :span="10">
                <!--<img src="../../assets/image/lianjie_icon.png" />-->
                <el-form-item label="手机号" prop="lecturesPhone" label-width="80px">
                  <el-input maxlength="11"
                            size="small"
                            v-model="formData.lecturesPhone"
                            placeholder="请输入手机号"
                            style="width:85%;"
                            :disabled="liveEditFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="24">
              <div style="color:#666666;font-size:10px;">嘉宾（选填）</div>
            </el-col>
            <div v-for="(item, index) in formData.guests" :key="index">
              <el-row>
                <el-col :span="10">
                  <el-form-item label=" 姓名" label-width="80px">
                    <el-input
                        size="small"
                        v-model="item.username"
                        placeholder="请输入姓名"
                        style="width:85%;"
                        :disabled="guestEditFlag"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="1">
                  <img style="vertical-align: middle" src="../../assets/image/lianjie_icon.png" />
                </el-col>
                <el-col :span="10">
                  <el-form-item label="手机号" label-width="80px">
                    <el-input maxlength="11"
                              size="small"
                              v-model="item.phone"
                              placeholder="请输入手机号"
                              style="width:85%;"
                              :disabled="guestEditFlag"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <img
                      @click="addGuest(index)"
                      class="edit-img"
                      src="../../assets/image/plus.png"
                      v-if="isPreview!=1"
                  />
                  <img
                      @click="delGuest(index)"
                      v-if="index >= 1 && isPreview!=1"
                      class="edit-img"
                      src="../../assets/image/trash.png"
                  />
                </el-col>
              </el-row>
            </div>
            <!--<el-col :span="15">-->
              <!--<p class="err-text" v-if="guestErrFlag"><img src="../../assets/image/err-icon.svg" alt="">{{guestErrText}}</p>-->
            <!--</el-col>-->
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
  import BreadCrumb from "@/components/breadcrumb.vue";
  import { isEmptyUtils, openLoading, closeLoading } from "../../utils/utils";
  import { doUpload, getFilePath } from "../../utils/qiniu-util";
  import { checkMobile } from '../../utils/patients/checkValid';
  import { getRtcInfo } from "../../utils/yqrange/yqrangeApi";
  // import { checkPhone } from "../login.vue";

  let vm = null;
  export default {
    components: {
      BreadCrumb
    },
    data(){
      let checkProjectStr = (rule, value, callback) => {
        if (value.indexOf("\\") != -1) {
          //存在
          callback(new Error("请勿输入字符“ \\ ”"));
        } else if (value.indexOf(".") != -1) {
          callback(new Error("请勿输入字符“ . ”"));
        } else {
          callback();
        }
      };
      return{
        circleId: '',
        curmbFirst: '云鹊小圈',
        curmbSecond: '直播管理',
        curmbThird: '新建直播',// /live-manage?id=
        jumPathThird: '',
        showIntroImageFlag: false,
        introduceIndex: 0,
        isDisabledIns: false,//为了防止上传多图时，点太快图片错位
        //页面展示位置
        isCollectShow: false,
        styleEditFlag: false,// 直播方式是否可以编辑
        liveEditFlag: false,// 直播方式、讲师是否可以编辑
        guestEditFlag: false,// 嘉宾是否可以编辑
        pullFlag: false, // 是否显示拉流地址
        formData: {
          circleId: "",// 圈子ID
          name: '',// 直播名称
          liveStatus: "1", // 直播状态
          streamType: "1", // 直播方式
          pullStreamRtmp: "", //APP拉流地址
          pullStreamHttp: "", //H5拉流地址
          scope: "1",// 直播范围 1-非公开 2-公开
          infoCollect: "0",// 是否采集用户信息 0-否 1-是
          openTime: '',// 直播开始时间
          rtcIntroduces:[],// 直播简介
          cover: '', // 直播封面url 直播第一帧图片
          preImage: '', // 直播预告图url
          textContent: '', // 直播简介文字版
          imageContent: '',// 直播简介图片版
          // imgUrl2: '',
          // imgUrl2More: {},
          // imgUrl3: '',
          // imgUrl3More: {},
          intro:'',
          hostName: '',
          guestName: '',
          hostMobile: '',
          guestMobile: '',
          mobile1: '',
          lecturesUserName: '',
          lecturesPhone: '',
          lecturers: [{
            username: '',
            phone: ''
          }],// 讲师
          guests: [{
            phone: '',
            username: ''
          }] // 嘉宾
        },
        introTextNum: 0,
        rtcIntroducesText:[],
        rtcIntroducesImages: [],
        // imgUrl1: '',
        imgUrl1More: {},
        guestErrFlag: false,
        guestErrText: '嘉宾最多5位！',
        isPreview: 0,
        imgMouseOver1: false,
        uploadImgMessage1: false,//未上传图片，校验提示语
        imgMouseOver2: false,
        uploadImgMessage2: false,
        imgMouseOver3: false,
        uploadImgMessage3:false,
        submitFlag: false,
        pickerOptions0: {
          disabledDate: time => {
            // 在科学计数法中，为了使公式简便，可以用带“E”的格式表示。例如1.03乘10的8次方，可简写为“1.03e8”的形式
            // 一天是24*60*60*1000 = 86400000 = 8.64e7
            // console.log('this.maxDate',this.maxDate)
              return time.getTime() < Date.now() - 8.64e7
          }
        },
        rules: {
          name: [
            { required: true, message: "请输入直播标题", trigger: "blur" },
            {
              min: 2,
              max: 24,
              message: "输入长度为2-24的内容，可包含中英文、数字及特殊符号",
              trigger: "blur"
            },
            { validator: checkProjectStr, trigger: "blur" }
          ],
          streamType: [{
            required: true, message: "请选择直播方式", trigger: 'blur'
          }],

          scope:[
            {required: true}
          ],
          infoCollect: [
            {required: true, message: "请选择是否收集用户信息", trigger: "blur"}
          ],
          openTime: [
            {required: true, message: "请选择直播开始时间", trigger: "blur"}
          ],
          // // 直播简介
          // introduce: [
          //   {required: true, message: "请选择文字版或图片版", trigger: "blur"}
          // ],
          lecturesUserName: [
            {required: true, message: "请输入姓名", trigger: "blur"},
          ],
          // guestName: [
          //   {required: true, message: "请输入姓名", trigger: "blur"},
          // ],
          lecturesPhone: [
            {required: true, message: "请输入手机号", trigger: ['change','blur']},
            {validator: checkMobile, trigger: ['change','blur']}
          ],

          // introduce: [
          //   { required: true, message: "请输入", trigger: "blur" },
          //   {
          //     min: 2,
          //     max: 24,
          //     message: "输入长度为2-24的内容，可包含中英文、数字及特殊符号",
          //     trigger: "blur"
          //   },
          //   { validator: checkProjectStr, trigger: "blur" }
          // ],
        }
      }
    },
    created() {

      // 区分内部用户和外部用户
      let idType = localStorage.getItem('storageIdType');
      this.circleId = this.$route.query.circleId;
      this.formData.circleId = this.circleId;

      this.jumPathThird = '/live-manage?id=' + this.circleId;
    },
    mounted() {
      const rtcId = this.$route.query.rtcId;
      // if(rtcId){
      //   this.curmbThird = "编辑直播";
      // }
      if(rtcId){
        this.curmbThird = "编辑直播";
        this.initRtcInfo(rtcId);
      }
    },

    methods: {
      checkPhone(val) {
        if(!(/^1[3456789]\d{9}$/.test(val))) {
          return false;
        } else {
          return true;
        }
      },
      // 初始化直播
      initRtcInfo(rtcId){
        getRtcInfo({
          rtcId
        }).then((res) => {
          if(res.code == "000000") {
            this.formData = res.data;
            if(this.formData != null){
              // 讲师、嘉宾是否可以编辑
              // //直播状态 1-未开始 2-直播中 3-暂停中 4-已结束 5-回放中目前只能用到1，2，4
              // 预告状态时，所以都可以修改
              if(this.formData.liveStatus == "1"){
                this.styleEditFlag = false;
                this.liveEditFlag = false;// 可以编辑
                this.guestEditFlag = false;
              }
              // 直播中状态时，直播方式、讲师不可修改，其他都可修改
              else if(this.formData.liveStatus == "2"){
                this.styleEditFlag = true;
                this.liveEditFlag = true;// 不可以编辑
                this.guestEditFlag = false;
              }
              // 直播结束状态时，直播方式、讲师、嘉宾不可修改，其他都可修改
              else if(this.formData.liveStatus == "4"){
                this.styleEditFlag = true;
                this.liveEditFlag = true;
                this.guestEditFlag = true;
              }

              if(this.formData.guests == null || this.formData.guests.length == 0){
                this.formData.guests = [{phone: '',username: ''}];
              }
            }
            this.formData.circleId = this.circleId;
            this.initFormData();
            console.log(this.formData);
          }
        }).catch((error) => {
          this.$message({
            message: "请重试",
            type: 'error'
          });
        })
      },
      getIndexIntroduce(index) {
        // if (!this.isDisabledIns) {
        //  if(this.formData.rtcIntroduces != null && this.formData.rtcIntroduces.length == 1){
        //   index = 0;
        // }
        // else if(this.formData.rtcIntroduces != null && this.formData.rtcIntroduces.length > index){
        //     index = index + 1;
        //   }
          this.introduceIndex = index;
        // }else {
        //   this.$message.warning('正在上传，请稍等')
        // }
      },
      //上传直播简介
      beforeUploadPic1(file) {
        let fileLimit = {
          width: 750,
          height: 3000,
          size: 2,
          sizeText: "2Mb",
          key: "imageContent",
          more: "imgUrl1More",
          show: "uploadImgMessage1"
        };
        this.beforeUploadMore(file, fileLimit);
      },
      // 上传直播封面
      beforeUploadPic2(file) {
        let fileLimit = {
          width: 160,
          height: 120,
          size: 0.2,
          sizeText: "200k",
          key: "cover",
          more: "imgUrl2More",
          show: "uploadImgMessage2"
        };
        this.beforeUpload(file, fileLimit);
      },
      // 上传直播预告图
      beforeUploadPic3(file) {
        let fileLimit = {
          width: 750,
          height: 420,
          size: 0.5,
          sizeText: "500k",
          key: "preImage",
          more: "imgUrl3More",
          show: "uploadImgMessage3"
        };
        this.beforeUpload(file, fileLimit);
      },
      //上传图片
      beforeUpload(file, fileLimit) {
        let vm = this;
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < fileLimit.size;
        if (!isJPG && !isPNG) {
          vm.$message.error("图片格式不符合规范，请根据规范上传图片");
          return;
        }
        if (!isLt2M) {
          vm.$message.error("图片大小不符合规范，请根据规范上传图片 ");
          return;
        }
        let _img = new FileReader();
        _img.readAsDataURL(file);
        _img.onload = function(theFile) {
          let image = new Image();
          image.src = theFile.target.result;
          image.onload = function() {
            let _this = this;

            if(fileLimit.key == "imageContent" & _this.width != fileLimit.width){
              vm.$message.error("图片尺寸不符合规范，请根据规范上传图片");
            }
            else if (fileLimit.key != "imageContent" & (_this.width != fileLimit.width || _this.height != fileLimit.height)) {
              vm.$message.error("图片尺寸不符合规范，请根据规范上传图片");
            } else {
              openLoading(vm);
              doUpload(vm, file, getFilePath(file, null), "preview4", "progress1", 1).then(function(path) {
                closeLoading(vm);
                console.log('上传成功后路径',path);
                if (fileLimit.show == "uploadImgMessage1") {
                  vm.uploadImgMessage1 = false;
                } else if (fileLimit.show == "uploadImgMessage2") {
                  vm.uploadImgMessage2 = false;
                }
                else if (fileLimit.show == "uploadImgMessage3") {
                  vm.uploadImgMessage3 = false;
                }
                vm.formData[fileLimit.key] = path.fullPath;
                vm.formData[fileLimit.more] = {
                  attachmentName: path.name,
                  attachmentExt: path.ext,
                  attachmentSize: path.size
                };
                vm.$message.success("上传成功");
              });
            }
          };
        };
        return isJPG && isLt2M;
      },

      beforeUploadMore(file, fileLimit) {
        let vm = this;
        console.log('简介配置图上传前',file)
        if (isEmptyUtils(file)) {
          return;
        }
        vm.isDisabledIns = true;
        // vm.$message.info('开始上传');
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < fileLimit.size
        if (!isJPG && !isPNG) {
          vm.$message.error('上传直播简介图片只能是 JPEG或者png 格式!')
          // vm.isDisabledIns = false;
          return;
        }
        if (!isLt2M) {
          vm.$message.error('图片大小不符合规范，请根据规范上传图片')
          // vm.isDisabledIns = false;
          return;
        }

        var _img = new FileReader()
        _img.readAsDataURL(file)
        _img.onload = function(theFile) {
          let image = new Image();
          image.src = theFile.target.result;
          image.onload = function() {
            let _this = this;
            if ( _this.width != fileLimit.width || _this.height > fileLimit.height) {
              vm.$message.error('图片尺寸不符合规范，请根据规范上传图片');
              // vm.isDisabledIns = false;
              return;
            }else {
              openLoading(vm);
              doUpload(vm,file, getFilePath(file,null), 'preview4', 'progress1', 1).then(function (path) {
                closeLoading(vm);
                // vm.cleatBroadcast.liveIntroduceModel[vm.introduceIndex].content = path.fullPath;
                vm.rtcIntroducesImages[vm.introduceIndex].content = path.fullPath;
                vm.rtcIntroducesImages[vm.introduceIndex].seqNo = vm.introduceIndex+1;
                vm.$message.success('上传成功');
                // vm.isDisabledIns = false;
              });
            }
            // vm.cleatBroadcast.liveIntroduceModel[vm.introduceIndex].content1 = _this.width + '*' + _this.height;

          }
        }
        return false;
      },

      //上传图片
      // beforeUploadMore(file, fileLimit) {
      //   let vm = this;
      //   const isJPG = file.type === "image/jpeg";
      //   const isPNG = file.type === "image/png";
      //   const isLt2M = file.size / 1024 / 1024 < fileLimit.size;
      //   if (!isJPG && !isPNG) {
      //     vm.$message.error("图片格式不符合规范，请根据规范上传图片");
      //     return;
      //   }
      //   if (!isLt2M) {
      //     vm.$message.error("图片大小不符合规范，请根据规范上传图片 ");
      //     return;
      //   }
      //   let _img = new FileReader();
      //   _img.readAsDataURL(file);
      //   _img.onload = function(theFile) {
      //     let image = new Image();
      //     image.src = theFile.target.result;
      //     image.onload = function() {
      //       let _this = this;
      //
      //       if(fileLimit.key == "imageContent" & _this.width != fileLimit.width){
      //         vm.$message.error("图片尺寸不符合规范，请根据规范上传图片");
      //       }
      //       else if (fileLimit.key != "imageContent" & (_this.width != fileLimit.width || _this.height != fileLimit.height)) {
      //         vm.$message.error("图片尺寸不符合规范，请根据规范上传图片");
      //       } else {
      //         openLoading(vm);
      //         doUpload(vm, file, getFilePath(file, null), "preview4", "progress1", 1).then(function(path) {
      //           closeLoading(vm);
      //           console.log('上传成功后路径',path);
      //           if (fileLimit.show == "uploadImgMessage1") {
      //             vm.uploadImgMessage1 = false;
      //           } else if (fileLimit.show == "uploadImgMessage2") {
      //             vm.uploadImgMessage2 = false;
      //           }
      //           else if (fileLimit.show == "uploadImgMessage3") {
      //             vm.uploadImgMessage3 = false;
      //           }
      //           vm.formData[fileLimit.key] = path.fullPath;
      //           vm.formData[fileLimit.more] = {
      //             attachmentName: path.name,
      //             attachmentExt: path.ext,
      //             attachmentSize: path.size
      //           };
      //           vm.$message.success("上传成功");
      //         });
      //       }
      //     };
      //   };
      //   return isJPG && isLt2M;
      // },
      // 直播方式
      changeStreamType(){
         if(this.formData.streamType == 2){
           this.pullFlag = true;
         }
         else {
           this.pullFlag = false;
         }

      },


      // 是否公开
      changeScope(value){
        if(value == 2){
          this.isCollectShow = true;
        }
        else {
          this.isCollectShow = false;
        }
      },

      // 校验拉流地址
      checkpullStream(){
        let flag = true;
        if(this.formData.streamType == "2"){

          // 公开直播，两个拉流地址都需要
          if(this.formData.scope == "2"){
            if(this.formData.pullStreamRtmp == "" && this.formData.pullStreamHttp == ""){
              this.$message.warning("请输入APP拉流地址和H5拉流地址");
              flag = false;
              return flag;
            }
            if(this.formData.pullStreamRtmp == ""){
              this.$message.warning("请输入APP拉流地址");
              flag = false;
              return flag;
            }
            if(this.formData.pullStreamHttp == ""){
              this.$message.warning("请输入H5拉流地址");
              flag = false;
              return flag;
            }
          }
          else {
            if(this.formData.pullStreamRtmp == "" && this.formData.pullStreamHttp == ""){
              this.$message.warning("请输入APP拉流地址或H5拉流地址");
              flag = false;
            }

          }

        }
        return flag;
      },
      // 校验直播简介文字版或图片版
      checkIntroduce(){
        // console.log(this.formData.rtcIntroduces[0].content);
        // console.log(this.formData.rtcIntroduces[1].content);

        let flag = true;
        // if(this.formData.textContent == ""
        //   &  this.formData.imageContent == ""){
        if(this.formData.rtcIntroduces == null || this.formData.rtcIntroduces.length == 0){
          flag = false;
          this.$message.error("直播简介中可选择仅文字版，仅图片版或文字版+图片版");
        }
        return flag;
      },
      // 增加直播简介
      addIntroImage(){
        let length = this.rtcIntroducesImages.length;


        if(length >= 5){
          this.$message.warning("直播简介图片最多支持新增5张图片!");
          return;
        }
        this.showIntroImageFlag = true;
        const item = {
          seqNo: length + 1,
          content: "",
          type: 2 // 文字
        };
          this.rtcIntroducesImages.push(item);

      },
      // 删除直播简介
      delIntroImage(index, item){

        this.rtcIntroducesImages.splice(index, 1);
      },


      //删除图片
      deleteImg(type) {
        if (type == 1) {
          this.formData.imageContent = "";
          this.imgMouseOver1 = false;
        }
        else if (type == 2) {
          this.formData.cover = "";
          this.imgMouseOver2 = false;
        }
        else if (type == 3) {
          this.formData.preImage = "";
          this.imgMouseOver3 = false;
        }
      },
      // 校验直播封面
      checkCover(){
        let flag = true;
        if(this.formData.cover == ""){
          flag = false;
          this.$message.error("请上传直播封面！");
        }

        return flag;
      },
      // 校验直播预告图
      checkPreImage(){
        let flag = true;
        if(this.formData.preImage == ""){
          flag = false;
          this.$message.error("请上传直播预告图！");
        }

        return flag;
      },
      // 校验嘉宾姓名和手机号
      checkGuests(){
        let flag = true;
        if(this.formData.guests != null & this.formData.guests.length >= 1){
          for(let i=0;i<this.formData.guests.length;i++) {

            if(this.formData.guests[i].username == "" & this.formData.guests[i].phone == ""){
               // this.formData.guests.splice(i, 1);
              if(this.submitFlag){
                 this.formData.guests.splice(i, 1);
                 continue;
              }
              else {
                this.$message.error("请输入嘉宾姓名和手机号");
                flag = false;
                break;
              }
            }
            if(this.formData.guests[i].username != "" & this.formData.guests[i].phone == ""){
              this.$message.error("请输入嘉宾'" +  this.formData.guests[i].username + "'的手机号");
              flag = false;
              break;
            }
            else if(this.formData.guests[i].username != "" & this.formData.guests[i].phone != ""){

              if(!this.checkPhone(this.formData.guests[i].phone)){
                this.$message.error("请输入嘉宾'" +  this.formData.guests[i].username + "'的正确手机号");
                flag = false;
                break;
              }
              // 检查讲师和嘉宾手机号是否相同
              if(!this.checkUniquePhone(this.formData.lecturesPhone, this.formData.guests[i].phone)){
                this.$message.error("请输入不同的手机号");
                flag = false;
                break;
              }
              // 检查嘉宾手机号是否相同
              if(this.formData.guests.length > 1){
                for(let j= i + 1;j<this.formData.guests.length;j++) {
                  if(!this.checkUniquePhone(this.formData.guests[i].phone, this.formData.guests[j].phone)){
                    this.$message.error("请输入不同的手机号");
                    flag = false;
                    break;
                  }
                }

              }
            }
            else if(this.formData.guests[i].username == "" & this.formData.guests[i].phone != ""){
              this.$message.error("请输入手机号为'" +  this.formData.guests[i].phone + "'嘉宾的姓名");
              flag = false;
              break;
            }
          }
        }

        return flag;
      },

      checkUniquePhone(phone1, phone2){
        let flag = true;
        if(phone1 != "" & phone2 != "" & phone1 == phone2){
          flag = false;
        }

        return flag;
      },
      // 增加嘉宾
     addGuest(index) {

        if(this.guestEditFlag){
          return;
        }

        this.submitFlag = false;

        if(!this.checkGuests()){
          return;
        }
        if(this.formData.guests != null & this.formData.guests.length >= 5){
          this.$message.error("嘉宾最多5位！");
           // this.guestErrFlag = true;
          //  setTimeout(function () {
          //   this.guestErrFlag = false;
          // }, 3000)
        }
        else {
          this.formData.guests.push({username: "", phone: ""});
          // this.formData.guests.splice(index + 1, 0, "");
        }
      },

      // 删除嘉宾
      delGuest(index) {

        if(this.guestEditFlag){
          return;
        }
        this.formData.guests.splice(index, 1);
      },
      // 封装数据
      initFormData(){
        this.formData.streamType = String(this.formData.streamType);
        this.changeStreamType();

        this.formData.scope = String(this.formData.scope);
        if(this.formData.scope == "2"){
          this.isCollectShow = true;
        }
        this.formData.infoCollect = String(this.formData.infoCollect);
        this.$set(this.formData, 'textContent', "");
        if(this.formData.rtcIntroduces != null){
          this.rtcIntroducesImages = [];
          for(let i=0;i<this.formData.rtcIntroduces.length;i++) {
            if(this.formData.rtcIntroduces[i].type == "1"){
                // this.formData.textContent = this.formData.rtcIntroduces[i].content;
                this.$set(this.formData, 'textContent', this.formData.rtcIntroduces[i].content);
                // break;
            }
            else {
              // this.$set(this.formData, "rtcIntroducesImages", )
              this.rtcIntroducesImages.push(this.formData.rtcIntroduces[i]);
            }
            // else if(this.formData.rtcIntroduces[i].type == "2"){
            //     // this.formData.imageContent = this.formData.rtcIntroduces[i].content;
            //     this.$set(this.formData, 'imageContent', this.formData.rtcIntroduces[i].content);
            // }
          }

          // this.rtcIntroducesImages = this.formData.rtcIntroduces.filter(function (item) {
          //   return item.type == "2";
          // });




        }
        // (formData.textContent).replace(/\s+/g,"").length

        // if(this.formData.textContent == ""){
        //   this.introTextNum = 0;
        // }
        // else {
        //   this.introTextNum
        // }


        // 设置讲师
        if(this.formData.lecturers.length > 0){
          // this.formData.lecturesUserName = this.formData.lecturers[0].username;
          // this.formData.lecturesPhone = this.formData.lecturers[0].phone;
          this.$set(this.formData, 'lecturesUserName', this.formData.lecturers[0].username);
          this.$set(this.formData, 'lecturesPhone', this.formData.lecturers[0].phone);
        }

      },
      // 封装数据
      setFormData(){

        if(this.formData.streamType == "1"){
          this.formData.pullStreamRtmp = "";
          this.formData.pullStreamHttp = "";
        }

        // 直播简介图片版

        if(this.rtcIntroducesImages != null && this.rtcIntroducesImages.length != 0){
          let rtcIntroducesImagesArray = this.rtcIntroducesImages.filter(function (item) {
            return item.content != "";
          });
          if(rtcIntroducesImagesArray != null && rtcIntroducesImagesArray.length != 0){
            // 直播简介图片版
            this.formData.rtcIntroduces = JSON.parse(JSON.stringify(this.rtcIntroducesImages));
          }
          else {
            this.formData.rtcIntroduces = [];
          }
        }
        else {
          this.formData.rtcIntroduces = JSON.parse(JSON.stringify(this.rtcIntroducesImages));

        }

        // 直播简介文字版
        if(this.formData.textContent != null && this.formData.textContent != ""){
          this.rtcIntroducesText = this.formData.rtcIntroduces.filter(function (item) {
            return item.type == "1";
          });
          if(this.rtcIntroducesText.length == 0){
            this.formData.rtcIntroduces.push({type:1,content:this.formData.textContent});
          }
        }

          // this.formData.rtcIntroduces[0].content = this.formData.textContent;
        // 直播简介图片版
        //   this.formData.rtcIntroduces[1].type = 2;
        //   this.formData.rtcIntroduces[1].content = this.formData.imageContent;
        // 设置讲师
        // if(this.formData.lecturers == undefined){
        //   this.formData.lecturers
        // }
        // if(this.formData.lecturers != undefined & this.formData.lecturers.length == 0){
        //
        //   this.formData.lecturers.push({username: this.formData.lecturesUserName, phone: this.formData.lecturesPhone});
        // }
        if(this.formData.lecturesUserName){
          this.formData.lecturers = [{username: this.formData.lecturesUserName,phone: this.formData.lecturesPhone}];
        }
      },

      complete(formName) {
        console.log(this.formData);
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submit();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      //完成
      submit() {

        this.submitFlag = true;
        this.setFormData();
        // 校验拉流地址
        if(!this.checkpullStream()){
          return;
        }
        // 校验直播简介文字版或图片版
        if(!this.checkIntroduce()){
          return;
        }
        // 校验直播封面、预告图
        if(!this.checkCover() || !this.checkPreImage()){
          return;
        }
        // 校验嘉宾姓名和手机号
        if(!this.checkGuests()){
          return;
        }

        if(!this.pullFlag){
          this.formData.pullStreamHttp = "";
          this.formData.pullStreamRtmp = "";
        }

        let req = this.formData;
        openLoading(this);
        this.POST('rtc/liveAdmin', req).then((res) => {
          closeLoading(this);
          if( res.code == '000000') {
            this.$message.success("操作成功");
            this.$router.push({
              path: '/live-manage',
              query: {
                id: this.formData.circleId
              }
            })
          }
          else {
            this.formData.guests = [{
              phone: '',
              username: ''
            }];
            this.$message.error("操作失败，请重试");
          }
        })


      },
    },
  }
</script>
<style lang="scss">
  .yqrange-index-wrapper{
    .yqrange-index-content{
      background: #fff;
      padding: 10px;
      .step-content{
        overflow: hidden;
        height: 60px;
        padding: 15px 0 50px 0;
        border-bottom: 1px solid #efefef;
        .is-text {
          display: none;
        }
        .el-steps--simple {
          background: #fff;
          padding: 10px 8%;
        }
        .step-num {
          display: block;
          margin-top: 1.5px;
          font-size: 12px;
          border: 1px solid #999 !important;
          border-radius: 50%;
          width: 25px;
          height: 18px;
          line-height: 15px;
          text-align: center;
          color: #999;
        }
        .el-step__title.is-wait {
          color: #999;
        }
        .el-step__title.is-process {
          color: #449284;
        }
        .is-finish {
          color: #999 !important;
        }
        .on-step {
          color: #449284;
          border: 1px solid #449284 !important;
        }
      }
      .first-step{
        margin-top: 20px;
        .p-title{
          padding-left: 10px;
          margin-bottom: 15px;
        }
        .basic-item-icon {
          position: relative;
          .require {
            position: absolute;
            left: 67px;
            top: 11px;
            color: #f56c6c;
          }
          .upload-message {
            position: absolute;
            left: 160px;
            top: 105px;
            font-size: 12px;
            color: #f56c6c;
          }
          .img-delete {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 84px;
            height: 100px;
            background: #000;
            opacity: 0.7;
            z-index: 999;
            i {
              color: #fff;
              margin-top: 39px;
              margin-left: 0px;
            }
          }
        }
        .word-num {
          font-size: 12px;
          color: #999;
          padding-top: 5px;
        }
        .line {
          margin-left: 10px;
          width: 20px;
        }
        .bg-uploader {
          height: 100px;
          .bg-img {
            float: left;
            width: 84px;
            height: 100px;
          }
          .limit-text {
            float: left;
            margin-left: 10px;
            margin-top: -10px;
            p {
              font-size: 12px;
              color: #999;
              text-align: left;
            }
          }
        }
        .el-upload__tip {
          position: absolute;
          top: -6px;
          left: 130px;
        }
      }
    }
  }
  .required-label .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }
  .edit-img {
    width: 20px;
    vertical-align: middle;
  }
  .guest-label .el-form-item__label{
    width: 57px;
  }
  </style>
