<template>
  <div id="addSection">
    <el-dialog
      :visible.sync="dialogVisible"
      width="900px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">添加节</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogVisible = false"
          />
        </div>
      </div>
      <div>
        <p>
          <el-button :size="size" type="primary" @click="addChapterList"
            >添加</el-button
          >
        </p>
        <div class="heightMax">
          <div v-for="(item, index) in list" :key="index">
            <el-form
              label-width="130px"
              class="elform_style"
              :ref="`listRulesList${index}`"
              :model="list[index]"
              :rules="rules"
            >
              <div class="left_box">
                <el-form-item label="标题前缀">
                  <el-input v-model="item.prefixName"></el-input>
                  <p class="p_style">注：便于检索、归类，以及区分一样的标题</p>
                </el-form-item>
                <el-form-item label="节标题" prop="name">
                  <el-input v-model="item.name"></el-input>
                  <p class="p_style">
                    注：请尽量规范易懂，方便在课程目录表呈现给学员
                  </p>
                </el-form-item>
                <el-form-item label="节类型" prop="sectionType">
                  <el-select
                    clearable
                    v-model="item.sectionType"
                    placeholder="请选择节类型"
                    @change="changesType(index, $event)"
                  >
                    <el-option
                      v-for="(items, indexs) in sectionTypeOptions"
                      :key="indexs"
                      :label="items.label"
                      :value="items.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="item.sectionType"
                  :label="item.sectionType === 1 ? 'URL地址' : '频道号'"
                  prop="url"
                >
                  <el-input
                    v-model="item.url"
                    @blur="
                      item.sectionType === 1 ? getUrlTime(index, $event) : ''
                    "
                  ><el-button :disabled="item.url.length <= 0" slot="append" @click="seeTheVideoFunc(item)">预览</el-button></el-input>
                   
                </el-form-item>
                <div v-if="item.sectionType === 1">
                  <el-form-item label="节时长" prop="durationTime">
                    <el-time-picker
                      value-format="HH:mm:ss"
                      range-separator=":"
                      v-model="item.durationTime"
                      placeholder="请填入节时长"
                      :disabled="item.disabled"
                    >
                    </el-time-picker>
                  </el-form-item>
                </div>
                <div v-if="item.sectionType === 2">
                  <el-form-item label="直播开始时间" prop="liveStartTime">
                    <el-date-picker
                      v-model="item.liveStartTime"
                      type="datetime"
                      placeholder="请选择直播开始时间"
                      value-format="timestamp"
                      @change="changeStartTime(index, $event)"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="直播结束时间" prop="liveEndTime">
                    <el-date-picker
                      v-model="item.liveEndTime"
                      type="datetime"
                      placeholder="请选择直播结束时间"
                      value-format="timestamp"
                      @change="changeEndTime(index, $event)"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="直播时长"
                    v-if="item.liveStartTime && item.liveEndTime"
                  >
                    {{ compTimeOUT(item.liveStartTime, item.liveEndTime) }}
                  </el-form-item>
                </div>
                <el-form-item
                  label="讲师"
                  prop="teacherId"
                  :rules="[
                    {
                      required: item.sectionType === 2 ? true : false,
                      message: '请选择讲师',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-select
                    clearable
                    v-model="item.teacherId"
                    placeholder="请选择讲师"
                  >
                    <el-option
                      v-for="(items, indexs) in teacherList"
                      :key="indexs"
                      :label="items.teacherName"
                      :value="items.teacherId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="clear_style">
                <el-button :size="size" @click="list.splice(index, 1)"
                  >删除</el-button
                >
              </div></el-form
            >
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :disabled="!list.length"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      size: "small",
      dialogVisible: false,
      list: [],
      rules: {
        prefixName: [
          { required: true, message: "请输入标题前缀", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入节标题", trigger: "blur" }],
        sectionType: [
          { required: true, message: "请选择节类型", trigger: "change" },
        ],
        url: [
          { required: true, message: "请输入URL地址/频道号", trigger: "blur" },
        ],
        durationTime: [
          { required: true, message: "请选择节时长", trigger: "change" },
        ],
        liveStartTime: [
          { required: true, message: "请选择直播开始时间", trigger: "change" },
        ],
        liveEndTime: [
          { required: true, message: "请选择直播结束时间", trigger: "change" },
        ],
      },
      sectionTypeOptions: [
        {
          label: "录播",
          value: 1,
        },
        {
          label: "直播",
          value: 2,
        },
      ],
    };
  },
  mounted() {
    this.$api.inquiresystemteacherlist({ status: 1 }).then((res) => {
      this.teacherList = res.rows;
    });
  },
  computed: {
    /**
     * 自动计算直播时长
     */
    compTimeOUT: function () {
      return function (start, end) {
        if (start && end) {
          if (end < start) {
            return "请检查开始与结束的时间范围";
          }
          const asTimes = end / 1000 - start / 1000;
          return this.$methodsTools.secondToDate(asTimes, false);
        } else {
          return "未检测到直播开始时间结束时间，无法计算！";
        }
      };
    },
  },
  methods: {
    /**
     * 查找节时长
     */
    getUrlTime(index, value) {
      var self = this;
      let val = value.target.value;
      const valueUrl = val.replace(/\s/g, "");
      if (valueUrl && valueUrl.length > 30) {
        this.$api
          .inquirepolyvvideo(valueUrl)
          .then((res) => {
            if (res.data.duration) {
              this.$set(this.list[index], "durationTime", res.data.duration);
              this.$set(this.list[index], "disabled", true);
              this.$message.success("已自动录入节时长");
            } else {
              this.$set(this.list[index], "disabled", false);
              this.$message.error("查找不到该节时长，请手动输入节时长");
            }
          })
          .catch((err) => {
            this.$set(this.list[index], "disabled", false);
          });
      }
    },
    /**
     * 直播开始逻辑处理
     */
    changeStartTime(index, time) {
      if (this.list[index].liveEndTime && this.list[index].liveEndTime < time) {
        this.$set(this.list[index], "liveEndTime", "");
        this.$message.warning("直播开始时间不能大于直播结束时间");
        return;
      }
    },
    /**
     * 直播结束逻辑处理
     */
    changeEndTime(index, time) {
      if (
        this.list[index].liveStartTime &&
        this.list[index].liveStartTime > time
      ) {
        this.$set(this.list[index], "liveEndTime", "");
        this.$message.warning("直播结束时间不能小于直播开始时间");
        return;
      }
    },
    /**
     * 修改节类型需要处理的逻辑
     */
    changesType(index, val) {
      let ary = ["url", "durationTime", "liveStartTime", "liveEndTime"];
      for (let i = 0; i < ary.length; i++) {
        this.$set(this.list[index], ary[i], "");
      }
    },
    /**
     * 添加节
     */
    addChapterList() {
      this.list.push({ disabled: false });
    },
    /**
     * 打开页面触发函数
     */
    openBoxs(arr) {
      this.businList = JSON.parse(JSON.stringify(arr));
      this.list = [{}];
      this.dialogVisible = true;
    },
    /**
     * 表单校验
     */
    submitForm() {
      //用Promise.all进行全部form表单的验证
      Promise.all([
        //数组部分的表单，用map返回验证函数的调用
        ...this.list.map((item, index) =>
          this.validateForm(`listRulesList${index}`)
        ),
      ])
        .then((res) => {
          if (res) {
            // 全部表单验证通过
            this.submitForms();
          }
        })
        .catch(() => {
          this.$message.error("请检查必填项是否填写规范");
        });
    },
    validateForm(refs) {
      //获取到form表单的dom，如果是对象直接拿到，如果是数组，就拿第一个
      //elementui对循环的form包装成了数组
      let valiForm = this.$refs?.[refs].validate
        ? this.$refs?.[refs]
        : this.$refs?.[refs][0];
      return new Promise((resolve, reject) => {
        //在Promise里进行验证，如果通过就resolve()
        valiForm.validate((res) => {
          if (res) resolve();
          else reject();
        });
      });
    },
    /**
     * 通过验证提交逻辑
     */
    submitForms() {
      let ary = JSON.parse(JSON.stringify(this.list));
      ary.forEach((item) => {
        if (item.sectionType === 1) {
          item.recordingUrl = item.url;
          item.durationTime = this.$methodsTools.secondFormDate(
            item.durationTime
          );
          delete item.url;
        }
        if (item.sectionType === 2) {
          item.liveUrl = item.url;
          delete item.url;
          item.liveStartTime = this.$methodsTools.time10to13(
            item.liveStartTime,
            1
          );
          item.liveEndTime = this.$methodsTools.time10to13(item.liveEndTime, 1);
          item.durationTime = item.liveEndTime - item.liveStartTime;
        }
        item.businessList = this.businList;
        item.status = 1;
        item.publishStatus = 1;
        item.coverUrl = "oss/images/avatar/20211013/1634097664410_1397766697";
        delete item.disabled;
      });
      this.$api.drCourseSectionaddMore(ary.reverse()).then((res) => {
        this.dialogVisible = false;
        console.log(res.data, "data");
        this.$emit("backData", res.data);
      });
    },
    /**
     * 预览
     */
    seeTheVideoFunc(item) {
      let jsonstr = JSON.parse(JSON.stringify(item));
      if(jsonstr.sectionType === 1){
        jsonstr.recordingUrl = item.url;
      }
      if(jsonstr.sectionType === 2){
        jsonstr.liveUrl = item.url
      }
      this.$parent.$refs.preview.diavosFun(jsonstr);
    },
  },
};
</script>

<style lang="less" scoped>
.elform_style {
  background-color: #eee;
  padding: 10px 10px 0px;
  display: flex;
  margin-bottom: 16px;
  .left_box {
    flex: 1;
  }
  .clear_style {
    flex-shrink: 0;
    width: 80px;
    vertical-align: top;
    text-align: center;
  }
}
.p_style {
  font-size: 12px;
  color: #a4a4a4;
  margin: 0;
}
.heightMax {
  max-height: 600px;
  overflow: auto;
}
</style>
