<template>
  <div>
    <p class="sub_back" @click="handleBack">&#60;返回</p>
    <p class="sub_title">数字学习馆</p>
    <div class="study_detail">
      <div class="control">
        <p class="control_name">{{seriesName}}</p>
        <div>
          <el-button type="primary" @click="handleAdd" style="margin-right:20px;" v-if="userType==3">新增</el-button>
          <el-input placeholder="搜索" v-model="search" clearable prefix-icon="el-icon-search" @change="searchChange">
          </el-input>
        </div>
      </div>
      <div class="select_box">
        <p class="select_tag">文件类型：</p>
        <el-select v-model="fileExtensionName" placeholder="文件格式" @change="fileExtensionNameChange">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe v-if="tableData.length>0">
        <el-table-column label="文件名" >
          <template #default="props">
            <p class="time">{{props.row.title}}.{{props.row.type}}</p>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="teacherName" label="上传用户" >
        </el-table-column> -->
        <el-table-column label="上传时间" >
          <template #default="props">
            <p class="time">{{formatTime(props.row.createTime)}}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <a @click="handleView(scope.row)" style="cursor: pointer; margin-right: 10px">预览</a>
            <a @click="handleDownload(scope.row)" style="cursor: pointer; margin-right: 10px">下载</a>
            <a @click="handleEdit(scope.row)" style="cursor: pointer; margin-right: 10px" v-if="userType==3">修改</a>
            <el-popconfirm title="确定删除？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDel(scope.row)" v-if="userType==3">
              <template #reference>
                <a style="cursor: pointer; margin-right: 10px;color: rgb(249, 62, 62);">删除</a>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-empty description="暂无内容" v-if="tableData.length==0"></el-empty>
      <el-pagination :hide-on-single-page="total<=10" background layout="prev, pager, next" v-model="currentPage" :total="total" @current-change="handleCurrentChange">
      </el-pagination>
      <el-dialog :title="editTitle" v-model="editBoxShow">
        <el-upload class="uploader" action="" :http-request="upload" :show-file-list="false">
          <i v-if="form.urlAddress" class="el-icon-document-checked uploader-icon" style="border-color:#67c23a;color:#67c23a;"></i>
          <i v-else class="el-icon-plus uploader-icon"></i>
          <template #tip>
            <div class="el-upload__tip">上传文件(支持文件格式：.pdf,.ppt,.doc,.docx,.xls,.mp4,.mp3,.jpg,jpeg,.png)</div>
          </template>
        </el-upload>
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="文件名：" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="hideEditBox">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <transition name="el-fade-in">
        <preview v-if="showPreview" @closePreview="showPreview=false" :previewType="previewType" :previewUrl="previewUrl"></preview>
      </transition>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'
import { formatTime,deepClone } from '@/utils'
import download from 'downloadjs'
import preview from './component/preview.vue'
export default {
  name: 'StudyDetail',
  components: {
    preview
  },
  setup () {

    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { typeId, typeName, seriesId, seriesName } = route.query
    const urlReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;

    const state = reactive({
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      editBoxShow: false,//编辑框显示
      editTitle: '',
      form: {
        id: '0',
        title: '',
        size: '',
        urlAddress: '',
        teacherId: 1
      },
      rules: {
        title: [
          { required: 'true', message: '文件名不能为空', trigger: ['change'] }
        ]
      },
      options: [{
        value: '',
        label: '全部'
      }, {
        value: 'png',
        label: 'png'
      }, {
        value: 'jpg',
        label: 'jpg'
      }, {
        value: 'jpeg',
        label: 'jpeg'
      }, {
        value: 'mp3',
        label: 'mp3'
      }, {
        value: 'mp4',
        label: 'mp4'
      }, {
        value: 'zip',
        label: 'zip'
      }, {
        value: 'rar',
        label: 'rar'
      }],
      fileExtensionName: '',
      // 预览显示，预览文件类型，预览地址
      showPreview: false,
      previewType: '',
      previewUrl: '',
      userType:'',//用户身份 部分功能仅心理老师3可用
    })
    onMounted(() => {
      getResourceDetail()
      const userType = JSON.parse(localStorage.getItem('userInfo'))?.userType
      state.userType = userType
    })
    // 数字学习馆3级详情
    const getResourceDetail = () => {
      state.loading = true
      axios.post('/Resource/ResourceDetail/List', {
        "TypeId": typeId,
        "SeriesId": seriesId,
        "FileExtensionName": state.fileExtensionName,
        "Title": state.search,
        "PageIndex": state.currentPage,
        "PageSize": 10
      }).then(res => {
        // console.log('数字学习馆3级详情:', res)
        let tableData = res.data
        for (let i in tableData) {
          // 获取文件后缀
          let type = tableData[i].urlAddress.split('.')
          type = type[type.length - 1];
          tableData[i].type = type
        }
        state.tableData = tableData
        state.total = res.count
        state.loading = false
      }).catch(err => {
        console.log('err', err)

      })
    }
    // 搜索
    const searchChange = (e) => {
      getResourceDetail()
    }
    // 新建
    const handleAdd = () => {
      state.editTitle = '新建';
      state.form = {
        id: '0',
        title: '',
        size: '',
        urlAddress: '',
        teacherId: 1
      };

      state.editBoxShow = true
    }
    // 编辑修改
    const handleEdit = (e) => {
      state.form = deepClone(e);
      state.editTitle = '编辑';
      state.editBoxShow = true
    }
    // 删除
    const handleDel = (e) => {
      axios.delete('/Resource/ResourceDetail', {
        params: {
          "Id": e.id,
        }
      }).then(() => {
        ElMessage.success('删除成功')
        state.currentPage = 1;
        getResourceDetail()
      })
    }
    // 新建或修改提交
    const submitForm = () => {
      formRef.value.validate((vaild) => {
        if (vaild) {
          if (state.form.id == 0) {
            // 新建
            axios.post('/Resource/ResourceDetail', {
              "Id": 0,
              "SeriesId": seriesId,
              "Title": state.form.title,
              "Description": state.form.description,
              "UrlAddress": state.form.urlAddress,
              "DownloadCount": 0,
              "TeacherId": state.form.teacherId,
              "Size": state.form.size
            }).then(() => {
              ElMessage.success('新建成功')
              state.editBoxShow = false
              getResourceDetail()
            })
          } else {
            // 修改
            axios.put('/Resource/ResourceDetail', {
              "Id": state.form.id,
              "SeriesId": seriesId,
              "Title": state.form.title,
              "Description": state.form.description,
              "UrlAddress": state.form.urlAddress,
              "DownloadCount": 0,
              "TeacherId": state.form.teacherId,
              "Size": state.form.size
            }).then(() => {
              ElMessage.success('修改成功')
              state.editBoxShow = false
              getResourceDetail()
            })
          }
        }
      })
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e;
      getResourceDetail()
    }
    // 点击iframe遮罩
    const handleIframeMask = () => {
      state.iframeMaskShow = false;
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      resetForm()
    }
    // 点击查看
    const handleView = (e) => {
      // console.log(e)
      // 获取文件存储位置，并替换为可访问地址
      let url = e.urlAddress;
      url = url.replace('D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadStudyFile', 'http://10.238.0.182:8090/UploadStudyFile')//新昌内网
      // url = url.replace('D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadStudyFile', 'http://psychologicalapi.myjxt.com/UploadStudyFile')//21公司的服务器
      // 获取文件后缀
      let type = url.split('.')
      type = type[type.length - 1];
      if ('png,jpg,jpeg,gif,bmp,mp4,webm,ogg,wav,mp3,ogg,acc,webm'.indexOf(type) > -1) {
        state.showPreview = true;
        state.previewType = type;
        state.previewUrl = url;
      } else {
        ElMessage.error('当前所选类型文件不可预览，请下载后打开查看')
      }
    }
    // 点击下载
    const handleDownload = (e) => {
      // console.log(e)
      // 获取文件存储位置，并替换为可访问地址
      let url = e.urlAddress;
      url = url.replace('D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadStudyFile', 'http://10.238.0.182:8090/UploadStudyFile')//新昌内网
      // url = url.replace('D:\\网站\\PyhsicalAdmin\\wwwroot\\wwwroot\\UploadStudyFile', 'http://psychologicalapi.myjxt.com/UploadStudyFile')//21公司的服务器
      // 获取文件后缀
      let type = url.split('.')
      type = type[type.length - 1];
      axios.post('/Download/StudyFile?id=' + e.id, {}, { responseType: 'blob' },).then(res => {
        var blob = new Blob([res]);
        download(blob, `${e.title}.${type}`)
      })
      // 下载次数
      axios.put('/Resource/ResourceDetail/DownloadCount?id='+e.id)
    }
    const handleBack = () => {
      router.back()
    }
    // 重置表单
    const resetForm = () => {
      formRef.value.resetFields();
      state.form = {
        id: '0',
        title: '',
        size: '',
        urlAddress: ''
      };
    }
    // 上传
    const upload = (param) => {
      // console.log(param)
      const formData = new FormData()
      formData.append('file', param.file)
      axios.post('/Upload/StudyFile', formData, { headers: { "Content-Type": "multipart/form-data" } }).then(res => {
        state.form.size = res.size
        state.form.urlAddress = res.urlAddress
      })
    }
    const fileExtensionNameChange = () => {
      state.currentPage = 1;
      getResourceDetail()
    }
    return {
      ...toRefs(state),
      formRef,
      searchChange,
      handleAdd,
      handleEdit,
      handleDel,
      handleView,
      handleDownload,
      submitForm,
      typeName,
      seriesName,
      handleCurrentChange,
      handleIframeMask,
      hideEditBox,
      handleBack,
      formatTime,
      fileExtensionNameChange,
      upload
    }
  }
}
</script>
<style lang="scss" scoped>
.control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .control_name {
    font-size: 23px;
    font-weight: bold;
  }
  .el-input {
    width: 300px;
  }
}
.select_box {
  margin-bottom: 40px;
  .select_tag {
    font-size: 16px;
    display: inline-block;
  }
}
.study_detail {
  background: #fff;
  padding: 0 20px;
  padding-bottom: 40px;
  .uploader {
    margin-bottom: 50px;
  }
  .uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .el-upload__tip {
    display: inline-block;
    font-size: 16px;
    color: #999;
    margin-left: 50px;
  }
}
</style>