<template>
  <div class="app-container bus-training-video-index">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="项目名称" prop="projectName" v-if="!userStore.currentProId">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="培训名称" prop="trainTitle">
        <el-input v-model="queryParams.trainTitle" placeholder="请输入培训名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>  
      <el-form-item label="培训类型" prop="trainType">
        <el-select v-model="queryParams.trainType" placeholder="请选择培训类型" clearable> 
          <el-option v-for="dict in edu_train_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> 
      <el-form-item label="工种岗位" prop="craftPost">
        <el-select v-model="queryParams.craftPost" placeholder="请选择工种岗位" clearable> 
          <el-option v-for="dict in pro_craft_post" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>       
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:busTrainingVideo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:busTrainingVideo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:busTrainingVideo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:busTrainingVideo:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
   
    <el-tabs
    v-model="queryParams.trainLevel"
    type="card"
    class="demo-tabs"
    @tab-change="getList"
  >
    <el-tab-pane :label="'公司级（'+tabs.gsj+'）'" name="2" />
    <el-tab-pane :label="'项目级（'+tabs.xmj+'）'" name="3" />
    <el-tab-pane :label="'班组级（'+tabs.bzj+'）'" name="4" />
  </el-tabs>
    <el-table v-loading="loading" :data="busTrainingVideoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属公司" align="center" prop="comName" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          <span v-if="scope.row.comId">{{scope.row.comName}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="projectName" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          <span v-if="scope.row.projectId">{{scope.row.projectName}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="培训名称" align="center" prop="trainTitle"/>
      <el-table-column label="培训类型" align="center" prop="trainType" width="120">
        <template #default="scope">
          <dict-tag :options="edu_train_type" :value="scope.row.trainType" />
        </template>
      </el-table-column>
      <el-table-column label="培训级别" align="center" prop="trainLevel" width="100">
        <template #default="scope">
          <dict-tag :options="edu_train_level" :value="scope.row.trainLevel" />
        </template>
      </el-table-column>
      <el-table-column label="工种岗位" align="center" width="450">
        <template #default="scope">
          <div v-if="scope.row.craftPost" class="flex gap-2">
            <el-tag
              v-for="dict in pro_craft_post"
              v-show="scope.row.craftPost.indexOf(dict.value)>-1"
              effect="dark"
            >
              {{ dict.label }}
            </el-tag>
          </div>
          <div v-if="!scope.row.craftPost">-</div>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="isDel" width="88">
        <template #default="scope">
          <el-tooltip :content="scope.row.isDel == 0 ? '启用' : '停用'" placement="top">
            <el-switch
              :active-value="parseInt(0)"
              :inactive-value="parseInt(1)"
              v-model="scope.row.isDel"
              :disabled="scope.row.disabledState"
              @change="setStatus($event, scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="培训时长" align="center" prop="palyTimes" width="80">
        <template #default="scope">{{ scope.row.palyTimes }}秒</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="播放" align="center" width="80">
        <template #default="scope">
          <el-button type="primary" link icon="VideoPlay" @click="handlePlayVideo(scope.row)">播放</el-button>
        </template>
      </el-table-column>  
      <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="!scope.row.disabledState" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:busTrainingVideo:edit']">修改</el-button>
          <el-button v-if="!scope.row.disabledState" link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:busTrainingVideo:remove']">删除</el-button>
          <el-button v-if="scope.row.disabledState" type="danger" link disabled>-</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改培训视频对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body modal-class="bus-training-video-dlg">
      <el-form ref="busTrainingVideoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属公司" v-if="form.comId">
          <el-tag effect="plain">{{ form.comName }}</el-tag>
        </el-form-item>
        <el-form-item label="项目名称" v-if="form.projectId && form.trainLevel && form.trainLevel!='1'" >
          <el-tag effect="plain">{{ form.projectName }}</el-tag>
        </el-form-item>
        <el-form-item label="培训类型" prop="trainType">
          <el-select v-model="form.trainType" placeholder="请选择培训类型" style="width:100%">
            <el-option v-for="dict in edu_train_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训名称" prop="trainTitle">
          <el-input v-model="form.trainTitle" placeholder="请输入培训名称" maxlength="64" show-word-limit />
        </el-form-item>        
        <el-form-item label="培训级别" prop="trainLevel">
          <el-select v-model="form.trainLevel" placeholder="请选择培训级别" @change="trainLevelChange" style="width:100%">
            <el-option v-for="dict in data.eduTrainLevelList" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工种岗位" prop="craftPost">
          <el-cascader
            v-model="form.craftPost"
            :options="craftPostOptions"
            :props="casProps"
            style="width: 100%"
            placeholder="请选择工种岗位"
          />
        </el-form-item>
        <el-form-item label="播放时长" prop="palyTimes">
          <el-input v-model.number="form.palyTimes" placeholder="请输入播放时长" maxlength="8" show-word-limit/>
        </el-form-item>
        <el-form-item label="播放排序" prop="sortBy">
          <el-input v-model.number="form.sortBy" placeholder="请输入播放排序" maxlength="8" show-word-limit/>
        </el-form-item>
        <el-form-item label="培训视频" prop="trainFilePath">
          <file-upload v-model="form.trainFilePath" :limit="1" :fileType="['mp4']" :fileSize="500" />
        </el-form-item>
        <el-form-item label="视频主图" prop="trainFileImage">
          <file-upload v-model="form.trainFileImage" :limit="1" :fileType="['jpg','jpeg','png']" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--培训视频播放对话框 -->
    <el-dialog :title="videoTitle" v-model="videoOpen" width="680px" append-to-body modal-class="video-play-dlg">
      <video
        ref="videoRef"
        :src="videoSrc"
        controls="controls"
        autoplay="autoplay"
        :poster="videoPoster?videoPoster:poster"
        style="width: 100%;max-height: 550px"
      />
    </el-dialog>
  </div>
</template>

<script setup name="BusTrainingVideo">
import poster from '@/assets/images/poster.gif'
import { listBusTrainingVideo, findBusTrainingVideo, getBusTrainingVideo, delBusTrainingVideo, addBusTrainingVideo, updateBusTrainingVideo } from "@/api/manage/busTrainingVideo";
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const { edu_train_level, edu_train_type, pro_craft_type, sys_is_del, pro_craft_post } = proxy.useDict('edu_train_level', 'edu_train_type', 'pro_craft_type', 'sys_is_del', 'pro_craft_post');

const busTrainingVideoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tabs = ref({'gsj':0,'xmj':0,'bzj':0});
const activeName = ref("gsj");
const craftPostOptions = ref([]);

const videoSrc = ref("");
const videoPoster = ref("");
const videoOpen = ref(false);
const videoTitle = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    comId: null,
    projectId: null,
    projectName: null,
    trainTitle: null,
    trainType: null,
    trainLevel: '2',
    craftPost: null,
    isDel: null,
  },
  rules: {
    trainType:[{ required: true, message: "培训类型不能为空", trigger: "blur" }],
    trainTitle:[{ required: true, message: "培训名称不能为空", trigger: "blur" }],
    trainLevel:[{ required: true, message: "培训级别不能为空", trigger: "blur" }],
    craftPost:[{ required: true, message: "工种岗位不能为空", trigger: "blur" }],
    sortBy:[{ required: true, message: "显示排序不能为空", trigger: "blur" },{ type: "number", message: "请输入数字类型", trigger: "blur" }],
    trainFilePath:[{ required: true, message: "培训视频不能为空", trigger: "blur" }],
    trainFileImage:[{ required: true, message: "视频主图不能为空", trigger: "blur" }],
  },
  craftPostList:[],
  queryCraftPostList:[]
});

const { queryParams, form, rules } = toRefs(data);
const userStore = useUserStore()

const casProps = {
  value: "value",
  label: "label",
  multiple: true,
};

/** 查询培训视频列表 */
function getList() {
  loading.value = true;
  listBusTrainingVideo(queryParams.value).then(response => {
    response.rows.forEach(item => {
      item.disabledState = initRowDisabled(item);
    })
    busTrainingVideoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  findCount();
}

function findCount() {
  findBusTrainingVideo(queryParams.value).then(response => {
    let countMap = {'gsj':0,'xmj':0,'bzj':0};
    response.data.forEach(item =>{
      if(item.trainLevel=='2'){
        countMap.gsj = item.total;
      }else if(item.trainLevel=='3'){
        countMap.xmj = item.total;
      }else if(item.trainLevel=='4'){
        countMap.bzj = item.total;
      }else{
        //忽略...
      }
    });
    tabs.value = countMap;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    projectId: null,
    trainTitle: null,
    trainType: null,
    trainLevel: null,
    craftType: null,
    craftPost: null,
    trainFileType: null,
    trainFilePath: null,
    trainFileImage: null,
    trainFileTimes: null,
    compName:null,
    ord:1,
    remark: null
  };
  proxy.resetForm("busTrainingVideoRef");
  data.craftPostList=[]
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if(!userStore.currentComId){
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    open.value = false;
    return false;
  }
  reset();
  initPost();
  form.value.comId = userStore.currentComId;
  form.value.comName = userStore.currentComName;
  open.value = true;
  title.value = "添加培训视频";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  initPost();
  const _id = row.id || ids.value
  getBusTrainingVideo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改培训视频";
  });
}

/** 培训级别操作 */
function trainLevelChange(){
  if(form.value.trainLevel){
    if(form.value.trainLevel=='3' || form.value.trainLevel=='4'){
      if(!userStore.currentProId){
        proxy.$modal.msgWarning("请切换到项目数据！！！");
        open.value = false;
        return false;
      }else{
        form.value.projectId = userStore.currentProId;
        form.value.projectName = userStore.currentProName;
      }
    }else{
      form.value.projectId = null;
      form.value.projectName = null;
    }
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["busTrainingVideoRef"].validate(valid => {
    if (valid) {
      form.value.remark = JSON.stringify(form.value.craftPost);
      let craftTypeValues = [];
      let craftPostValues = [];
      form.value.craftPost.forEach((item) => {
        if(craftTypeValues.indexOf(item[0])<0){
          craftTypeValues.push(item[0]);
        }
        craftPostValues.push(item[1]);
      });
      form.value.craftType = craftTypeValues.toString();
      form.value.craftPost = craftPostValues.toString();
      if (form.value.id != null) {
        updateBusTrainingVideo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBusTrainingVideo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 启用状态滑块控制 */
function setStatus(val, row) {
  proxy.$modal
    .confirm(`是否确认${val == 0 ? "启用" : "停用"}当前数据项？`)
    .then(function () {
      let param = {'id': row.id, 'isDel': val};
      return updateBusTrainingVideo(param);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("修改成功");
    })
    .catch(() => {
      // 取消时恢复原始开关状态
      if (val == 0) {
        row.isDel = 1;
      } else {
        row.isDel = 0;
      }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除培训视频编号为"' + _ids + '"的数据项？').then(function () {
    return delBusTrainingVideo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/busTrainingVideo/export', {
    ...queryParams.value
  }, `busTrainingVideo_${new Date().getTime()}.xlsx`)
}

/** 播放视频操作 */
function handlePlayVideo(row) {
  videoSrc.value = row.trainFilePath;
  videoPoster.value = row.trainFileImage;
  videoOpen.value = true;
  videoTitle.value = "视频播放 #"+row.trainTitle;
}

/** 初始化行标识 */
function initRowDisabled(row) {
  let roles = userStore.roles;
  if(roles.includes("admin")){
    return false;
  }else if(roles.includes("gsAdmin") && row.comId){
    return false;
  }else if(row.projectId){
    return false;
  }else{
    return true;
  }
}

/** 初始化岗位 */
function initPost() {
  let craftTypeDatas=pro_craft_type._object.pro_craft_type;
  let craftPostDatas=pro_craft_post._object.pro_craft_post;
  craftTypeDatas.forEach(item =>{
    item.children = craftPostDatas.filter(deatil=>deatil.elTagClass==item.value);
  });
  console.log("DEFAULT" , craftTypeDatas);
  craftPostOptions.value = craftTypeDatas;
  initTrainLevel();
}

function initTrainLevel() {
  let datas=edu_train_level._object.edu_train_level;
  let roles = userStore.roles;
  if(roles.includes("admin") || roles.includes("gsAdmin")){
    // 管理员添加所有数据
    data.eduTrainLevelList = datas;
  }else{
    data.eduTrainLevelList = datas.filter(detail=>detail.value!='2');
  }
}
  
getList();
</script>
<style lang="scss">
.gap-2{
  .el-tag--default{
    margin:2px 3px;
  }
}
.bus-training-video-dlg{
  .el-dialog__body{
    overflow: auto;
    max-height: 680px;
  }
}
.bus-training-video-index{
   .fitem-craft-type{
      .el-select{
         width:150px;
      }
   }
}
.bus-training-video-dlg{
  .fitem-video{
    &.has-video{
      .el-form-item__content{
        .upload-file-uploader{
          display: none;
        }
        .el-upload__tip{
          display: none;
        }
      }
    }
  }
}
.video-play-dlg{
  .el-dialog__body{
    padding: 10px;
  }
}
</style>