<template>
  <MOSTY.PageTree :pageTitle="'课件库列表'" :searchType="'01'" @getDeptId="getdeptId">
    <template #titleright>
      <div class="toggle" :class="{ active: isOpen }" @click="handleTotal">
        <span>统计</span>
        <el-icon>
          <DArrowLeft />
        </el-icon>
      </div>
    </template>
    <template #serach>
      <div v-show="isOpen" ref="getHeight">
        <MOSTY.Assort title="课件库统计" style="padding: 0;" />
        <section class="flex">
          <section class="left-tj">
            <Sjtj :info="countlist" :isShowTip="false" :isShowBottom="false" :width="236" mb="6px" />
          </section>
        </section>
      </div>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
      <el-divider />
      <section class="button">
        <!-- v-if="isAqbm" -->
        <!-- <el-popconfirm v-if="isRealAqbm" confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定批量上报?"
          @confirm="handleBatchPush()">
          <template #reference>
            <el-button type="primary" :loading="batchReportLoading">
              <el-icon>
                <Upload />
              </el-icon>
              <span>批量上报</span>
            </el-button>
          </template>
</el-popconfirm> -->
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="primary" @click="export2Excel" v-loading="loadingShow">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出表格</span>
        </el-button>
      </section>
    </template>
    <template #table>
      <div :style="{ 'height': totalHeights }">
        <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading" :isSelect="true"
          actionsW="250" :isSort="true" style="width: 100%;" @selectionChange="handleSelectionChange"
          :selectable="selectable">
          <template #learntype="{ row }">
            <span class="operate" v-if="row.learntype == '2'">视频</span>
            <span class="operate" v-else>文件</span>
          </template>
          <template #studytype="{ row }">
            <span class="operate" v-if="row.studytype == '1'">全员参与</span>
            <span class="operate" v-else-if="row.studytype == '2'">指定人员</span>
            <span class="operate" v-else>-</span>
          </template>
          <template #state="{ row }">
            <el-tag v-if="D_BZ_PXZYK_OBJ[row.state]" :type="colorTypeObj[row.state]">{{ D_BZ_PXZYK_OBJ[row.state]
              }}</el-tag>
          </template>
          <template #actions="{ row }">
            <div style="display: flex;flex-wrap: wrap;justify-content: space-around;gap:4px">
              <!-- <el-popconfirm confirm-button-text="是" v-if="isShowReportBtn(row)" cancel-button-text="否" icon-color="red"
                title="确定要上报?" @confirm="handlePush(row)">
                <template #reference>
                  <span class="operedit" size="small">
                    <el-icon>
                      <Upload />
                    </el-icon>
                    上报</span>
                </template>
</el-popconfirm> -->
              <span style="margin-left: 0;" class="operesee" @click="handlexq(row, 'see')"><el-icon>
                  <EditPen />
                </el-icon>详情
              </span>
              <!-- <span> -->
              <span class="operedit" v-if="isShowEdit(row)" @click="handleedit(row)"><el-icon>
                  <!-- v-if="isAqbm" -->
                  <EditPen />
                </el-icon>编辑
              </span>
              <span class="operedit" @click="handlestudy(row)"><el-icon>
                  <EditPen />
                </el-icon>学习</span>
              <el-popconfirm v-if="isShowDelBtn(row)" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="确定要删除?" @confirm="handledelete(row)">
                <!--  v-if="isAqbm"  -->
                <template #reference>
                  <span class="operdel" size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <span v-if="isShowSet(row)" class="operesee" @click="handletest(row, 'see')"><el-icon>
                  <!-- v-if="isAqbm" -->
                  <EditPen />
                </el-icon>设置考题</span>
              <span v-if="isShowPush(row)" class="operesee" @click="handlepeplo(row, 'see')"><el-icon>
                  <Compass />
                </el-icon>推送
              </span>
              <!-- </span> -->
              <span class="operedit" @click="handleSee(row, 'see')"><el-icon>
                  <EditPen />
                </el-icon>学习统计
              </span>
            </div>
          </template>
        </MOSTY.Table>
      </div>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="listQuery" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
        </MOSTY.Pages>
      </div>
    </template>
  </MOSTY.PageTree>
  <!-- 新增弹出框 -->
  <el-dialog v-model="dialogVisible" :title="title" width="865px" :before-close="CloseEvent">
    <div class="from_box" v-if="dialogVisible">
      <div class="from_left">
        <div style="height: 175px;overflow-y: hidden;">
          <MOSTY.Upload :width="'100%'" :limit="1" :nopicer="false" :isImg="true" :ShowfileList="false"
            v-model="dialogForm.videopic" :gsgfList="['jpg', 'png']" :disabled='!savebtn'>
          </MOSTY.Upload>
        </div>
        <span style="margin-left: 40px">课件封面图</span>
      </div>
      <el-form ref="frombt" :model="dialogForm" :rules="rules" label-width="120px" :disabled='!savebtn'>
        <el-form-item label="课件类型：" prop="videotype">
          <el-select class="pxdx_box" v-model="dialogForm.videotype" clearable style="width: 212px">
            <el-option v-for="item in D_TB_YWLX" :key="item" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="学习类型：" prop="learntype">
          <el-select class="pxdx_box" v-model="dialogForm.learntype" clearable style="width: 212px"
            @change="learntypeChange">
            <el-option v-for="item in xxlxlist" :key="item" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课件名称：" prop="videoname">
          <el-input v-model="dialogForm.videoname" maxlength="50" autosize type="textarea" show-word-limit
            placeholder="不能超过50个字" style="width: 547px"></el-input>
        </el-form-item>
        <el-form-item label="课件简介：" prop="instro">
          <el-input style="width: 547px" v-model="dialogForm.instro" autosize type="textarea" row="10" />
        </el-form-item>
        <el-form-item ref="videoTimeRef" label="学时：" :prop="dialogForm.learntype == '2' ? '' : 'videotime'">
          <el-input v-model="dialogForm.videotime" type="Number" maxlength="30" @input="check" style="width: 547px"
            :disabled="dialogForm.learntype == '2'"></el-input>
        </el-form-item>
        <el-form-item label="课件附件：" prop="videourl" v-if='dialogForm.learntype == "1"'>
          <MOSTY.Upload width="547px" :limit="1" :nopicer="true" :isImg="false" :ShowfileList="true"
            :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" v-model="dialogForm.videourl"
            :delrow="delrow">
          </MOSTY.Upload>
        </el-form-item>
        <el-form-item label="视频上传：" prop="videourl" v-if='dialogForm.learntype == "2"'>
          <MOSTY.Upload width="547px" :limit="1" :nopicer="true" :isImg="false" :isVideosp="true" :ShowfileList="true"
            v-model="dialogForm.videourl" :delrow="delrow" @filehandleChange="changeFile" :keys="keys">
          </MOSTY.Upload>
          <div style="margin-left:20%;color:red;"> <span> (仅支持视频格式文件上传)</span></div>
        </el-form-item>
        <!-- <el-form-item label="仅本级查看：" v-if="isShowBJBtn(dialogForm, savebtn)" prop="pubpriv">
          <div style="width: 215px">
            <MOSTY.DictRidioAndSelect :dictData="[{ label: '是', value: '01' }, { label: '否', value: '02' }]"
              v-model="dialogForm.pubpriv" selectType="radio" />
          </div>
        </el-form-item> -->
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">

        <el-button type="primary" v-if='savebtn' :loading="loading" @click="saveFrom(frombt)">
          <el-icon class="mr4">
            <DocumentChecked />
          </el-icon>
          保存
        </el-button>
        <el-button @click="CloseEvent"><el-icon class="mr4">
            <DocumentDelete />
          </el-icon>关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 参加人员 -->
  <Addcjry v-if="addDiaShow" :id="rowId" @changeAddVi="changeAddVi" @changeclose="changeclose" />
  <!-- 设置考题 -->
  <div v-if="comprehensiveShow" class="dialog-box">
    <Ktk @close="closeEven" :RowId="rowId" />
  </div>
  <!-- 视频播放组件 -->
  <div v-if="showVideo" class="dialog-box">
    <div class="barbox">
      <div class="titleBox">
        <div class="title">{{ title }}-课件学习</div>
        <div class="btnBox" style="margin-top: 0;">
          <el-button @click="closeVIde">
            <el-icon>
              <Back />
            </el-icon>
            <span>返回</span>
          </el-button>
        </div>
      </div>
      <div class="videos">
        <MOSTY.VideoPlay :showVideo="showVideo" :currTime="positionTime" :videourl="videourl" @EndChange="EndChange"
          @changeTime="changeTime" />
      </div>
    </div>
  </div>

  <!-- 预览 -->
  <el-dialog v-model="isShowFile" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false"
    top="10px" bottom="10px" width="1120px">
    <div style="height: 84vh; text-align: center">
      <Kkfile :files="priviewFileid" @changedialog="isShowFile = false" />
    </div>
  </el-dialog>
  <!-- 审核弹框 -->
  <kjkAuditTc v-if="isShowKjkAuditTc" :resData="auditResData" @close="kjkAuditTcClose" />
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance, computed, nextTick, onBeforeUnmount } from "vue";
import { exportXlsx } from "@/excel/Export2Excel.js";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { useRouter, useRoute } from "vue-router";
import * as rule from "@/utils/rules.js";
import Ktk from "./ktk.vue";
import Addcjry from "./addcjry.vue";
import { getItem } from "@/utils/storage";
import { ElMessage, ElMessageBox } from "element-plus";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
import { filterqx } from "@/utils/auth.js";// isSgs,isgs,isxgs,isaqbm,isldbz
import { isShowReportButton } from './reportcom/reportTools.js';
import kjkAuditTc from "./kjkCom/kjkAuditTc.vue";
import Kkfile from "@/components/MyComponents/kkfile/index.vue";

let deptId = ref('')
/** 展示文件 */
const isShowFile = ref(false)
/** 预览文件id */
const priviewFileid = ref()
const { proxy } = getCurrentInstance();
const { D_TB_YWLX, D_BZ_PXZYK } = proxy.$dict("D_TB_YWLX", "D_BZ_PXZYK");
const router = useRouter();
const route = useRoute();
const frombt = ref();
const videourl = ref(null);
/**当前id */
const id = ref(null);
const engPlay = ref(false);
const rowId = ref(null);
const loadingShow = ref(false);
const delrow = ref();
const keys = ref(1);
const loading = ref(false);
const addDiaShow = ref(false);
const comprehensiveShow = ref(false);
const showVideo = ref(false);
const title = ref("");
const dialogVisible = ref(false);
const tableloading = ref(false);
const savebtn = ref(false);
/** 选中的数组 */
const selected = ref([]);
/** 批量上报loading */
const batchReportLoading = ref(false)
/** 审核弹框数据 */
const auditResData = ref({})
/** 审核弹框 */
const isShowKjkAuditTc = ref(false)
const USERID = getItem("USERID").toString();
const isRealAqbm = filterqx('isaqbm') == '1'
const dialogForm = ref({
  /** 是否本级 01 是 02 否 */
  pubpriv: '01' // 默认本级
});
const currTime = ref(0)
const positionTime = ref(0)
const getHeight = ref(null)
const totalHeights = ref(null)
const isOpen = ref(false);
const videoTimeRef = ref({})
const countlist = ref(
  [
    { title: '消防', num: 0, dm: 'xf', icon: 'ccss/icon_01.png' },
    { title: '交通', num: 0, dm: 'jt', icon: 'ccss/icon_02.png' },
    { title: '生产', num: 0, dm: 'sc', icon: 'ccss/icon_03.png' },
    { title: '设备', num: 0, dm: 'sb', icon: 'ccss/icon_04.png' },
    { title: '电气', num: 0, dm: 'dq', icon: 'ccss/icon_05.png' },
    { title: '食品', num: 0, dm: 'sp', icon: 'ccss/icon_05.png' },
    { title: '特种作业', num: 0, dm: 'tzzy', icon: 'ccss/icon_05.png' },
    { title: '特种设备', num: 0, dm: 'tzsb', icon: 'ccss/icon_05.png' },
    { title: '其它', num: 0, dm: 'qt', icon: 'ccss/icon_05.png' },
  ]
)
/** 审核对照对象 00 未上报，01 审核中，02  市公司审核完成，03  省审核中  04省公司审核完成 */
const colorTypeObj = {
  '00': '',
  '01': 'danger',
  '02': 'success',
  '03': 'danger',
  '04': 'success',
}
const D_BZ_PXZYK_OBJ = computed(() => {
  let arr = Array.isArray(D_BZ_PXZYK.value) ? D_BZ_PXZYK.value : []
  return arr.reduce((obj, item) => {
    obj[item.value] = item.label
    return obj
  }, {})
})
//查询
function onSearch(obj) {
  listQuery.value.year = obj.year;
  listQuery.value.videoname = obj.videoname;
  listQuery.value.pageCurrent = 1;
  getTableData();
}
const searchArr = reactive([
  {
    showType: "year",
    prop: "year",
    width: '250px',
    placeholder: '请选择年份'
  },
  {
    showType: "input",
    prop: "videoname",
    width: '250px',
    placeholder: '请输入课件名称'
  }
]);
const tableColumn = reactive([
  { title: "课件名称", prop: "videoname" },
  { title: "上传人", prop: "xtCjr" },
  { title: "课件时长", prop: "videotime" },
  { title: "点击次数", prop: "clickedtime" },
  { title: "上传时间", prop: "xtCjsj" },
  { title: "类型", prop: "learntype", slot: true, },
  { title: "指定范围", prop: "studytype", slot: true, },
  // { title: "上报状态", prop: "state", slot: true },
  { title: "操作", prop: "actions", slot: true, },
])
const getscsbsscount = () => {
  getApi({ 'depId': String(listQuery.value?.deptid) }, '/mosty-jcgl/videoStudy/getStatisticsCount').then(res => {
    if (res) {
      for (const key in res) {
        let _item = countlist.value.find(v => v.dm == key)
        if (_item) {
          _item.num = res[key] || 0
        }
      }
    }
  })
}
onBeforeUnmount(() => {
  getApi({ currTime: currTime.value, videoId: id.value }, '/mosty-jcgl/videoStudy/setCurrTime')
})
const learntypeChange = () => {
  /// 清空 学时表单验证
  videoTimeRef.value?.resetFields?.()
}
const changeTime = (val) => {
  currTime.value = val
}
// 是否是本部
const isAqbm = computed(() => {
  return getItem("deptId").ssbmid == listQuery.value.deptid
})
const handleTotal = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    totalHeights.value = `calc(100vh - 585px)`
  } else {
    totalHeights.value = `calc(100vh - 373px)`
  }
}


const CloseEvent = () => {
  if (savebtn.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        frombt.value.clearValidate();
        dialogForm.value = {}
        dialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    frombt.value.clearValidate();
    dialogForm.value = {}
    dialogVisible.value = false
  }

};
const xxlxlist = ref([
  { label: '附件', value: '1' },
  { label: '视频学习', value: '2' }
])
const tableData = ref([]);
const videoPrefix = ref('avi,wmv,mp4,mov,3gp')
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  year: '',
  videoname: '',
});
const total = ref(0);
//规则校验
const rules = reactive({
  videotype: [{ required: true, message: "课件类型不能为空", trigger: "blur" }],
  learntype: [{ required: true, message: "学习类型不能为空", trigger: "blur" }],
  videoname: [{ required: true, message: "课件名称不能为空", trigger: "blur" }],
  instro: [{ required: true, message: "课件简介不能为空", trigger: "blur" }],
  ...rule.znumberRule({ validator: true, require: true }, "videotime"),
  videourl: [
    {
      trigger: "blur",
      required: true,
      message: "课件附件不能为空"
    }
  ],
  studytype: [
    {
      trigger: "blur",
      required: true,
      message: "指定范围不能为空"
    }
  ]
});
onMounted(() => {
  nextTick(() => {
    if (isOpen.value) {
      totalHeights.value = `calc(100vh - 585px)`
    } else {
      totalHeights.value = `calc(100vh - 373px)`
    }
  })
  // 去审核
  if (route.query.id && route.query.rwlx == '63') goToAudit(route.query)
  if (route.query.id && route.query.rwlx == '51') goToStudy(route.query)
});
//获取部门数据
const getdeptId = (val) => {
  listQuery.value.deptid = val.id;
  listQuery.value.pageCurrent = 1;
  getTableData();
  getscsbsscount()
};
function check(event) {
  if (dialogForm.value.videotime.length > 30) {
    dialogForm.value.videotime = dialogForm.value.videotime.slice(0, 30);
  }
}
function changeFile(val) {
  if (val[0].id) {
    getApi({}, '/mosty-base/minio/image/downloadUrl/' + val[0].id).then((res) => {
      if (res) {
        let prefix = res.substring(res.lastIndexOf('.') + 1);
        if (prefix) {
          if (videoPrefix.value.indexOf(prefix.toLowerCase(prefix)) != -1) {
            //这里是视频信息
            const videoUrls = res;
            const video = document.createElement('video');
            video.preload = 'metadata';
            video.src = videoUrls;
            video.onloadedmetadata = () => {
              URL.revokeObjectURL(videoUrls);
              const duration = video.duration;
              // 处理视频时长
              dialogForm.value.videotime = (video.duration / 3600).toFixed(3); // 转换为小时并保留三位小数
            };

          } else {
            // 这里是其他格式的问题件
            window.open(res, "_blank")
          }
        } else {
          ElMessage.warning('附件格式错误！');
        }
      } else {
        ElMessage.warning('学习附件不存在！');
      }
    }).catch((err) => {
      ElMessage({ type: 'warning', message: err.message });
    });
  }
}
// 获取表格数据
const getTableData = () => {
  tableloading.value = true;
  getApi(listQuery.value, "/mosty-jcgl/videoStudy/getPageList").then((res) => {
    tableData.value = res.records;
    listQuery.value.total = res.total;
    tableloading.value = false;
  }).finally(() => {
    tableloading.value = false;
  });
};

// 新增弹出框
const handleAdd = () => {
  tableloading.value = false;
  dialogForm.value = {
    pubpriv: '01' // 默认本级
  };
  title.value = "新增课件";
  savebtn.value = true
  dialogVisible.value = true;
};
//修改
function handleedit(val) {
  getxqData(val.id);
  title.value = "修改课件";
  savebtn.value = true
  dialogVisible.value = true;
}
/** 是否显示上报按钮 */
const isShowReportBtn = (row) => {

  return isShowReportButton(row, 'kjk')
}
const selectable = (row) => {
  return isShowReportButton(row, 'kjk')
}
const handleSelectionChange = (val) => {
  selected.value = val;
};
/**推送 */
const handlePush = (row) => {
  getApi({ ids: row.id }, `/mosty-jcgl/videoStudy/reporting`).then(() => {
    ElMessage.success("上报成功");
    getTableData()
  })
}
/** 上报推送 */
const reportPush = (ids, call) => {
  getApi({ ids: ids }, `/mosty-jcgl/videoStudy/reporting`).then(() => {
    ElMessage.success("上报成功");
    getTableData()
  }).finally(() => {
    if (typeof call === 'function') call()
  })
}

/** 批量上报 */
const handleBatchPush = () => {
  if (!selected.value.length) {
    ElMessage.warning('请先选择数据')
    return
  }
  const ids = selected.value.map(item => item.id).join(',')
  batchReportLoading.value = true
  reportPush(ids, () => {
    batchReportLoading.value = false
  })
}

//详情查看
function handlexq(val) {
  getxqData(val.id);
  title.value = "课件详情";
  savebtn.value = false
  dialogVisible.value = true;
}
//	查询数据详情
function getxqData(id, call) {
  getApi({ id }, "/mosty-jcgl/videoStudy/getInfo").then((res) => {
    dialogForm.value = res;
    positionTime.value = res.currTime ? Number(res.currTime) : 0
    if (typeof call === 'function') call(res)
  });
}
//学习
function handlestudy(row) {
  //视频
  getxqData(row.id, (res) => {
    if (res.learntype == '2') {
      title.value = res.videoname;
      id.value = res.id;
      videourl.value = res.videourl;
      showVideo.value = true;

    } else if (res.learntype == '1') {
      id.value = res.id;
      priviewFileid.value = res.videourl
      isShowFile.value = true
      addstudycs(); // 看来就计算学习次数

    }
  });
}
function goToStudy(query) {
  handlestudy({ id: query.id })
}
//判断是否学习完
function closeVIde() {
  if (engPlay.value == false) {
    //没有学习完
    open();
  } else {
    showVideo.value = false;
  }
}
//视频是否播放完
function EndChange(val) {
  engPlay.value = val;
  opens();
}
const open = () => {
  ElMessageBox.confirm(
    "视频尚未看完，如果当前退出将不计入查阅次数，确定退出?",
    "系统信息",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      showVideo.value = false;
    })
    .catch(() => {
      return;
    });
};
const opens = () => {
  ElMessageBox.confirm("视频播放完成！！！", "系统信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      addstudycs();
    })
    .catch(() => {
      addstudycs();
    });
};
// 记录一次学习次数
function addstudycs() {
  postApi({}, `/mosty-jcgl/videoStudy/insertUser/${id.value}`)
    .then((res) => {
      ElMessage.success("已计入学习次数");
      showVideo.value = false;
      getTableData()
    })
    .catch((err) => {
      ElMessage.warning(err.message);
    });
}
//学习统计
const handleSee = (row) => {
  router.push({
    path: "/jgryandzz/Readytotal",
    query: {
      id: row.id
    }
  });
};
const changeclose = (val) => {
  if (val) {
    getTableData();
  }
  addDiaShow.value = false
}

const isShowBJBtn = (form) => {
  if (filterqx('isxgs') == 1) return false; // 县公司没有本级权
  // 新增 省市可见
  if (!form.id) return filterqx('isSgs') == 1 || filterqx('isgs') == 1;
  return form.historylevel == form.level // level 没变过才显示
}
const isShowEdit = (row) => {
  return true // 之前人人都可以编辑
  const status = row.state
  // 01 审核中，03  省审核中 不显示按钮
  if (['01', '03'].includes(status)) return false
  const isNotReported = row.historylevel == row.level // 是未否上报过
  // const isAqbm = filterqx('isaqbm') == '1'
  return isNotReported
}
const isShowDelBtn = (row) => {
  return true // 之前人人都可以编辑
  const status = row.state
  // 01 审核中，03  省审核中 不显示按钮
  if (['01', '03'].includes(status)) return false
  const isNotReported = row.historylevel == row.level // 是未否上报过
  // return filterqx('isaqbm') == '1'
  return isNotReported
}
const isShowSet = (row) => {
  return true
  const status = row.state
  // 01 审核中，03  省审核中 不显示按钮
  if (['01', '03'].includes(status)) return false
  return true
}
const isShowPush = (row) => {
  const status = row.state
  // 01 审核中，03  省审核中 不显示按钮
  if (['01', '03'].includes(status)) return false
  return true
}
//新增课件
const saveFrom = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      dialogForm.value.videopic = dialogForm.value.videopic ? dialogForm.value.videopic.toString() : null;
      dialogForm.value.videourl = dialogForm.value.videourl ? dialogForm.value.videourl.toString() : null;
      if (dialogForm.value.id) {
        postApi(dialogForm.value, '/mosty-jcgl/videoStudy/editStudy').then(res => {
          ElMessage.success('修改成功');
          loading.value = false;
          dialogVisible.value = false;
          getTableData();
        })
      } else {
        postApi(dialogForm.value, '/mosty-jcgl/videoStudy/addStudy').then(res => {
          ElMessage.success('新增成功');
          loading.value = false;
          dialogVisible.value = false;
          getTableData();
        })
      }

    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}
//删除
function handledelete(row) {
  deleteApi({}, `/mosty-jcgl/videoStudy/del/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
  });
}
//设置考题
function handletest(row) {
  rowId.value = row.id;
  comprehensiveShow.value = true;
}
//参加人员
function handlepeplo(row) {
  deptId.value = row.deptid
  rowId.value = row.id;
  addDiaShow.value = true;
}
//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  getTableData();
};
//关闭
function closeEven() {
  comprehensiveShow.value = false;
  getTableData();
}
function changeAddVi() {
  addDiaShow.value = false;
  getTableData();
}

//导出表格
const export2Excel = () => {
  loadingShow.value = true
  let title = {
    videoname: "课件名称",
    studytypes: "指定范围",
    xtCjsj: "上传时间",
    orgname: "单位名称",
    deptname: "部门名称",
    xtCjr: "人员姓名",
    clickedtime: "点击次数"
  };
  let obj = {
    deptid: listQuery.value.deptid,
    pageCurrent: 1,
    pageSize: 100000

  }
  getApi(obj, "/mosty-jcgl/videoStudy/exportData").then((res) => {
    if (res) {
      let data = res;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].studytype == "0" || data[i].studytype == "1") {
            data[i].studytypes = "全员参与";
          } else if (data[i].studytype == "2" || data[i].studytype == "3") {
            data[i].studytypes = "指定人员";
          } else {
            data[i].studytypes = "-";
          }
        }
        let tablename = `${new Date()
          .getFullYear()
          .toString()}年度在线安全学习参与学习人员清单.xlsx`;
        let tabletitle = `${new Date()
          .getFullYear()
          .toString()}年度在线安全学习参与学习人员清单`
        exportXlsx(title, data, tabletitle, tablename);
      }
    }
  }).finally(() => {
    loadingShow.value = false
  })
};
/** 打开审核详情 */
function goToAudit(query) {
  auditResData.value = {
    id: query.id,
    rwid: query.rwid
  }
  isShowKjkAuditTc.value = true
}
const kjkAuditTcClose = () => {
  isShowKjkAuditTc.value = false
  if (route.query.id) router.replace({ path: '/safety/pxzyk/zxaqxxk' })//地址还原 避免刷新就提示审核
  getTableData();
}
</script>

<style lang="scss" scoped>
.barbox {
  margin: 20px;
  width: 90%;
  height: 80vh;
}

.videos {
  margin: 40px auto;
  width: 50vw;
  height: 60vh;
}

.from_box {
  display: flex;
  justify-content: space-between;

  .from_left {
    width: 25%;

    >div {
      height: 150px;
      overflow: hidden;
    }
  }
}

.flex {
  display: flex;
  align-items: center;

  .left-tj {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: start;
  }
}

.left {
  width: 300px;
  background: #ffffff;
  box-shadow: 0px 2px 10px 0px rgba(107, 107, 107, 0.1);
  border-radius: 0px 0px 0px 0px;
  opacity: 1;

  .treeBox {
    overflow: auto;
  }
}

.el-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  padding: 0;
}

.toggle {
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #0f3916;

  .el-icon {
    transform: rotate(90deg);
    transition: all 0.25s ease;
  }

  &.active {
    .el-icon {
      transform: rotate(-90deg);
    }
  }
}



.button {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

::v-deep .el-button--default:hover {
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  color: #333 !important;
}
</style>
