<template>
  <div class="app-container">
    <h1>直播信息</h1>
    <div class="form-box">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
        :disabled="$route.query.type === '2' || $route.query.type === '3'"
      >
        <el-form-item label="播放类型" prop="playType">
          <el-select
            v-model="ruleForm.playType"
            placeholder="请选择播放类型"
            :disabled="ruleForm.status === 3"
          >
            <el-option label="直播" :value="1"></el-option>
            <el-option label="录播" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="录播视频"
          prop="fileId"
          v-if="ruleForm.playType === 2"
        >
          <el-upload
            class="upload-demo"
            action="/"
            :limit="1"
            :on-change="handleChange"
            :on-remove="
              () => {
                ruleForm.fileId = null;
              }
            "
            :before-upload="
              rawFile => checkFile(rawFile, ['mp4'], 1024 * 1024 * 1024)
            "
            :http-request="options => myUpload(options)"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传mp4文件，且不超过1G
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频形式" prop="playStyle">
          <el-radio-group v-model="ruleForm.playStyle">
            <el-radio :label="1" :disabled="!openPortraitScreen">竖屏</el-radio>
            <el-radio :label="2">横屏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="本期看点" prop="viewPoint">
          <el-input
            v-model="ruleForm.viewPoint"
            type="textarea"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="详情" prop="detail">
          <vue-editor
            :disabled="$route.query.type === '2' || $route.query.type === '3'"
            v-model="ruleForm.detail"
            useCustomImageHandler
            @image-added="handleImageAdded"
          />
        </el-form-item>
        <el-form-item
          label="计划直播时间"
          prop="time"
          v-if="ruleForm.playType === 1"
        >
          <el-date-picker
            v-model="time"
            prop="time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
          <p class="tip">
            若设置当天的直播时间，直接点击开始时间，系统自动填充当天的日期，若设置非当天的直播时间，需先选择日期再选择时间进行配置
          </p>
        </el-form-item>
        <!-- 讲师设置 -->
        <el-form-item label="讲师设置" prop="teacherId">
          <adviser-select
            v-model="ruleForm.teacherId"
            :dept-id="user.user.deptId"
            :disabled="
              !(
                $route.query.isZj === '1' ||
                ($route.query.type === '2' || $route.query.type === '3')
              ) || !!ruleForm.id
            "
            @init="
              item => {
                ruleForm.teacherId = item.id;
              }
            "
            @change="
              () => {
                ruleForm.serialIds = [];
                ruleForm.courseIds = [];
                getLastPush(ruleForm.teacherId);
              }
            "
          ></adviser-select>
        </el-form-item>
        <el-form-item
          label="回放有效期设置"
          prop="replayExpireDays"
          v-if="ruleForm.playType === 1"
        >
          <el-radio-group v-model="ruleForm.setReplayExpireDays">
            <el-radio :label="1">永久有效</el-radio>
            <el-radio :label="2">直播结束后</el-radio>
          </el-radio-group>
          <el-input-number
            v-if="ruleForm.setReplayExpireDays === 2"
            v-model="ruleForm.replayExpireDays"
            :min="1"
            size="small"
          ></el-input-number>
          <span v-if="ruleForm.setReplayExpireDays === 2">天内有效</span>
        </el-form-item>
        <div v-if="ruleForm.playType === 1">
          <el-form-item label="嘉宾设置">
            <!-- type=2为查看，这时候filterSelf传2，就不要过滤掉自己了 -->
            <adviser-select
              v-model="ruleForm.mixQuery.guestId"
              :dept-id="user.user.deptId"
              :filterSelf="$route.query.type === '2' ? 2 : 1"
            ></adviser-select>
          </el-form-item>
          <el-form-item
            label="嘉宾展示区域"
            prop="mixQuery.templateId"
            v-if="ruleForm.mixQuery.guestId"
          >
            <div class="flex">
              <el-select
                v-model="ruleForm.mixQuery.templateId"
                placeholder="请选择嘉宾展示区域"
                style="width: 100%;"
              >
                <el-option
                  v-for="(value, key) in mixQueryTemplateObj"
                  :key="key"
                  :label="value"
                  :value="key"
                >
                </el-option>
              </el-select>
              <el-button
                :disabled="!ruleForm.mixQuery.templateId"
                type="text"
                @click="lookTemp"
                >查看示例</el-button
              >
            </div>
          </el-form-item>
        </div>

        <!-- 所属合集 -->
        <el-form-item label="所属合集">
          <serial-select
            ref="serialSelect"
            v-model="ruleForm.serialIds"
            :dept-id="user.user.deptId"
            :advisor-id="ruleForm.teacherId"
            multiple
          ></serial-select>
        </el-form-item>
        <!-- 所属课程 -->
        <el-form-item label="所属课程">
          <course-select
            ref="courseSelect"
            v-model="ruleForm.courseIds"
            :dept-id="user.user.deptId"
            :advisor-id="ruleForm.teacherId"
            multiple
          ></course-select>
        </el-form-item>
        <el-form-item label="详情封面" prop="imgUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :headers="headers"
            action="/admin/common/file/upload"
            :before-upload="beforeUpload"
          >
            <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpeg/png文件，且不超过1MB，建议尺寸750*420px或16:9
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="列表封面" prop="listCoverUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :on-error="handleError"
            :headers="headers"
            action="/admin/common/file/upload"
            :before-upload="beforeUpload"
          >
            <img
              v-if="ruleForm.listCoverUrl"
              :src="ruleForm.listCoverUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpeg/png文件，且不超过1MB，建议尺寸166*224px或者3:4
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="观看限制" prop="limitType">
          <el-radio-group v-model="ruleForm.limitType">
            <el-radio :label="1">无限制</el-radio>
            <el-radio :label="3">邀请码观看</el-radio>
            <el-radio :label="6">权限判定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.limitType === 6"
          label="权限号"
          prop="authIds"
          key="authIds"
        >
          <el-input
            v-model="ruleForm.authIds"
            placeholder="请输入权限号，多个权限号可通过逗号区分(最多4个)"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="ruleForm.limitType === 5">
          <el-select
            v-model="ruleForm.productType"
            clearable
            placeholder="请选择产品类型"
            style="margin-right:20px"
          >
            <el-option
              v-for="(item, index) in productTypeList"
              :key="index"
              :label="item.productName"
              :value="item.productType"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="ruleForm.productId"
            style="margin-right:20px"
            filterable
            remote
            reserve-keyword
            placeholder="请选择需要关联的产品"
            :remote-method="remoteMethodProductTwo"
            :loading="loadingProductTwo"
          >
            <el-option
              v-for="item in productListTwo"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.limitType === 3"
          label="邀请码"
          prop="inviteCode"
          key="inviteCode"
        >
          <el-input
            v-model="ruleForm.inviteCode"
            maxlength="4"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="是否配置购物车" prop="isCart">
          <el-radio-group v-model="ruleForm.isCart">
            <el-radio :label="2">不配置</el-radio>
            <el-radio :label="1">配置</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- c端添加H5按钮 -->
        <el-form-item v-if="ruleForm.isCart === 1" prop="cartList">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加自定义产品</el-button
          >
          <el-table :data="ruleForm.cartList" size="mini" style="width: 100%">
            <el-table-column label="产品名称" prop="productName" width="100">
            </el-table-column>
            <el-table-column prop="url" label="产品ID" width="180">
            </el-table-column>
            <el-table-column prop="productDesc" label="产品介绍" width="180">
            </el-table-column>
            <el-table-column prop="" label="封面图">
              <template slot-scope="scope">
                <el-popover placement="right" :width="400" trigger="hover">
                  <img
                    :src="scope.row.coverImgUrl"
                    style="max-height: 200px; max-width: 200px"
                  />
                  <template #reference>
                    <img
                      :src="scope.row.coverImgUrl"
                      style="max-width: 50px;max-height: 50px;"
                    />
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="url" label="产品链接"> </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  @click="midifiCart(scope.row, scope.$index)"
                  type="text"
                  size="small"
                  >修改</el-button
                >
                <el-button
                  @click="deleteShopping(scope.$index, scope.row.id)"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- 个人主页是否展示 -->
        <el-form-item label="个人主页是否展示">
          <el-radio-group v-model="ruleForm.isShow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 互动区展示内容 -->
        <el-form-item label="互动区展示内容">
          <el-radio-group v-model="ruleForm.interactType">
            <el-radio :label="1">全部互动</el-radio>
            <el-radio :label="2">投顾消息</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="是否同步转播"
          v-if="ruleForm.playType === 1"
          prop="rebroadcast"
        >
          <el-radio-group v-model="ruleForm.rebroadcast">
            <el-radio :label="1">否</el-radio>
            <el-radio :label="2">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.rebroadcast === 2 && ruleForm.playType === 1"
          prop="pushList"
        >
          <el-button type="primary" @click="modifiRebroadcast({ type: 0 })"
            >配置转播平台信息</el-button
          >
          <el-table :data="ruleForm.pushList" size="mini" style="width: 100%">
            <el-table-column label="平台名称" width="100">
              <template slot-scope="scope">
                {{ channelFilter(scope.row.channel) }}
              </template>
            </el-table-column>
            <el-table-column prop="pushUrl" label="推流地址" width="180">
            </el-table-column>
            <el-table-column prop="pushParam" label="推流码/秘钥">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  @click="
                    modifiRebroadcast({
                      type: 1,
                      row: scope.row,
                      index: scope.$index
                    })
                  "
                  type="text"
                  size="small"
                  >修改</el-button
                >
                <el-button
                  @click="modifiRebroadcast({ type: 2, index: scope.$index })"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="风险等级">
          <el-select
            v-model="ruleForm.riskLevel"
            placeholder="请选择风险等级"
            clearable
          >
            <el-option label="低风险" :value="1"></el-option>
            <el-option label="中低风险" :value="2"></el-option>
            <el-option label="中风险" :value="3"></el-option>
            <el-option label="中高风险" :value="4"></el-option>
            <el-option label="高风险" :value="5"></el-option>
          </el-select>
          <!-- <p>观看门槛为不限制或手机号登录即可观看的风险等级固定为低风险</p> -->
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="$route.query.type !== '2' || $route.query.type !== '3'"
            type="primary"
            @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
      <el-form
        v-if="$route.query.type === '3'"
        ref="formReview"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="3">通过</el-radio>
            <el-radio :label="4">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.status === 4" label="驳回理由" prop="reason">
          <el-input v-model="form.reason" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <el-button
        v-if="$route.query.type === '3'"
        type="primary"
        @click="review('formReview')"
        >审核</el-button
      >
    </div>
    <el-dialog
      :title="dialogFormTitle"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="cancel()"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        :rules="rulesDialog"
        label-width="80px"
      >
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="dialogForm.productName"
            placeholder="请输入产品名称"
            autocomplete="off"
            maxlength="20"
            clearable
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="产品介绍" prop="productDesc">
          <el-input
            v-model="dialogForm.productDesc"
            type="textarea"
            placeholder="请输入产品介绍"
            autocomplete="off"
            maxlength="100"
            clearable
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImgUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="dialogHandleSuccess"
            :on-error="handleError"
            :headers="headers"
            action="/admin/common/file/upload"
            :before-upload="beforeUpload"
          >
            <img
              v-if="dialogForm.coverImgUrl"
              :src="dialogForm.coverImgUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过1MB，建议尺寸104*140px；在直播间推荐产品后悬浮展示在右下角，若本场直播不涉及推送产品的场景，无需上传该封面图
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品ID" prop="url">
          <el-input
            v-model="dialogForm.url"
            autocomplete="off"
            placeholder="请输入产品ID"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="confirmDialog()">确 定</el-button>
      </div>
    </el-dialog>
    <platformDialog
      ref="platformDialogRef"
      :pushList="ruleForm.pushList"
      :title="platformVisibleTitle"
      :visible="platformVisible"
      @close="cancelPlatform"
      @confirm="confirmPlatformDialog"
    ></platformDialog>
    <el-dialog
      title="嘉宾展示区域示例"
      :visible.sync="templateDialogVisible"
      :modal-append-to-body="false"
      width="500px"
    >
      <img
        class="temp-img"
        :src="templateImgObj[ruleForm.mixQuery.templateId]"
        style="max-width: 100%;max-height: 100%;"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";
import {
  getColumnList,
  save,
  tagList,
  infoGet,
  updateStatus,
  packageList,
  update,
  getLastPush
} from "@/api/videoLive";
import { uploadSign } from "@/api/shortVideo";
import dayjs from "dayjs";
import TcVod from "vod-js-sdk-v6";
import { mapGetters } from "vuex";

import AdviserSelect from "@/views/adviser/components/select";
import CourseSelect from "@/views/course/components/select";
import SerialSelect from "@/views/serial/components/select";
import { fileUpload } from "@/api/upload";
import { channelArr, mixQueryTemplateObj } from "@/utils/options";
import platformDialog from "@/views/liveBroadcast/components/platformDialog";

export default {
  components: {
    AdviserSelect,
    CourseSelect,
    SerialSelect,
    platformDialog
  },
  data() {
    var validateInviteCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入邀请码"));
      }
      const inviteCode = value.toString();
      const isNum = /^\d{4}$/.test(inviteCode);
      if (inviteCode.length !== 4 || isNaN(inviteCode) || !isNum) {
        return callback(new Error("邀请码必须是4位数字"));
      }
      callback();
    };
    var validateURL = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入产品链接"));
      }
      const urlRegex = /^(http|https):\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(\/\S*)?$/;
      if (!urlRegex.test(value)) {
        return callback(new Error("无效的产品链接"));
      }
      callback();
    };

    var validatePushList = (rule, value, callback) => {
      if (!value || !value.length) {
        return callback(new Error("请配置转播平台信息"));
      }
      callback();
    };

    var validateTime = (rule, value, callback) => {
      if (!this.time || !this.time.length) {
        return callback(new Error("请选择计划直播时间"));
      }
      callback();
    };

    var validateReplayExpireDays = (rule, value, callback) => {
      if (
        this.ruleForm.setReplayExpireDays === 2 &&
        !this.ruleForm.replayExpireDays
      ) {
        return callback(new Error("请输入回放有效天数"));
      }
      callback();
    };

    var validateCartList = (rule, value, callback) => {
      if (
        this.ruleForm.isCart === 1 &&
        (!this.ruleForm.cartList || !this.ruleForm.cartList.length)
      ) {
        return callback(new Error("请添加自定义产品"));
      }
      callback();
    };

    var validateTemplateId = (rule, value, callback) => {
      if (this.ruleForm.mixQuery && this.ruleForm.mixQuery.guestId && !value) {
        return callback(new Error("请选择双播模板"));
      }
      callback();
    };

    return {
      mixQueryTemplateObj,
      id: null,
      type: 1, // 1 修改 2 查看 3 审核
      form: {
        status: null,
        reason: "",
        id: null,
        inviteCode: ""
      },
      dialogForm: {
        productName: "",
        productId: "",
        productDesc: "",
        productType: 21,
        url: "",
        coverImgUrl: ""
      },
      ruleForm: {
        title: "",
        playType: 1,
        fileId: "",
        startTime: "",
        endTime: "",
        isColumn: 0,
        viewPoint: "",
        imgUrl: "",
        limitType: 1,
        columnId: null,
        isCart: 2,
        cartList: [],
        productType: 1,
        cartProductType: 1,
        riskLevel: null,
        playStyle: 2,
        interactType: 1,
        isShow: 1,
        teacherId: null,
        listCoverUrl: "",
        detail: "",
        pushList: [],
        rebroadcast: 1,
        setReplayExpireDays: 1,
        replayExpireDays: 0,
        mixQuery: {
          guestId: "",
          templateId: ""
        }
      },
      time: [],
      loading: false,
      loadingTag: false,
      loadingProduct: false,
      productList: [],
      loadingProductTwo: false,
      productListTwo: [],
      tagIdList: [],
      columnList: [],
      options: [],
      optionsTag: [],
      fileList: [],
      productListId: [],
      headers: {
        Authorization: "Bearer " + getToken(),
        "X-File-Size": 0
      },
      productTypeList: [],
      dialogFormTitle: "添加自定义产品",
      dialogFormVisible: false,
      rulesDialog: {
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        productDesc: [
          { required: true, message: "请输入产品介绍", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur"
          }
        ],
        coverImgUrl: [
          { required: true, message: "请上传封面图", trigger: "blur" }
        ],
        url: [{ required: true, message: "请输入产品ID", trigger: "blur" }]
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "请输入驳回理由", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择", trigger: "change" }],
        playType: [
          { required: true, message: "请选择播放类型", trigger: "change" }
        ],
        fileId: [
          { required: true, message: "请上传录播视频", trigger: "change" }
        ],
        inviteCode: [
          { required: true, validator: validateInviteCode, trigger: "blur" }
        ],
        limitType: [
          { required: true, message: "请选择观看限制", trigger: "change" }
        ],
        authIds: [
          { required: true, validator: this.validateTitles, trigger: "blur" }
        ],
        time: [
          {
            required: true,
            validator: validateTime,
            trigger: "change"
          }
        ],
        columnId: [
          { required: true, message: "请选择视频专栏", trigger: "change" }
        ],
        playStyle: [
          { required: true, message: "请选择视频形式", trigger: "change" }
        ],
        isColumn: [{ required: true, message: "请选择", trigger: "change" }],
        viewPoint: [
          { required: true, message: "请填写本期看点", trigger: "blur" }
        ],
        imgUrl: [
          { required: true, message: "请上传详情封面", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "请选择讲师", trigger: "change" }
        ],
        rebroadcast: [
          { required: true, message: "请选择是否同步转播", trigger: "change" }
        ],
        pushList: [
          { required: true, validator: validatePushList, trigger: "change" }
        ],
        isCart: [
          { required: true, message: "请配置转播平台信息", trigger: "change" }
        ],
        cartList: [
          { required: true, validator: validateCartList, trigger: "change" }
        ],
        replayExpireDays: [
          {
            required: true,
            validator: validateReplayExpireDays,
            trigger: "blur"
          }
        ],
        "mixQuery.templateId": [
          { required: true, validator: validateTemplateId, trigger: "blur" }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前时间
          const now = new Date();
          // 减去5分钟（5分钟 = 5 * 60 * 1000 毫秒）
          const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
          return time.getTime() < fiveMinutesAgo.getTime();
        }
      },
      affiliation: {
        type: null,
        dialogVisible: false,
        title: ""
      },
      tableData: [
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄"
        }
      ],
      multipleSelection: [],
      optionsTeacher: [],
      optionsPage: {
        current: 1,
        size: 10,
        total: 0
      },
      collectionList: [],
      courseList: [],
      userType: null,
      platformVisible: false,
      channelArr,
      platformVisibleTitle: "添加转播平台信息",
      templateDialogVisible: false,
      templateImgObj: {
        10: require("@/assets/images/template/10.png"),
        20: require("@/assets/images/template/20.png"),
        30: require("@/assets/images/template/30.png"),
        40: require("@/assets/images/template/40.png")
      },
      openPortraitScreen: window.config.openPortraitScreen
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.time.length && this.ruleForm.playType === 1) {
            this.$message.error("请选择计划时间!");
            return;
          }
          if (this.time[0]) {
            // 使用 Day.js 解析字符串
            const dateTime = dayjs(this.time[0]);

            // 设置小时、分钟和秒为你想要的值（这里将秒设置为00）
            // 注意：dayjs.set('second', 0) 会自动处理小时和分钟的进位问题
            const newDateTime = dateTime.set("second", 0).set("millisecond", 0);
            this.ruleForm.startTime = newDateTime.format("YYYY-MM-DD HH:mm:ss");
          }
          if (this.time[1]) {
            // 使用 Day.js 解析字符串
            const dateTime = dayjs(this.time[1]);

            // 设置小时、分钟和秒为你想要的值（这里将秒设置为00）
            // 注意：dayjs.set('second', 0) 会自动处理小时和分钟的进位问题
            const newDateTime = dateTime.set("second", 0).set("millisecond", 0);
            this.ruleForm.endTime = newDateTime.format("YYYY-MM-DD HH:mm:ss");
          }

          if (this.ruleForm.playType === 2 && !this.ruleForm.fileId) {
            this.$message.error("请上传录播视频!");
            return;
          }
          if (this.ruleForm.isCart === 1 && !this.ruleForm.cartList.length) {
            this.$message.error("请配置购物车产品!");
            return;
          }
          if (
            this.ruleForm.limitType === 3 &&
            !this.ruleForm.inviteCode.trim()
          ) {
            this.$message.error("请填写邀请码!");
            return;
          }
          if (this.ruleForm.imgUrl === "") {
            this.$message.error("请上传封面!");
            return;
          }
          if (
            this.ruleForm.limitType === 5 &&
            (!this.ruleForm.productId || !this.ruleForm.productType)
          ) {
            this.$message.error("请选择需要关联的产品!");
            return;
          }
          if (this.ruleForm.limitType !== 5) {
            this.ruleForm.productId = null;
            this.ruleForm.productType = null;
          }

          if (this.ruleForm.isCart === 1) {
            this.ruleForm.cartList.forEach((item, index) => {
              item.productId = index + 1;
            });
          }
          if (this.ruleForm.limitType === 1) {
            this.ruleForm.limitType === 2;
          }
          // 合集id
          if (this.collectionList.length > 0) {
            this.ruleForm.serialIds = this.collectionList.map(item => item.id);
          }
          // 课程id
          if (this.courseList.length > 0) {
            this.ruleForm.courseIds = this.courseList.map(item => item.id);
          }
          if (this.$route.query.isZj === "1" && !this.ruleForm.teacherId) {
            this.$message.error("请选择讲师!");
            return;
          }
          if (this.ruleForm.limitType !== 6) {
            this.ruleForm.authIds = "";
          }
          if (this.ruleForm.limitType !== 3) {
            this.ruleForm.inviteCode = "";
          }
          if (this.ruleForm.rebroadcast === 1 || this.ruleForm.playType !== 1) {
            this.ruleForm.pushList = [];
          }
          if (this.ruleForm.mixQuery && !this.ruleForm.mixQuery.guestId) {
            this.ruleForm.mixQuery = null;
          }
          if (this.id && !this.$route.query.isCopy) {
            this.ruleForm.videoId = this.id;
            update(this.ruleForm).then(data => {
              if (data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                this.$router.go(-1);
              }
            });
          } else {
            save(this.ruleForm).then(data => {
              if (data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                if (this.$route.query.isZj === "1") {
                  this.$router.push("/liveBroadcast/liveBroadcastListZj");
                } else {
                  this.$router.push("/liveBroadcast/liveBroadcastList");
                }
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleSuccess(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      setTimeout(() => {
        this.ruleForm.imgUrl = response.data.url;
      }, 100);
      this.$notify({
        title: "详情封面上传成功",
        type: "success",
        duration: 2500
      });
    },
    handleCoverSuccess(response, file, fileList) {
      this.$set(this.ruleForm, "listCoverUrl", response.data.url);
      this.$notify({
        title: "列表封面上传成功",
        type: "success",
        duration: 2500
      });
    },
    dialogHandleSuccess(response) {
      this.dialogForm.coverImgUrl = response.data.url;
    },
    beforeUpload(file) {
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("上传只支持jpeg格式和png格式!");
        return false;
      }
      const isLt = file.size / 1024 < 1024;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 1MB!");
      }
      this.headers["X-File-Size"] = file.size;
      return isLt;
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message);
      this.$notify({
        title: msg.message,
        type: "error",
        duration: 2500
      });
    },
    remoteMethod(query) {
      if (this.ruleForm.isColumn === 1 || !query) {
        this.loading = true;
        const queryParams = {
          columnName: query,
          current: 1,
          size: 99,
          status: 3
        };
        getColumnList(queryParams).then(data => {
          this.options = data.data.list;
          this.loading = false;
        });
      } else {
        this.options = [];
      }
    },
    remoteMethodTag(query) {
      this.loadingTag = true;
      const queryParams = {
        name: query,
        current: 1,
        size: 99,
        type: 3,
        status: 1
      };
      tagList(queryParams).then(data => {
        this.optionsTag = data.data.list;
        this.loadingTag = false;
      });
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice();
    },
    checkFile(rawFile, type, size) {
      // const limitType = type.includes(
      //   rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
      // )
      if (rawFile.type !== "video/mp4") {
        this.$message.error("上传文件格式有误!");
        return Promise.reject();
      }
      const isLimit = rawFile.size < size;
      if (!isLimit) {
        this.$message.error("上传文件过大!");
        return Promise.reject();
      }
      return Promise.resolve(true);
    },
    myUpload(options) {
      // 视频走腾讯云上传
      return new Promise(resolve => {
        const tcVod = new TcVod({
          getSignature: async () => (await uploadSign()).data
        });
        const uploader = tcVod.upload({
          mediaFile: options.file
        });
        uploader.on("media_progress", info => {
          options.onProgress({
            ...info,
            percent: Number((info.percent * 100).toFixed(1))
          });
        });
        uploader.done().then(doneResult => {
          options.onSuccess({});
          this.ruleForm.fileId = doneResult.fileId;
          this.ruleForm.fileName = options.file.name;
          resolve(doneResult.fileId);
        });
      });
    },
    async getDetail(id) {
      infoGet({ id: id || this.id }).then(res => {
        if (res.code === 0) {
          // 是否专栏
          if (res.data.columnId) {
            res.data.isColumn = 1;
            this.remoteMethod();
            // this.options.push({
            //   name: res.data.columnName,
            //   id: res.data.columnId
            // });
          } else {
            res.data.isColumn = 0;
          }
          // 是否配置购物车
          if (res.data.cartVOList.length) {
            res.data.isCart = 1;
          } else {
            res.data.isCart = 2;
          }
          // 是否录播
          if (res.data.playType === 2) {
            this.fileList = [{ name: res.data.libraryName }];
          }
          if (res.data.cartVOList.length) {
            for (let index = 0; index < res.data.cartVOList.length; index++) {
              res.data.cartVOList[index].id =
                res.data.cartVOList[index].productId;
              res.data.cartVOList[index].name =
                res.data.cartVOList[index].productName;
            }
            res.data.cartList = res.data.cartVOList;
          } else {
            res.data.cartList = [];
          }
          if (this.isCopy && res.data.startTime) {
            // 计划时间
            this.time = [
              `${dayjs().format("YYYY-MM-DD")} ${
                res.data.startTime.split(" ")[1]
              }`,
              `${dayjs().format("YYYY-MM-DD")} ${
                res.data.endTime.split(" ")[1]
              }`
            ];
          } else if (!this.isCopy && res.data.startTime) {
            // 计划时间
            this.time = [res.data.startTime, res.data.endTime];
          }

          if (res.data.tagVOList.length) {
            // this.optionsTag = res.data.tagVOList;
            res.data.tagIdList = res.data.tagVOList.map(v => {
              return v.id;
            });
          } else {
            // this.optionsTag = [];
            res.data.tagIdList = [];
          }
          if (res.data.limitType === 2) {
            res.data.limitType === 1;
          }
          res.data.isShow = res.data.isDisplay;
          if (res.data.limitType === 6) {
            res.data.authIds = res.data.authIds.join(",");
          }
          res.data.rebroadcast =
            res.data.pushList && res.data.pushList.length ? 2 : 1;
          res.data.replayExpireDays =
            res.data.replayExpireDays === null ? 0 : res.data.replayExpireDays;
          res.data.setReplayExpireDays = res.data.replayExpireDays ? 2 : 1;
          res.data.mixQuery = {
            guestId:
              res.data.mixInfo && res.data.mixInfo.guestId
                ? res.data.mixInfo.guestId
                : "",
            templateId:
              res.data.mixInfo && res.data.mixInfo.templateId
                ? res.data.mixInfo.templateId.toString()
                : ""
          };
          this.ruleForm = res.data;
          if (this.isCopy) {
            this.ruleForm.id = "";
            this.ruleForm.startTime = "";
            this.ruleForm.endTime = "";
          }
          if (!this.ruleForm.teacherId && this.user.advisorInfo) {
            this.ruleForm.teacherId = this.user.advisorInfo.id;
          }
          if (this.ruleForm.courseVOList)
            this.ruleForm.courseIds = this.ruleForm.courseVOList.map(
              item => item.id
            );

          if (this.ruleForm.serialVOList) {
            this.ruleForm.serialIds = this.ruleForm.serialVOList.map(
              item => item.id
            );
          }
          this.$refs.courseSelect.getList();
        } else {
          this.$message({
            type: "error",
            message: "获取直播详情失败!"
          });
        }
      });
    },
    review(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm(`您确定提交审核?`, {
            confirmButtonText: "提交",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.form.id = this.id;
              updateStatus(this.form).then(res => {
                if (res.code === 0) {
                  this.$message({
                    type: "success",
                    message: "操作成功!"
                  });
                  this.$router.push("/liveBroadcast/liveBroadcastManage");
                }
              });
            })
            .catch(() => {});
        }
      });
    },
    remoteMethodProduct(query) {
      this.loadingProduct = true;
      const queryParams = {
        packageName: query,
        current: 1,
        size: 99,
        statusList: [3]
      };
      packageList(queryParams).then(data => {
        this.productList = data.data.list;
        this.loadingProduct = false;
      });
    },
    remoteMethodProductTwo(query) {
      this.loadingProductTwo = true;
      const queryParams = {
        packageName: query,
        current: 1,
        size: 99,
        statusList: [3]
      };
      packageList(queryParams).then(data => {
        this.productListTwo = data.data.list;
        this.loadingProductTwo = false;
      });
    },

    changeItem(e) {
      let item = null;
      for (let index = 0; index < this.productList.length; index++) {
        if (this.productList[index].id === e) {
          item = this.productList[index];
        }
      }
      console.log(item, this.ruleForm.cartList);
      this.ruleForm.cartList.push({
        productId: item.id,
        productType: this.ruleForm.cartProductType,
        name: item.name
      });
    },
    deleteCart(i, id) {
      this.ruleForm.productListId = null;
      this.ruleForm.cartList.splice(i, 1);
    },
    deleteShopping(i) {
      this.ruleForm.cartList.splice(i, 1);
    },
    midifiCart(row, index) {
      this.dialogFormTitle = "修改自定义产品";
      this.dialogFormVisible = true;
      Object.assign(this.dialogForm, row, { index });
    },
    getProductList() {
      const queryParams = {
        packageName: "",
        current: 1,
        size: 99,
        statusList: [3]
      };
      packageList(queryParams)
        .then(data => {
          this.productListTwo = data.data.list;
          this.productList = data.data.list;
        })
        .catch(() => {});
    },
    confirmDialog() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          if (this.dialogForm.index !== undefined) {
            Object.assign(
              this.ruleForm.cartList[this.dialogForm.index],
              this.dialogForm
            );
          } else {
            this.ruleForm.cartList.push(this.dialogForm);
          }
          this.cancel();
        }
      });
    },
    cancel() {
      this.dialogForm = {
        productName: "",
        productDesc: "",
        productType: 21,
        url: "",
        coverImgUrl: ""
      };
      this.dialogFormVisible = false;
      this.dialogFormTitle = "添加自定义产品";
    },
    cancelDialog() {
      this.multipleSelection = [];
      this.affiliation.dialogVisible = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    confirmAffiliation() {
      if (this.affiliation.title === "选择合集") {
        this.collectionList = this.multipleSelection;
      } else {
        this.courseList = this.multipleSelection;
      }
      this.multipleSelection = [];
      this.affiliation.dialogVisible = false;
    },
    validateTitles(rule, value, callback) {
      if (!value || !value.length) {
        return callback(new Error("请输入权限号"));
      }
      var reg = /^(\d+,?)+$/;
      if (!reg.test(value)) {
        return callback(new Error("权限号为纯数字，多个权限号以逗号隔开！"));
      }
      const titles = value.split(",").map(t => t.trim());
      if (titles.length > 4) {
        callback(new Error("只能输入最多 4 个权限号"));
      } else {
        callback();
      }
    },
    handleCloseCollection(id) {
      // 使用 filter 方法找到需要删除的元素的索引
      const index = this.collectionList.findIndex(item => item.id === id);
      if (index !== -1) {
        // 使用 splice 方法移除该元素
        this.collectionList.splice(index, 1);
      }
    },
    handleCloseCourse(id) {
      // 使用 filter 方法找到需要删除的元素的索引
      const index = this.courseList.findIndex(item => item.id === id);
      if (index !== -1) {
        // 使用 splice 方法移除该元素
        this.courseList.splice(index, 1);
      }
    },
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formData = new FormData();
      formData.append("file", file);

      let ret = await fileUpload(formData);
      if (ret && ret.code === 0) {
        const url = ret.data.url; // Get url from response
        Editor.insertEmbed(cursorLocation, "image", url);
        resetUploader();
      }
    },
    async getLastPush(advisorId) {
      let ret = await getLastPush({
        advisorId
      });
      if (ret && ret.code === 0 && ret.data) {
        this.ruleForm.pushList = [
          {
            channel: ret.data.channel,
            pushUrl: ret.data.pushUrl,
            pushParam: ret.data.pushParam,
            isPush: 1
          }
        ];
      }
    },
    channelFilter(value) {
      for (let i = 0; i < this.channelArr.length; i++) {
        if (value === this.channelArr[i].id) {
          return this.channelArr[i].label;
        }
      }
    },
    cancelPlatform() {
      this.platformVisible = false;
    },
    confirmPlatformDialog(dialogPlatformForm) {
      if (this.platformVisibleTitle === "修改转播平台信息") {
        Object.assign(
          this.ruleForm.pushList[dialogPlatformForm.index],
          dialogPlatformForm
        );
      } else {
        this.ruleForm.pushList.push(dialogPlatformForm);
      }
    },
    modifiRebroadcast({ type, row, index }) {
      if (type === 0) {
        this.platformVisibleTitle = "添加转播平台信息";
        this.platformVisible = true;
      } else if (type === 1) {
        this.platformVisibleTitle = "修改转播平台信息";
        this.$refs.platformDialogRef.dialogPlatformForm = Object.assign(
          {},
          row,
          { index }
        );
        this.platformVisible = true;
      } else {
        this.ruleForm.pushList.splice(index, 1);
      }
    },
    lookTemp() {
      this.templateDialogVisible = true;
    }
  },
  async mounted() {
    this.getProductList();
    this.remoteMethodTag();
    this.remoteMethod("");
    this.userType = Number(this.$route.query.userType);
    if (this.$route.query.id) {
      if (this.isCopy) {
        // 复制
        this.id = Number(this.$route.query.id);
        this.getDetail(this.$route.query.id);
      } else {
        this.id = Number(this.$route.query.id);
        this.type = Number(this.$route.query.type);
        this.getDetail();
      }
    } else {
      // 查询上次转推信息
      this.userType === 1 && this.getLastPush(this.user.advisorInfo.id);
    }
    if (!this.ruleForm.teacherId && this.user.advisorInfo) {
      this.ruleForm.teacherId = this.user.advisorInfo.id;
    }
  },
  watch: {
    "ruleForm.limitType"(value) {
      if (value === 2) {
        this.ruleForm.riskLevel = 1;
      }
    },
    "ruleForm.setReplayExpireDays"(value) {
      if (value === 1) {
        this.ruleForm.replayExpireDays = 0;
      }
    },
    "ruleForm.playType"(value) {
      if (value === 2) {
        this.ruleForm.setReplayExpireDays = 1;
        this.ruleForm.mixQuery = {
          guestId: "",
          templateId: ""
        };
      }
    }
  },
  computed: {
    ...mapGetters(["user"]),
    isCopy() {
      return this.$route.query.isCopy;
    }
  }
};
</script>

<style scoped lang="scss">
.form-box {
  width: 60%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.tip {
  margin: 5px 0 0 0;
  line-height: 20px;
  color: red;
}
.flex {
  display: flex;
}
.temp-img {
  width: 100%;
  height: auto;
}
</style>
