<template>
  <div class="app-container">
    <div style="padding-bottom: 20px">
        <span v-if="courseName!=null">{{ courseName }}</span>
    </div>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小节名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入小节名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table border v-loading="loading" :data="userCourseVideoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="视频ID" align="center" prop="videoId" />
      <el-table-column label="小节名称" align="center" show-overflow-tooltip prop="title" />
      <el-table-column label="视频文件名称" align="center" show-overflow-tooltip  prop="fileName" >
      </el-table-column>
      <el-table-column label="视频时长" align="center" prop="duration">
          <template slot-scope="{ row }">
              {{ formatDuration(row.duration) }}
          </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="courseSort" />
      <el-table-column label="上传时间" align="center" prop="createTime" />
      <el-table-column label="默认红包" align="center" prop="redPacketMoney" />
      <el-table-column label="公司红包" align="center" prop="companyRedPacketMoney" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >查看</el-button>

          <el-button
            size="mini"
            type="text"
            v-hasPermi="['course:userCourseVideo:edit']"
            @click="updateMoney(scope.row)"
          >设置红包金额</el-button>

<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            @click="openDialog(scope.row)"-->
<!--            v-hasPermi="['course:courseLink:create']"-->
<!--          >生成应急短链</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-drawer
      :with-header="false"
      size="75%"
      :visible.sync="open" append-to-body>
      <userCourseVideoDetails  ref="userCourseVideoDetails" />
    </el-drawer>
    <el-dialog title="设置红包金额" :visible.sync="moneyOpen" width="600px" append-to-body>
      <el-form ref="form"  label-width="100px">
        <el-form-item label="红包金额" prop="corpId">
          <el-input-number v-model="redPacketMoneyForm.redPacketMoney" :min="0.1" :max="200" :step="0.1" ></el-input-number>
        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="生成链接"
      :visible.sync="dialogVisible"
      width="400px"
      @close="resetForm"
      append-to-body
    >
      <div>
        <p style="color: gray;">不传默认以系统参数为准</p>
        <el-form :model="linkForm" label-width="120px">
          <el-form-item label="链接有效时长(天)">
            <el-input
              v-model="linkForm.days"
              placeholder="请输入有效时长"
              type="number"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </el-dialog>
<!--    <el-dialog title="设置红包金额" :visible.sync="moneyOpen" width="600px" append-to-body>-->
<!--      <el-form ref="form"  label-width="100px">-->
<!--        <el-form-item label="红包金额" prop="corpId">-->
<!--          <el-input-number v-model="redPacketMoneyForm.redPacketMoney" :min="0.1" :max="200" :step="0.1" ></el-input-number>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import { updatePacketMoney,getSort,getVideoListByCourseId,delUserCourseVideo,getUserCourseVideo,addUserCourseVideo,updateUserCourseVideo } from "@/api/course/userCourseVideo";
import userCourseVideoDetails from '../../components/course/userCourseVideoDetails.vue';
import { createLinkUrl } from "@/api/course/sopCourseLink";
import { userList } from "@/api/qw/user";

import request from '@/utils/request'

  export default {
    name: "userCourseCatalog",
    components: {
      userCourseVideoDetails
    },
    data() {
      return {
        linkForm:{
          days:null,
          courseId:null,
          videoId:null
        },
        dialogVisible: false, // 控制弹框显示
        //短链
        sortLink:'',
        //课题
        questionBank:{
          title:'',
          open:false,
        },
		    moneyOpen:false,
        videoUrl: "",
        uploadTypeOptions: [
          { dictLabel: "线路一", dictValue: 2 },

          { dictLabel: "线路二", dictValue: 1 },
          { dictLabel: "线路三", dictValue: 3 },
        ],
        uploadLoading:false,
        courseId:null,
        videoName:'',
        title: "",
        redPacketMoneyForm:{
          redPacketMoney:null,
          voidId:null
        },
        // 是否显示弹出层
        open: false,
        uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadHuaWeiObs",
        baseUrl: process.env.VUE_APP_BASE_API,
        typeOptions:[],
        files:[],
        fileList: [],
        // 上传成功后的地址
        videoURL: '',
        // 进度条百分比
        progress: 0,
        // 上传视频获取成功后拿到的fileID【备用】
        fileId: '',
        courseName:null,
        userCourseVideoList:[],
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          courseId:null,
          title:null
        },
        // 显示搜索条件
        showSearch: true,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
          // 表单参数
        form: {},
        // 表单校验
        rules: {
          title: [
            { required: true, message: "小节名称不能为空", trigger: "change" }
          ],
          courseSort: [
            { required: true, message: "排序不能为空", trigger: "change" }
          ],
        }
      }
    },
    created() {
      this.getDicts("sys_course_temp_type").then(response => {
        this.typeOptions = response.data;
      });
    },
    methods: {
      // 打开弹框
      openDialog(row) {
        this.linkForm.courseId = row.courseId;
        this.linkForm.videoId = row.videoId;
        this.dialogVisible = true;
      },
      // 确认按钮操作
      confirm() {
        if (!this.linkForm.days) {
          this.$message.error("请输入有效时长！");
          return;
        }
        this.handleCreateLink();

        // 关闭弹框
        this.dialogVisible = false;
      },
      // 重置表单
      resetForm() {
        this.linkForm={
            days:null,
            courseId:null,
            videoId:null
        }
      },
      handleCreateLink(){
        createLinkUrl(this.linkForm).then(response => {
          if (response.code === 200){
            this.copyLink(response.url);
          }
        });
      },
      copyLink(url) {
        const link = url;
        // navigator clipboard 需要https等安全上下文
        if (navigator.clipboard && window.isSecureContext) {
          // navigator clipboard 向剪贴板写文本
          navigator.clipboard.writeText(link).then(() => {
            this.$message.success('链接已复制到剪贴板');
          });
        } else {
          // document.execCommand('copy') 向剪贴板写文本
          let input = document.createElement('input')
          input.style.position = 'fixed'
          input.style.top = '-10000px'
          input.style.zIndex = '-999'
          document.body.appendChild(input)
          input.value = link
          input.focus()
          input.select()
          try {
            let result = document.execCommand('copy')
            document.body.removeChild(input)
            if (!result || result === 'unsuccessful') {
              this.$message.error('复制失败');
              console.log('复制失败')
            } else {
              this.$message.success('链接已复制到剪贴板');
              console.log('复制成功')
            }
          } catch (e) {
            document.body.removeChild(input)
            alert('当前浏览器不支持复制功能，请检查更新或更换其他浏览器操作')
          }
        }
      },
      formatDuration(seconds) {
        if (seconds === null || seconds === undefined) {
          return '未上传视频'; // 或者您可以根据具体需求返回其他默认值
        }
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;

        const formattedHours = hours > 0 ? hours.toString() + ':' : '';
        const formattedMinutes = minutes.toString().padStart(2, '0');
        const formattedSeconds = remainingSeconds.toString().padStart(2, '0');

        return `${formattedHours}${formattedMinutes}:${formattedSeconds}`;
      },
      getDetails(courseId,courseName) {
        this.courseName = courseName
        this.courseId = courseId;
        this.queryParams.courseId = courseId;
        this.getList();
      },
      getList() {
        this.loading = true;
        getVideoListByCourseId(this.queryParams).then(response => {
          this.userCourseVideoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      updateMoney(row){
        this.redPacketMoneyForm.redPacketMoney=row.companyRedPacketMoney;
        this.redPacketMoneyForm.videoId=row.videoId;

        this.moneyOpen=true;
      },
      submitForm(){

       updatePacketMoney(this.redPacketMoneyForm).then(response => {
          this.msgSuccess("修改成功");
          this.moneyOpen=false;
          this.getList()
          });
      },
      updateMoneycancel(){
        this.moneyOpen=false;
      },

      // 表单重置
      reset() {
        this.form = {
          videoId: null,
          title: null,
          description: null,
          url: null,
          thumbnail: null,
          duration: null,
          createTime: null,
          uploadType:null,
          lineOne:null,
          lineTwo:null,
          lineThree:null,
          fileName:null,
          userId: null,
          cateId: null,
          courseId: null,
          likes: null,
          views: null,
          comments: null,
          status: 0,
          courseSort: 1,
          isHot: null,
          isShow: null,
          isAudit: null,
          auditBy: null,
          auditTime: null,
          updateTime: null,
          source: null,
          isDel: null,
          shares: null,
          tags: null,
          productId: null,
          productJson: null,
          questionBankId:null,
          questionBankList:[],
        };
        this.videoURL = '';
        this.progress=0;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.courseId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleDetails(row) {
        this.open=true;
        setTimeout(() => {
          this.$refs.userCourseVideoDetails.getDetails(row.videoId);
        }, 500);

      }
    }
  }
</script>
<style>
  .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 {
       font-size: 28px;
       color: #8c939d;
       width: 150px;
       height: 150px;
       line-height: 150px;
       text-align: center;
     }

</style>
