<template>
  <div >
    <div style="padding: 12px 12px 10px 22px;">
      <!-- <div style="display: flex;justify-content:flex-start;"> -->
        <!-- <el-row :gutter="5">
          <el-col :span="6">
              <el-cascader placeholder="资源归属" clearable v-model="resOwner" :props="defaultProps" :options="resOwnerListMap"></el-cascader>
          </el-col>
           <el-col :span="4">
            <el-cascader placeholder="内容分类" clearable v-model="sysTypeList" :props="defaultTypeProps" :options="sysTypeListMap"></el-cascader>
          </el-col>
          <el-col :span="4">
              <el-input placeholder="创建人" v-model="params.createUser" @input="inputOn($event)" clearable></el-input>
          </el-col>
          <el-col :span="3">
             <el-input placeholder="名称" v-model="params.keyword" clearable></el-input>
          </el-col>
           <el-col :span="3">
              <el-select v-model="params.status" placeholder="状态" clearable>
                <el-option label="全部" :value="null"></el-option>
                <el-option label="待审核" value="2"></el-option>
                <el-option label="未提交" value="1"></el-option>
                <el-option label="已审核" value="5"></el-option>
                <el-option label="审核未通过" value="3"></el-option>
              </el-select>
          </el-col>
            <el-col :span="4">
              <el-select v-model="params.publish" placeholder="是否发布" clearable>
                <el-option label="全部" :value="null"></el-option>
                <el-option label="已发布" :value="true"></el-option>
                <el-option label="未发布" :value="false"></el-option>
              </el-select>
          </el-col>
          <el-col :span="6" class="sou">
               <el-button type="primary"  @click="searchData()" icon="el-icon-search" >搜索</el-button>
               <el-button icon="el-icon-refresh-right" type="primary" @click="reset">重置</el-button>
          </el-col>
        </el-row> -->
        <div style="display:flex">
          <div style="margin-right:5px">
            <el-cascader placeholder="内容分类" clearable v-model="sysTypeList" :props="defaultTypeProps" :options="sysTypeListMap"></el-cascader>
          </div>
          <div style="margin-right:5px"><el-input placeholder="创建人" v-model="params.createUser" @input="inputOn($event)" clearable></el-input></div>
          <div style="margin-right:5px"><el-input placeholder="名称" v-model="params.keyword" clearable></el-input></div>
          <div style="margin-right:5px">
            <el-select v-model="params.status" placeholder="状态" clearable>
                <el-option label="全部" :value="null"></el-option>
                <el-option label="待审核" value="2"></el-option>
                <el-option label="未提交" value="1"></el-option>
                <el-option label="已审核" value="5"></el-option>
                <el-option label="审核未通过" value="3"></el-option>
              </el-select>
          </div>
          <div style="margin-right:5px">
             <el-select v-model="params.publish" placeholder="是否发布" clearable>
                <el-option label="全部" :value="null"></el-option>
                <el-option label="已发布" :value="true"></el-option>
                <el-option label="未发布" :value="false"></el-option>
              </el-select>
          </div>
          <div style="width:390px">
              <el-button type="primary"  @click="searchData(true)" icon="el-icon-search" >搜索</el-button>
             <el-button icon="el-icon-refresh-right" type="primary" style="margin-left:5px" @click="reset">重置</el-button>
          </div>
        </div>
            <el-row :gutter="20" style="margin-top:10px">
            <!--     ai播放器相关        -->
            <el-col :span="24">
              <!-- <el-button icon="el-icon-folder" type="primary" size="small">导出</el-button> -->
              <el-button class="Create-coures" type="primary" @click="addNewCourse()" icon="el-icon-plus">新建课程</el-button>
              <el-button v-if="aiPermission" type="primary" @click="setLanguage()" icon="el-icon-connection" :disabled="selectedCourses.length === 0">设置语种</el-button>
              <el-button v-if="aiPermission" type="primary" @click="enableAI()" icon="el-icon-switch-button" :disabled="selectedCourses.length === 0">开启AI处理</el-button>
            </el-col >
        </el-row>
    </div>
    <div style="margin-right:30px;">
    <!--     ai播放器相关        -->
      <el-table style="margin:10px 32px 10px 22px;" :data="pageData" border stripe @selection-change="handleSelectionChange">
        <el-table-column v-if="aiPermission" type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column v-if="forChoose" label="选择"  width="80">
          <template slot-scope="scope" v-if="scope.row.published">
              <el-button type="default" size="mini" @click="handleChoose(scope.row)">选择</el-button>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="name" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="previewStyle" @click="viewTopic(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="内容分类" prop="sysType" sortable width="240px">
          <template slot-scope="scope">
            <span>{{sysTypeName(scope.row.sysType1)}}</span>
            <span v-if="scope.row.sysType2 !=''">/{{sysTypeName(scope.row.sysType2)}}</span>
            <span v-if="scope.row.sysType3 !=''">/{{sysTypeName(scope.row.sysType3)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="关键字" :show-overflow-tooltip="true" prop="name" width="200px">
          <template slot-scope="scope">
            {{ scope.row.keywords }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="资源归属" sortable prop="author" width="240px">
          <template slot-scope="scope">
            <span>{{resOwnerName(scope.row.resOwner1)}}</span>
            <span v-if="scope.row.resOwner2 != ''">/{{resOwnerName(scope.row.resOwner2)}}</span>
            <span v-if="scope.row.resOwner3 != ''">/{{resOwnerName(scope.row.resOwner3)}}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="授课方式" prop="type" width="120px">
          <template slot-scope="scope">
            {{ courseType(scope.row.type)}}
          </template>
        </el-table-column> -->
        <el-table-column label="状态" prop="status" width="120px">
          <template slot-scope="scope">
            <!-- 1，未提交 2.已提交 = 未审核 5 已审核 -->
            <span v-if="scope.row.status == 1">未提交</span>
            <span v-if="scope.row.status == 2">待审核</span>
            <span v-if="scope.row.status == 5">已审核</span>
            <span v-if="scope.row.status == 3">审核未通过</span>
          </template>
        </el-table-column>
        <el-table-column label="是否发布" width="130px">
          <template slot-scope="scope">
            {{ scope.row.published == true ? '已发布' : '未发布' }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="sysCreateBy"></el-table-column>
        <el-table-column label="创建时间" prop="sysCreateTime" width="230px" show-overflow-tooltip></el-table-column>
        <el-table-column label="是否停用" width="130px">
          <template slot-scope="scope">
          {{ scope.row.enabled == true ? '启用' : '停用' }}
          </template>
        </el-table-column>
        <el-table-column label="是否置顶" width="130px">
          <template slot-scope="scope">
            {{ scope.row.isTop == true ? '置顶' : '未置顶' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px" fixed="right">
          <template slot-scope="scope" class="btn-gl">
            <!-- 20240621 修改scope.row.isPermission = fasle 时不展示操作按钮-->
            <!--     ai播放器相关        -->
            <el-button v-if="aiPermission && scope.row.isPermission && scope.row.status != 2" type="text" size="mini" @click="setAI(scope.row)">AI设置</el-button>
            <el-button type="text" size="mini" v-if="scope.row.isPermission && scope.row.status == 5 && !scope.row.published" @click="releaseData(scope.row)">发布</el-button>
            <el-button v-if="scope.row.isPermission && pageManage && scope.row.published" @click="showStudent(scope.row)" type="text" size="mini">学员</el-button>
            <el-button v-if="scope.row.isPermission && !forChoose && scope.row.published" @click="showManageStudy(scope.row)" type="text" size="mini">管理</el-button>
            <el-button v-if="scope.row.isPermission && !forChoose && scope.row.status == 2" @click="withdraw(scope.row)" type="text" size="mini">撤回</el-button>
            <el-button v-if="scope.row.isPermission && scope.row.status != 2" type="text" size="mini" @click="editCurriculum(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.isPermission && (scope.row.status != 2 && !scope.row.published) || scope.row.isPermission &&!scope.row.enabled" type="text" size="mini" @click="delItem(scope.row)">删除</el-button>
            <el-dropdown v-if="scope.row.isPermission && scope.row.published" type="text" size="mini" style="margin-left:10px">
              <el-button type="text" size="mini">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="copyCourse(scope.row)">复制</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.published" @click.native="isDisable(scope.row)">{{scope.row.enabled? '停用':'启用'}}</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.published" @click.native="showQrimage(scope.row)">二维码</el-dropdown-item><!--发布之后才可以查看二维码-->
                <el-dropdown-item v-if="scope.row.published" @click.native="setTop(scope.row)">{{scope.row.isTop? '取消置顶':'置顶'}}</el-dropdown-item>

              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <div v-if="pageData.length > 0" style="text-align: center; margin-top:57px">
      <el-pagination  background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageIndex"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.count"
      ></el-pagination>
    </div>
    <div style="height: 100px;"></div>
    <!--邀请审核-->
    <el-dialog custom-class="g-dialog" title="邀请教师审核课程" :visible.sync="inviteTeacher.dlgShow">
      <div style="display: flex;justify-content:flex-start;padding-bottom: 10px;">
        <div style="padding: 0px 5px;"><el-input placeholder="姓名" v-model="inviteTeacher.params.name"></el-input></div>
        <div style="padding: 0px 5px;"><el-button @click="findTeachers()" icon="el-icon-search" type="primary" >搜索</el-button></div>
      </div>
      <div>
        <el-table max-height="500" border :data="inviteTeacher.list" style="width: 100%">
          <el-table-column prop="name" label="姓名" width="180"></el-table-column>
          <el-table-column prop="sex" label="性别"></el-table-column>
          <el-table-column prop="code" label="工号"></el-table-column>
          <el-table-column prop="orgInfo" label="组织"></el-table-column>
          <el-table-column prop="orgInfo" label="选择">
            <template slot-scope="scope">
              <el-radio v-model="scope.row.checked">选择</el-radio>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="inviteTeacher.dlgShow = false">取 消</el-button>
        <el-button type="primary" @click="enSure">确认</el-button>
      </template>
    </el-dialog>
    <!--课程管理-->
    <el-dialog
        custom-class="g-dialog"
        title="课程学习管理"
        width="900px"
        height="900px"
        :visible.sync="manageStudy.dlgShow"
        :close-on-click-modal="false"

        >
      <manager :manageStudyData="manageStudyData" :isShowDialog="manageStudy.dlgShow"></manager>
      <template #footer>
        <el-button @click="manageStudy.dlgShow = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog title="二维码" center :visible.sync="qrcodeShow" @close="closeCode" width="500px">
      <div style="height:250px;display: flex;flex-direction:column;justify-content: space-evenly;align-items: center;">
        <div id="qrcode" ref="qrcode"></div>
        <el-input v-model="pcDetailUrl" id="text"></el-input>
        <el-button type="primary" size="mini" @click="myCopy()">复制链接</el-button>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="qrcodeShow = false">取 消</el-button>
        <el-button type="primary" @click="qrcodeShow = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog title="审核" :visible.sync="dialogVisible" width="900px" custom-class="g-dialog">
      <div v-show="expandDetails">
        <div v-if="examin.detailType == 10"><auditCourse1 :id="examin.examineId"></auditCourse1></div>
        <div v-if="examin.detailType == 20"><auditCourse2 :id="examin.examineId"></auditCourse2></div>
      </div>
      <div style="border-top: 1px solid #eee; background-color: #eee; padding: 5px;">
        <div style="  text-align: center;margin-bottom: 10px;">
          <el-button @click="expandDetails = !expandDetails">{{expandDetails? '详情折叠':'详情展开'}}</el-button>
          <el-button @click="isExamine = 1">直接审核</el-button>
          <el-button @click="isExamine = 2">邀请审核</el-button>
        </div>

        <el-form label-width="80px" v-if="isExamine === 1">
          <el-form-item label="审核">
            <el-radio-group v-model="auditInfo.pass">
              <el-radio :label="true">通过</el-radio>
              <el-radio :label="false">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见"><el-input v-model="auditInfo.remark" type="textarea" rows="3"></el-input></el-form-item>
        </el-form>
        <div v-if="isExamine === 2">
          <div style="display: flex;justify-content:flex-start;padding-bottom: 10px;">
            <div style="padding: 0px 5px;"><el-input placeholder="姓名" v-model="inviteTeacher.params.name"></el-input></div>
            <div style="padding: 0px 5px;"><el-button @click="findTeachers()" icon="el-icon-search" type="primary" >搜索</el-button></div>
          </div>
          <div>
             <el-table v-if="inviteTeacher.list.length !== 0" max-height="500" border :data="inviteTeacher.list" style="width: 100%;margin-bottom: 10px;">
              <el-table-column prop="name" label="姓名" width="180"></el-table-column>
              <el-table-column prop="code" label="工号"></el-table-column>
              <el-table-column prop="orgInfo" label="组织"></el-table-column>
              <el-table-column prop="orgInfo" label="选择">
                <template slot-scope="scope">
                  <el-radio v-model="scope.row.checked">选择</el-radio>
                </template>
              </el-table-column>
            </el-table>
            <div>审核记录：</div>
            <el-table max-height="500" border :data="inviteTeacher.list" style="width: 100%;">
              <el-table-column prop="name" label="姓名" width="180"></el-table-column>
              <el-table-column prop="code" label="工号"></el-table-column>
              <el-table-column prop="orgInfo" label="组织"></el-table-column>
               <el-table-column prop="type" label="审核状态"></el-table-column>
              <el-table-column prop="text" label="备注"></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="examineData()">提交</el-button>
      </span>
    </el-dialog>
    <el-dialog v-if="showDetails" title="课程详情" :visible.sync="showDetails" @close="examin = {};" width="900px" custom-class="g-dialog">
      <div v-show="expandDetails">
        <div v-if="examin.detailType == 10"><auditCourse1 :showTest="true" :isDetails="false" :isShow="false" :id="examin.examineId"></auditCourse1></div>
        <div v-if="examin.detailType == 20"><auditCourse2 :showTest="true" :isDetails="false" :isShow="false" :id="examin.examineId"></auditCourse2></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDetails = false;examin = {};">取 消</el-button>
      </span>
    </el-dialog>
    <div>
      <course-form ref="courseForm" @submitSuccess="searchData" @close="searchData"></course-form>
    </div>

    <!--     ai播放器相关        -->
    <!-- 设置语种弹框 -->
    <el-dialog
      title="AI翻译"
      :visible.sync="languageSetting.dlgShow"
      width="500px"
      :close-on-click-modal="false"
    >
      <div style="margin-bottom: 20px;">
        <div style="margin-bottom: 15px;">请选择课程所支持语种</div>
        <el-select
          v-model="languageSetting.languageCode"
          multiple
          placeholder="请选择语种"
          style="width: 100%;"
        >
          <el-option
            v-for="lang in selectAllLang"
            :key="lang.srclang"
            :label="lang.label"
            :value="lang.srclang"
          ></el-option>
        </el-select>
      </div>
      <div style="color: #ff4d4f; font-size: 12px;">
        注：仅支持对已开启AI处理的课程进行批量语种设置；所选的课程中有{{languageSetting.aiSetNoNum}}个未开启AI处理的课程，以上配置仅对{{languageSetting.aiSetNum}}个已开启AI处理的课程生效。
      </div>
      <template #footer>
        <el-button @click="languageSetting.dlgShow = false">取消</el-button>
        <el-button type="primary" @click="confirmLanguageSetting">确认</el-button>
      </template>
    </el-dialog>

    <!-- 开启AI处理弹框 -->
    <el-dialog
        title="开启AI处理"
        :visible.sync="aiProcessSetting.dlgShow"
        width="400px"
      >
        <div class="ai-process-dialog">
          <!-- AI处理状态 -->
          <div class="form-item">
            <span class="form-label">
              <el-tooltip class="item" effect="dark" :content="aiSetTip" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
              AI处理：
            </span>
            <span class="status-text">
              {{ aiProcessSetting.aiSet === 1 ? '开启' : '关闭' }}
            </span>
            <el-switch
              v-model="aiProcessSetting.aiSet"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </div>

          <div v-show="aiProcessSetting.aiSet === 1">
            <!-- 是否生成AI摘要 -->
            <div class="form-item">
              <span class="form-label">
                <el-tooltip class="item" effect="dark" :content="aiAbstractTip" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                AI摘要：
              </span>
              <span class="status-text">
                {{ aiProcessSetting.aiAbstract === 1 ? '开启' : '关闭' }}
              </span>
              <el-switch
                v-model="aiProcessSetting.aiAbstract"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>

            <!-- 是否生成AI文稿 -->
            <div class="form-item">
              <span class="form-label">
                <el-tooltip class="item" effect="dark" :content="aiDraftTip" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                AI文稿：
              </span>
              <span class="status-text">
                {{ aiProcessSetting.aiDraft === 1 ? '开启' : '关闭' }}
              </span>
              <el-switch
                v-model="aiProcessSetting.aiDraft"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>

            <!-- 课程支持语种选择 -->
            <div class="form-item" style="flex-flow: column;align-items: baseline;">
              <span class="form-label">
                <el-tooltip class="item" effect="dark" :content="aiTranslateTip" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                AI翻译语种：
              </span>
              <el-select
                v-model="aiProcessSetting.languageCode"
                multiple
                style="width: 100%;"
                placeholder="请选择语种"
              >
                <el-option
                  v-for="lang in selectAllLang"
                  :key="lang.srclang"
                  :label="lang.label"
                  :value="lang.srclang"
                ></el-option>
              </el-select>
            </div>
          </div>

          <!-- 提示信息 -->
          <div class="tips">
            <span>注：已跳过{{aiProcessSetting.aiSetNum}}个已开启AI处理的课程，仅更新剩余{{aiProcessSetting.aiSetNoNum}}个</span>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="aiProcessSetting.dlgShow = false">取消</el-button>
          <el-button type="primary" @click="confirmAiProcess">确认</el-button>
        </span>
    </el-dialog>

      <!-- AI设置弹框 -->
      <el-dialog
        title="AI设置"
        :visible.sync="aiSetting.dlgShow"
        width="500px"
      >
        <div class="ai-setting-dialog">

          <!-- AI功能状态 -->
          <div class="form-item">
            <span class="form-label">
              <el-tooltip class="item" effect="dark" content="是否将课程进行AI处理" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
              AI功能状态：
            </span>
            <span class="status-text">
              {{ aiSetting.aiSet === 1 ? '已开放' : '未开放' }}
            </span>
            <el-switch
              v-model="aiSetting.aiSet"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </div>
          <div v-show="aiSetting.aiSet === 1">
            <!-- AI摘要状态 -->
            <div class="form-item">
              <span class="form-label">AI摘要状态：</span>
              <span  :class="aiSetting.aiAbstract === 1 ? 'custom-putaway' : 'custom-takeout'">
                {{ aiSetting.aiAbstract === 1 ? '已上架' : '已下架' }}
              </span>
              <div class="action-buttons">
                <el-button type="text" @click="changeAIKey('aiAbstract')">
                  {{ aiSetting.aiAbstract === 1 ? '下架' : '上架' }}
                </el-button>
                <el-button v-show="isV2" type="text" @click="toAiAbstract">编辑</el-button>
              </div>
            </div>

            <!-- AI文稿状态 -->
            <div class="form-item">
              <span class="form-label">AI文稿状态：</span>
              <span  :class="aiSetting.aiDraft === 1 ? 'custom-putaway' : 'custom-takeout'">
                {{ aiSetting.aiDraft === 1 ? '已上架' : '已下架' }}
              </span>
              <div class="action-buttons">
                <el-button type="text" @click="changeAIKey('aiDraft')">
                  {{ aiSetting.aiDraft === 1 ? '下架' : '上架' }}
                </el-button>
              </div>
            </div>

            <!-- AI翻译状态 -->
            <div class="form-item">
              <span class="form-label">AI翻译状态：</span>
              <span  :class="aiSetting.aiTranslate === 1 ? 'custom-putaway' : 'custom-takeout'">
                {{ aiSetting.aiTranslate === 1 ? '已上架' : '已下架' }}
              </span>
              <div class="action-buttons">
                <el-button type="text" @click="changeAIKey('aiTranslate')">
                  {{ aiSetting.aiTranslate === 1 ? '下架' : '上架' }}
                </el-button>
                <el-button v-show="isV2" type="text" @click="toAiTranslate">编辑</el-button>
              </div>
            </div>

            <!-- 支持语种 -->
            <div class="form-item" style="align-items: flex-start;">
              <span class="form-label" style="white-space: nowrap;">支持语种：</span>
              <div class="languages-list" v-show="false">
                <div v-for="lang in aiSetting.languageCode" :key="lang" class="language-tag">
                  {{ getLanguageName(lang) }}
                  <span class="custom-takeout">已下架</span>
                </div>
              </div>
              <el-select
                v-model="aiSetting.languageCode"
                multiple
                style="width: 100%;"
                placeholder="请选择语种"
              >
                <el-option
                  v-for="lang in selectAllLang"
                  :key="lang.srclang"
                  :label="lang.label"
                  :value="lang.srclang"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="aiSetting.dlgShow = false">取消</el-button>
          <el-button type="primary" @click="confirmAISetting">确认</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import courseForm from '@/components/Course/courseForm.vue';
import manager from '@/components/Study/manager.vue';
import QRCode from 'qrcodejs2';
import auditCourse1 from '@/components/Course/auditCourse1.vue';
import auditCourse2 from '@/components/Course/auditCourse2.vue';
import adminPage from '@/components/Administration/adminPage.vue';
import apiResowner from '../../api/modules/resowner.js';
import apiType from '../../api/modules/type.js'
import {courseType, deepCopy} from '../../utils/tools.js';
import apiCourse from '../../api/modules/course.js';
// import {resOwnerIndexName,sysTypeIndexName} from '@/utils/type.js';
import { mapGetters,mapActions } from 'vuex';
import apiUserbasic from "@/api/boe/userbasic.js"
export default {
  name: 'manageCourse',
  components: {courseForm, manager, auditCourse1, auditCourse2,adminPage},
  // ai播放器相关
  computed: {
      ...mapGetters(['resOwnerMap','sysTypeMap','userInfo', 'selectAllLang']),
  },
  data() {
    return {
      audiences: [],
      forChoose:false,
      pageManage:false,
      showDetails: false,
      examin:{
       detailType: '',
       examineId: '',
       examineName: '',
      },
      paperJson:{items:[]},
      courseType: courseType,
      sysTypeListMap: [],
      sysTypeList:[],
      resOwnerListMap: [],
      page: {
        pageIndex: 1,//第几页
        pageSize: 10, // 每页多少条
        count: 0
      },
      resOwner: [],
      defaultProps:{
        value: 'code',
        label: 'name',
      },
      defaultTypeProps:{
        value: 'id',
        label: 'name',
      },
      manageStudyData: {},
      expandDetails: true,
      qrcode: '',
      pcDetailUrl:'',
      isExamine: 1,
      auditInfo: {
        pass: true,
        remark: ''
      },
      dialogVisible: false,
      qrcodeShow: false,
      currentPage4: 4,
      inviteTeacher: {
        //邀请
        dlgShow: false,
        params: { name: '' },
        list: []
      },
      manageStudy: {
        dlgShow: false
      },
      params: {},
      pageData:[],
      courseChooseShow: false,
      courseChooseId: '',
      courseTypes: [
        { id: '1', img: this.webBaseUrl + '/images/ctype1.png', name: '微课', info: '一种单一课件的课程' },
        { id: '2', img: this.webBaseUrl + '/images/ctype2.png', name: '在线课', info: '有章节多课件的课程' },
        { id: '3', img: this.webBaseUrl + '/images/ctype3.png', name: '课程包', info: '微课和在线课组成' },
        { id: '4', img: this.webBaseUrl + '/images/ctype4.png', name: '线下课', info: 'XXXX' },
        { id: '5', img: this.webBaseUrl + '/images/ctype5.png', name: '直播课', info: 'XXXX' }
      ],
      weike: {
        onlyRequired: false,
        dlgShow: false,
        fileType: '',
        info: {
          shebei: ''
        }
      },
      biaoke: {
        dlgShow: false
      },
      recommend: {
        dlgShow: false,
      },
      catalogs: {
        addNewZhang: false,
        addNewCell: false,
      },
      extendRefId:'',
      extendRefType:'',
      // ai播放器相关
      aiPermission: false,
      selectedCourses: [], //已选课程
      languageSetting: { // 设置语种弹框
        dlgShow: false,
        languageCode: ['zh-CN', 'en-US'] // 默认选中的语种
      },
      aiProcessSetting: {  // 开启AI处理弹框
        dlgShow: false,
        aiSet: 1,
        aiAbstract: 1,
        aiDraft: 1,
        languageCode: ['zh-CN', 'en-US'] // 默认选中的语种
      },
      aiSetting: { // AI设置弹框
        dlgShow: false,
        courseId: '',
        aiSet: 1,
        aiAbstract: 1, // 1:上架 0:下架
        aiDraft: 1, // 1:上架 0:下架
        aiTranslate: 1, // 1:上架 0:下架
        languageCode: ['zh-CN', 'en-US', 'vi-VN'] // 支持的语种
      },
      aiSetTip: '是否将课程进行AI处理', //提示信息
      aiAbstractTip: '一键提炼课程视频核心要点，助力学员课前高效掌握重点，快速筛选学习资源', // 提示信息
      aiDraftTip: '分段展示视频内容并精准同步时间轴，实现视频进度与文稿双向定位，学习内容触手可及', //提示信息
      aiTranslateTip: '智能转换视频字幕与语音为多语种，支持全球学员按需切换语言，打破学习边界', // 提示信息
      isV2: true,
    };
  },
  mounted() {
    // ai播放器相关
    this.getAiPermission();
    this.getAudiences()
    let chooseFlag=this.$route.query.f;
    this.extendRefId=this.$route.query.refId;
    this.extendRefType=this.$route.query.refType;
    if(chooseFlag && chooseFlag=='choose'){
      this.forChoose=true;
    }

    if(this.$route.query && this.$route.query.page && this.$route.query.page == 'manage') {
       this.pageManage=true;
    }

    if (this.$route.query && this.$route.query.open && this.$route.query.open == 'new') {
      this.addNewCourse();
    }
    // this.getTree();
    // this.getTypeData();
    // this.searchData();
    this.getResOwnerTree().then(rs=>{
      this.resOwnerListMap=rs;
    });
    // 取消全局课程分类
    this.getSysTypeTree().then(rs=>{
      this.sysTypeListMap=rs;
    })
    //已经加载tree的情况下，不需要再单独的加载一次
    this.loadResOwners();
    this.loadSysTypes();

  },
  methods: {
    
    getAudiences(){
      apiUserbasic.getInAudienceIds().then(res=>{
        if (res.status == 200) {
          this.audiences = res.result;
        }
        this.searchData();
      })
    },
    showStudent(row){
        //出现学员管理
        window.parent.openSelectStu(row);
    },
    handleChoose(row){ //选择课程
      window.parent.selectCourse(row);
    },
    myCopy(){
      var ele = document.getElementById("text");
      ele.select();
      document.execCommand("Copy");
    },
    inputOn() {
      this.$forceUpdate();
    },

    // 置顶
    setTop(row) {
       let params = {
        ids: row.id,//课程id,多个使用逗号分隔,
        title:row.name,//课程的名称,
        top:!row.isTop,// top 是否置顶}
      }
      console.log(row.isTop);
       if(row.isTop == false){
        //  console.log('fa')
        this.$confirm('此操作将置顶此课程, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        apiCourse.setTop(params).then(res=>{
           if(res.status === 200 && res.result === true) {
            this.$message.success('置顶成功！')
            this.searchData();
        } else {
           this.$message({
            type: 'error',
            message: res.message
          });
        }
      })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '置顶失败'
          });
        });
       }else if(row.isTop == true){
         this.$confirm('此操作将取消置顶此课程, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        apiCourse.setTop(params).then(res=>{
           if(res.status === 200 && res.result === true) {
            this.$message.success('取消成功！')
            this.searchData();
        } else {
           this.$message({
            type: 'error',
            message: res.message
          });
        }
      })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消置顶失败'
          });
        });
       }






    },
    // 复制
    copyCourse(item) {
      let $this=this;
      this.$confirm('您确定要复制此课程吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            let reqdata={
               id:item.id,
               refId:$this.extendRefId,
               refType:$this.extendRefType,
            }
            apiCourse.copyCourse(reqdata).then(rs=>{
              if(rs.status==200){
                this.$message.success("复制课程成功");
                this.searchData();
              }else{
                this.$message.error("复制课程失败:"+rs.message);
              }
            })
        }).catch(() => {

        });
    },
    // 撤回接口
    withdraw(row) {
       this.$confirm('此操作将将撤回审核中的课程, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           apiCourse.revokeSubmit(row.id).then((res)=>{
              if(res.status == 200){
                if(res.result) {
                   this.$message({
                    type: 'success',
                    message: '撤回成功!'
                  });
                  this.searchData();
                }
              }
           })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消撤回'
          });
        });
    },
    reset(){
      this.resOwner = ''
      this.params.sysType = ''
      this.params.createUser = ''
      this.params.keyword = ''
      this.params.type = ''
      this.params.publish = ''
      this.params.status = ''
      this.sysTypeList = [];
      this.params.sysType1 = '';
      this.params.sysType2 = '';
      this.params.sysType3 = '';

	    this.searchData(true);
    },
    ...mapActions({
      getResOwnerTree:'resOwner/getResOwnerTree',
      loadResOwners:'resOwner/loadResOwners',
      getSysTypeTree:'sysType/getSysTypeTree',
      loadSysTypes:'sysType/loadSysTypes'
    }),
    resOwnerName(code){
      if(code==''){return '';}
      return this.resOwnerMap.get(code);
    },
    sysTypeName(code){
      if(code==''){return '';}
      return this.sysTypeMap.get(code);
    },
    // 直接审核
    examineData() {
      if(this.isExamine == 1) {
         let params = {
        id:this.examin.examineId,//课程id,
        title:this.examin.examineName,//课程的名称,
        pass: this.auditInfo.pass,//Boolean 是否通过,
        remark: this.auditInfo.remark,// 备注
      }
      apiCourse.audit(params).then(res=>{
        if(res.status === 200) {
          this.$message.success('操作成功！');
          this.dialogVisible = false;
          this.searchData();
         }else{
             this.$message.error(res.message);
         }
      })
      } else {
        this.$message.warning('暂未开放！');
      }

    },
    addNewCourse() {
      this.$refs.courseForm.initShow();
    },
    editCurriculum(row) {
      this.$refs.courseForm.initShow(row);
    },
    // 课程停用
    async isDisable(row) {
      //  {ids:课程id,多个使用逗号分隔,title:课程的名称, Boolean enabled 是否启用}
	  let message;
	  if(row.enabled){
	  	message='停用成功'
	  }else{
		  message='启用成功'
	  }
      let params = {
         ids: row.id,
         title: row.name,
         enabled: !row.enabled,
      };
       try {
        const {status} = await apiCourse.setEnabled(params);
        if(status === 200) {
          this.$message.success(message)
		  row.enabled=!row.enabled
        }
      } catch (error) {
        console.log(error);
      }

    },
    // 课程查询
    searchData(pageReset) {
      if(pageReset){
        this.page.pageIndex=1;
      }
      // if(this.extendRefId){
      //   this.params.refId=this.extendRefId;
      // }
      // if(this.extendRefType){
      //   this.params.refType=this.extendRefType;
      // }
      this.params.resOwner1 = this.resOwner[0];
      this.params.resOwner2 = this.resOwner[1];
      this.params.resOwner3 = this.resOwner[2];
      this.params.pageIndex = this.page.pageIndex;
      this.params.pageSize = this.page.pageSize;
      this.params.sysType1 = this.sysTypeList[0];
      this.params.sysType2 = this.sysTypeList[1];
      this.params.sysType3 = this.sysTypeList[2];
      if(this.$route.query.courseIds) this.params.courseIds = this.$route.query.courseIds.split(',');
      if(this.$route.query.projectId) this.params.projectId = this.$route.query.projectId;
      if(this.audiences && this.audiences.length > 0){
        this.params.audiences = this.audiences.join(',');
      }
      if(this.pageManage){
        this.params.isCreateCourse = false
      }else{
        this.params.isCreateCourse = true
      }
      apiCourse.pageList(this.params).then(rs=>{
          if(rs.status==200){
            this.pageData = rs.result.list ? rs.result.list : [];
            // this.pageData = rs.result.list;
            this.page.count = rs.result.count;
            this.page.pageSize = rs.result.pageSize;
          }else{
            return this.$message.error(rs.message);
          }
      })

    },
    viewTopic(row) {
      if(row.status == 1) {
        return this.$message.warning('请提交课程再预览！')
      }
      this.examin = {};
      this.examin.detailType = row.type;
      this.examin.examineId = row.id;
      this.examin.examineName = row.name;
      this.showDetails = true;
    },
    jumpDetails() {
      // this.$router.push('/course/micro');
      // 跳转打开新页面
       let routeData = this.$router.resolve({ path: '/course/detail'}); // , query: {  id: 1 }
       window.open(this.webBaseUrl+routeData.href, '_blank');
    },
    toExamine(row) {
      this.auditInfo = {pass: true};
      this.examin.detailType = row.type;
      this.examin.examineId = row.id;
      this.examin.examineName = row.name;
      this.dialogVisible = true;
    },
    enSure() {
      // 确认事件
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageIndex = 1;
      this.searchData();
    },
    handleCurrentChange(val) {
     this.page.pageIndex = val;
      this.searchData();
    },
    chooseInvite(row) {
      //邀请老师审核
      this.inviteTeacher.dlgShow = true;
    },
    findTeachers() {
      this.inviteTeacher.list = [
        { id: '1', name: '李玉冰', type:'通过',text: '实用',sex: '男', code: '1023123', orgInfo: '教育技术中心', checked: false },
        { id: '2', name: '李玉冰', type:'未通过',text: '内容在调整',sex: '男', code: '1023123', orgInfo: '教育技术中心', checked: false },
        { id: '3', name: '李玉冰', type:'驳回',text: '内容重复',sex: '男', code: '1023123', orgInfo: '教育技术中心', checked: false }
      ];
    },
    showQrimage(row) {
      this.qrcodeShow = true;

      let urlPre=window.location.protocol+'//'+window.location.host;

      //动态的地址
      //urlPre=urlPre+'/m?returnUrl='+urlPre+'/mobile/pages/login/loading?returnUrl=';
      //固定的地址
      let returnUrl=urlPre+'/mobile/pages/login/loading?returnUrl=/pages/study/courseStudy?id='+row.id;
      let mobilePre=urlPre+'/m?returnUrl=';
      this.qrcode = mobilePre+encodeURIComponent(returnUrl);
      this.pcDetailUrl=urlPre+this.webBaseUrl+'/course/studyindex?id='+row.id;
      if(row.type==20){
        this.pcDetailUrl=urlPre+this.webBaseUrl+'/course/detail?id='+row.id;
      }

      // 使用$nextTick确保数据渲染
      this.$nextTick(() => {
        this.crateQrcode();
      });
    },
    // 生成二维码
    crateQrcode() {
      this.qr = new QRCode('qrcode', {
        width: 150,
        height: 150, // 高度
        text: this.qrcode // 二维码内容
        // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        // background: '#f0f'
        // foreground: '#ff0'
      });
    },
    // 关闭弹框,清除已经生成的二维码
    closeCode() {
      this.$refs.qrcode.innerHTML = '';
    },
    showManageStudy(row) {
      this.manageStudyData = row;
      this.manageStudy.dlgShow = true;
    },
    releaseData(row) {
      this.$confirm('正在发布课程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
           let params = {
         ids: row.id,
         title: row.name,
         enabled: !row.published,
      };

       try {
        const {status} = await apiCourse.publish(params);
        if(status === 200) {
          this.$message.success('操作成功！');
          this.searchData();
        }
      } catch (error) {
        console.log(error);
      }

        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消发布'
          });
        });
    },
    showChooseCourse() {
      this.courseChooseShow = true;
    },
    chooseCourseType(item, idx) {
      this.courseChooseId = item.id;
    },
    toInputCourse() {
      if (this.courseChooseId == '1') {
        this.showWeike();
      } else if (this.courseChooseId == '2') {
        this.showBiaoke();
      }
      this.courseChooseShow = false;
    },
    newHandleClick() {},
    showRecords(item) {
      this.recommend.dlgShow = true;
    },
    showWeike() {
      this.weike.dlgShow = true;
    },
    showBiaoke() {
      this.biaoke.dlgShow = true;
    },
    // setTop(item, idx) {
    //   let msg = '已设置置顶';
    //   if (item.isTop) {
    //     item.isTop = false;
    //     msg = '已取消置顶';
    //   } else {
    //     item.isTop = true;
    //   }
    //   this.$message({ message: msg, type: 'success', offset: 50 });
    // },
    delItem(row) {
      this.$confirm('您确定要删除所选课程吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
            let params = {
         id: row.id,
         title: row.name,

      };
       try {
        //  {id:课程id,多个使用逗号分隔,Boolean erasable 是否物理删除,title:课程的名称, remark 备注}
        const {status} = await apiCourse.del(params);
        if(status === 200) {
          this.$message.success('操作成功！'); //只是之前发布过的课程删除才可
          // if(!row.erasable){
          //   let event = {
          //     key: "CourseDelete",//被管理员删除
          //     title: '被管理员删除课程',//事件的标题
          //     parameters:"author:"+row.sysCreateAid,//作者，一般这种情况不是管理员自己添加的
          //     content: '被管理员删除课程',//事件的内容
          //     objId: row.id,//关联的id
          //     objType: "1",//关联的类型
          //     objInfo:row.name,
          //     aid: this.userInfo.aid, //当前登录人的id
          //     aname: this.userInfo.name,//当前人的姓名
          //     status: 1 //状态，直接写1
          //   }
          //   this.$store.dispatch("userTrigger", event);
          // }

          this.searchData();
        }
      } catch (error) {
        console.log(error);
      }
        })
        .catch((err) => {
          this.$message({ type: 'info', message: '已取消删除', offset: 50 });
        });
    },
    showAddCatalogZhang(bal) {
      this.catalogs.addNewZhang = bal;
    },
    saveNewCatalogZhang() {
      this.catalogs.addNewZhang = false;
    },


    // ai播放器相关
    getLanguageName(lang){
      return this.selectAllLang.find(item => item.srclang === lang)?.label || '';
    },
    handleSelectionChange(val){
      this.selectedCourses = val;
      console.log(val);
    },
    // 获取选中课程的AI信息
    getAIInfoByList(list = []) { 
      let selectNum = 0; // 选中的课程数量
      let aiSetNum = 0; // 已设置AI的课程数量
      let aiSetNoNum = 0; // 未设置AI的课程数量
      list.forEach(item => {
        if(item.aiSet === 1){
          aiSetNum++;
        }else{
          aiSetNoNum++;
        }
      });
      return {
        selectNum,
        aiSetNum,
        aiSetNoNum
      }
    },
    // AI设置
    setAI(row) {
      console.log('row', row);
      this.aiSetting = {
        dlgShow: true,
        ...row
      };
    },
    changeAIKey(key) {
      this.aiSetting[key] = this.aiSetting[key] === 1 ? 0 : 1;
    },
    // 确认AI设置
    confirmAISetting() {
      const item = deepCopy(this.aiSetting);
      item.languageStatus = item.aiSet;
      item.languageCode = item.languageCode || [];
      if (!item.languageCode.includes('zh-CN')) {
        item.languageCode.unshift('zh-CN'); // 默认添加中文 去重
      }
      this._benchAiSet([item], (res) => {
        this.$message.success('AI设置保存成功');
        this.aiSetting.dlgShow = false;
        // 可以选择是否刷新列表数据
        this.searchData();
      }, (res) => {
        this.$message.error('AI设置保存失败！');
      })
    },
    setLanguage() {
      if (this.selectedCourses.length > 0) {
        this.languageSetting = {...{ 
          dlgShow: true,
          languageCode: ['zh-CN', 'en-US'] // 默认选中的语种
        }, ...this.getAIInfoByList(this.selectedCourses)}
      }
    },
    enableAI() {
      // 开启AI处理按钮点击事件
      if (this.selectedCourses.length > 0) {
        this.aiProcessSetting = {...{
          dlgShow: true,
          aiSet: 1,
          aiAbstract: 1,
          aiDraft: 1,
          languageCode: ['zh-CN', 'en-US'] // 默认选中的语种
        }, ...this.getAIInfoByList(this.selectedCourses)} 
      }
    },
    // 批量设置语种 - 确认
    confirmLanguageSetting() {
      const courseList = deepCopy(this.selectedCourses);
      let languageCode = deepCopy(this.languageSetting.languageCode || []);
      if (!languageCode.includes('zh-CN')) {
        languageCode.unshift('zh-CN'); // 默认添加中文 去重
      }
      courseList.forEach(item => {
        item.languageCode = languageCode;
        item.aiTranslate = item.aiSet;
        item.languageStatus = item.aiSet;
      })
      this._benchAiSet(courseList, (res) => {
        this.$message.success('设置语种成功！');
        this.languageSetting.dlgShow = false;
        // 可以选择是否刷新列表数据
        this.searchData();
      }, (res) => {
        this.$message.error('设置语种失败！');
      })
    },

    // 批量开启AI处理 - 确认
    confirmAiProcess() {
      // 获取AI处理配置
      let { aiSet, aiAbstract, aiDraft, languageCode } = this.aiProcessSetting;
      const courseList = deepCopy(this.selectedCourses);
      languageCode = languageCode || [];
      if (!languageCode.includes('zh-CN')) {
        languageCode.unshift('zh-CN'); // 默认添加中文 去重
      }
      courseList.forEach(item => {
        item.aiSet = aiSet;
        item.aiAbstract = aiAbstract;
        item.aiDraft = aiDraft;
        item.aiTranslate = aiSet;
        item.languageStatus = aiSet;
        item.languageCode = languageCode;
      })
      this._benchAiSet(courseList, (res) => {
        this.$message.success('开启AI处理成功！');
        this.aiProcessSetting.dlgShow = false;
        // 可以选择是否刷新列表数据
        this.searchData();
      }, (res) => {
        this.$message.error('开启AI处理失败！');
      })
    },

    _benchAiSet(courseList, successCB, failCB) {
      apiCourse.benchAiSet({courseList}).then(res => {
        if(res.status === 200){
          successCB && successCB(res);
        }else{
          failCB && failCB(res);
        }
      })
    },
    getAiPermission() {
      apiCourse.listByUser({}).then(res => {
        console.log('res', res);
        if(res.code === 200){
          let index = res.data.findIndex(item => item.permissionCode === 'KjbAiSetCode');
          this.aiPermission = index !== -1;
           console.log('index', index, this.aiPermission);
        }
      })
    },
    toAiAbstract() {
      this.$router.push({
        path: '/iframe/course/aiAbstract',
        query: {
          id: this.aiSetting.id
        }
      })
    },
    toAiTranslate() {
      this.$router.push({
        path: '/iframe/course/aiTranslate',
        query: {
          id: this.aiSetting.id
        }
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.sou{
   padding: 0 0 0 0px !important;
}
.el-col {
  padding: 0 0 0 10px !important;
}
.grid-content {
  padding-right: 0px;
}
.el-button--text{
  font-size: 14px;
}

.Create-coures{
  // margin-left: 14%;
}
.course-types {
  display: flex;
  justify-content: center;
  padding: 15px;

  .course-type {
    margin: 10px;
    text-align: center;
    padding: 5px;
    cursor: pointer;
    img {
      width: 110px;
      height: 110px;
    }
    .info {
      padding-top: 10px;
    }
  }
  .choose {
    border: 2px solid #008000;
  }
}

.el-aside {
  padding: 5px 10px;
}
.cctree {
  .cctree-chapter {
    .cctree-chapter-name {
      border-bottom: 1px solid #dddddd;
    }
    .cctree-chapter-cells {
      margin: 0px;
      list-style-type: circle;
      padding: 0px;
      .cctree-chapter-cell {
        line-height: 30px;
        list-style-type: circle;
        padding-left: 25px;
      }
    }
  }
}

.el-dialog__body {
  overflow: hidden;
}

 .form-item{
   margin-bottom: 20px;
   display: flex;
   align-items: center;
   gap: 10px;
 }
.tips {
  color: #f56c6c;
  font-size: 12px;
  margin: 10px 0;
  line-height: 1.5;
}
.languages-list{
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
</style>
