<template>
  <div class="app-container apkfile">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="关键字" prop="subName" label-width="95px">
        <el-input
          v-model="queryParams.versionName"
          placeholder="版本名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="onepcType" label-width="75px">
        <el-select v-model="queryParams.onepcType" placeholder="请选择设备类型" clearable size="small">
          <el-option label="管控一体机" value="1" />
          <el-option label="考试一体机" value="2" />
          <el-option label="电子信息牌" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-col :span="1.5">
          <p class="add-button-one-90"
             style="margin-left:10px;"
             @click="upPage"
          >上传APK</p>
        </el-col>
      </el-form-item>
      <el-form-item>
        <p class="inquire-button-one" @click="handleQuery">查询</p>
        <p class="reset-button-one" @click="resetQuery">重置</p>
      </el-form-item>

    </el-form>

    <el-table border v-loading="loading" :data="logList">
      <el-table-column label="版本名称" align="left" prop="versionName" />
      <el-table-column label="版本号" align="left" prop="version" />
      <el-table-column label="设备类型" align="left" prop="onepcType" >
        <template slot-scope="scope">
          <p>{{scope.row.onepcType==1?'管控一体机':(scope.row.onepcType==2?'考试一体机':(scope.row.onepcType==3?'电子信息牌':''))}}</p>
        </template>
      </el-table-column>
      <el-table-column label="说明信息" align="left" prop="apkInfo" :show-overflow-tooltip="true"/>
      <el-table-column label="APK大小" align="left" prop="fileData" >
        <template slot-scope="scope" v-if="scope.row.fileData">
          <p>{{scope.row.fileData.size}}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="left" prop="createBy" />
      <el-table-column label="创建时间" align="left" prop="createTime" />
      <el-table-column label="操作" align="left" width="160">
        <template slot-scope="scope">
          <div style="display: flex;justify-content: flex-start;">
            <p style="color: #0183fa;cursor: pointer" @click="handleClick('',scope.row,'download')">下载</p>
            <p style="color: #0183fa;cursor: pointer;margin-left: 20px"  @click="handleClick('',scope.row,'edit')">编辑</p>
            <p style="color: #0183fa;cursor: pointer;margin-left: 20px"  @click="handleClick('',scope.row,'delete')">删除</p>
          </div>

        </template>
      </el-table-column>
    </el-table>
    <pagination :page-sizes="[20, 30, 40, 50]"
      v-show="total>0"
      :total="total"
      layout="total, prev, pager, next, sizes, jumper"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--上传APK-->
    <el-dialog title="上传APK" class="dialog-up-data-box" :visible.sync="openUp" v-if="openUp" width="570px" append-to-body :close-on-click-modal="false">
      <div class="dialog-up-data-min-box scrollbar-box">
        <el-form  v-loading="loading" :rules="apkRules" :model="upForm" ref="upForm" :inline="true" v-show="showSearch">
          <el-form-item label="版本名称" prop="versionName" label-width="90px">
            <el-input
              v-model="upForm.versionName"
              maxLength="20"
              placeholder="请输入版本名称"
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="版本编号" prop="version" label-width="90px">
            <el-input
              v-model="upForm.version"
              maxLength="20"
              placeholder="请输入版本编号"
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="版本描述" prop="apkInfo" label-width="90px">
            <el-input
              type="textarea"
              v-model="upForm.apkInfo"
              maxLength="800"
              placeholder="请输入版本描述"
              clearable
              :rows="5"
              show-word-limit
              style="width: 300px;"
            />
          </el-form-item>
          <el-form-item label="类型" prop="onepcType" style="display: block" label-width="90px">
            <el-radio v-model="upForm.onepcType" label="1">管控一体机</el-radio>
            <el-radio v-model="upForm.onepcType" label="2">考试一体机</el-radio>
            <el-radio v-model="upForm.onepcType" label="3">电子信息牌</el-radio>
          </el-form-item>
          <el-form-item label="安装包" prop="apkFileUpload" label-width="90px">
            <uploader
              :autoStart="false"
              :options="options"
              ref="uploader"
              :file-list="fileList"
              :file-status-text="statusText"
              class="uploader-example"
              @file-complete="fileComplete"
              @complete="complete"
              @file-success="fileSuccess"
              @files-added="filesAdded">
              <uploader-unsupport></uploader-unsupport>
              <uploader-drop>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或 <uploader-btn :single="true" :attrs="attrs">点击上传</uploader-btn></div>
              </uploader-drop>
              <div class="text-box" v-if="fileData.name">
                <p>{{fileData.name}}</p>
                <p>{{fileData.size}}</p>
                <p>{{fileData.text}}</p>
              </div>
            </uploader>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormUp">确 定</el-button>
        <el-button @click="cancelUp">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLog,
  apkUploadList,
  getApkUploadList,
  addApkUpload,
  apkUploadDelete,
  editApkList
} from '@/api/laboratory/apkfile'
  import { getToken } from "@/utils/auth";
  import axios from 'axios'
  import SparkMD5 from 'spark-md5'
  import { delSensor } from '@/api/laboratory/subject'
  let httpHeader=window.location.href.split('://')[0]+'://'
  export default {
    name: "Log",
    data() {
      return {
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // apk需要对应升级的日志表格数据
        logList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize:20,
          searchValue: null,
          versionName: null,
          onepcType: null,
        },
        openUp:false,
        //文件列表
        fileList:[],
        options: {
          target: httpHeader+this.judgmentNetworkReturnAddress()+"/base/file/upload/chunk",
          // 开启服务端分片校验功能
          testChunks: true,
          single: true,
          fileParameterName: 'file',
          headers: {
            Authorization: "Bearer " + getToken()
          },
          parseTimeRemaining: function (timeRemaining, parsedTimeRemaining) {
            return parsedTimeRemaining
              .replace(/\syears?/, "年")
              .replace(/\days?/, "天")
              .replace(/\shours?/, "小时")
              .replace(/\sminutes?/, "分钟")
              .replace(/\sseconds?/, "秒");
          },
          // // 服务器分片校验函数
          checkChunkUploadedByResponse: (chunk, message) => {
            const result = JSON.parse(message);
            if (result.data.skipUpload) {
              this.skip = true;
              return true;
            }
            return (result.data.uploaded || []).indexOf(chunk.offset + 1) >= 0;
          },
        },
        //上传数据
        upForm:{
          id:'',
          versionName:null,
          version:null,
          apkInfo:null,
          onepcType:null,
          apkFileUpload:null,

        },
        // apk上传表单校验
        apkRules: {
          versionName: [
            { required: true, message: "请输入版本名称", trigger: "blur" }
          ],
          apkInfo: [
            { required: true, message: "请输入版本描述", trigger: "blur" }
          ],

          version: [
            { required: true, message: "请输入版本编号", trigger: "blur" },
            { required: true, message: "只能输入数字", validator: this.isNum, trigger: "blur" },
          ],
          onepcType: [
            { required: true, message: "请选择版本类型", trigger: "blur" }
          ],
          apkFileUpload: [
            { required: true, message: "请上传安装包", trigger: "blur" }
          ],
        },
        attrs: {
          accept: [".apk"]
        },
        statusText: {
          success: "上传成功",
          error: "上传出错了",
          uploading: "上传中...",
          paused: "暂停中...",
          waiting: "等待中...",
          cmd5: "计算文件MD5中...",
        },
        fileData:{},
      };
    },
    created() {
      this.getList();
    },
    methods: {
      //版本管理页面开关
      upPage(){
        this.apkGetList();
        this.$set(this,'upForm',{});
        this.$set(this,'fileData',{});
        this.openUp = true;
      },
      //apk列表获取
      apkGetList() {
        this.loading = true;
        listLog(this.queryParams).then( response => {
          this.apkLogList =  response.rows;
          this.apkTotal =  response.total;
          this.loading = false;
        });
      },
      //开始上传
      progressUp(event, file, fileList){
        this.loading = true;
      },
      //上传成功
      handleAvatarSuccess(res, file,index) {
        this.upForm.apkFileUpload = res.data.url;
        this.loading = false;
        this.$forceUpdate()
      },
      //上传失败
      errorUp(err, file, fileList){
        this.loading = false;
      },
      //上传检查
      beforeAvatarUpload(file) {
        let type = false;
        if (file.type == 'application/vnd.android.package-archive') {
          type = true;
        }else{
          this.$message.error('只能上传APK格式文件');
          type = false;
        }
        console.log('file',file);
        return type;
      },
      // 新增/编辑节点单击事件
      handleNodeClick(data) {
        this.form.deptId = data;
        this.getSubjectDictList(data);
      },
      // 新增/编辑节点单击事件
      handleNodeClick2(data) {
        this.$set(this.form, 'apkId', '')
        let params = {};
        if(data){
          params.onepcType = data;
        }
        console.log("params",params)
        getApkUploadList(params).then(response => {
          this.$set(this, 'apkIdOptions', response.data)
        });
      },
      handleClick(index,row,doType){
        if(doType=='download'){
          window.open(window.location.href.split('://')[0]+'://' + this.judgmentNetworkReturnAddress() + row.apkFileUpload)
        }else if(doType=='edit'){
          this.upForm.id=row.id
          this.upForm.versionName=row.versionName
          this.upForm.version=row.version
          this.upForm.apkInfo=row.apkInfo
          this.upForm.onepcType=row.onepcType.toString()
          this.upForm.apkFileUpload=row.apkFileUpload
          if(row.fileData){
            this.upForm.fileData=row.fileData
            this.fileData=row.fileData
          }
          this.openUp=true
        }else if(doType=='delete'){
          this.$confirm('确认要删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            //  确定
            apkUploadDelete(row.id).then((response) => {
              this.msgSuccess(response.msg)
              this.getList();
            });
          }).catch(function() {
            //  取消
          });
        }
      },
      /** 查询apk需要对应升级的日志列表 */
      getList() {
        this.loading = true;
        apkUploadList(this.queryParams).then( response => {
          this.total =  response.total;
          this.loading = false;
          this.logList =  response.rows;
          this.logList.forEach(function(item) {
            if(item.fileData){
              item.fileData=JSON.parse(item.fileData)
            }
          })
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.versionName='';
        this.queryParams.onepcType='';
        this.handleQuery();
      },
      fileSuccess(rootFile, file, response, chunk) {
        const result = JSON.parse(response);
        if (result.code == 200 && !this.skip) {
          axios.post(httpHeader+this.judgmentNetworkReturnAddress()+"/base/file/upload/merge", {
            identifier: file.uniqueIdentifier,
            filename: file.name,
            totalChunks: chunk.offset,
          },{
            headers: {
              Authorization: "Bearer " + getToken()
            }
          }).then((res) => {
            if (res.data.code==200) {
              this.upForm.apkFileUpload=res.data.data;
            } else {
              console.log(res);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          console.log("上传成功，不需要合并");
        }
        if (this.skip) {
          this.skip = false;
        }
      },
      fileComplete(rootFile) {
        // 一个根文件（文件夹）成功上传完成。
        this.fileName=rootFile.name;
        this.fileSize=rootFile.size;
        console.log("rootFile",rootFile)
        this.fileData = {
          name:rootFile.name,
          size:(parseInt(rootFile._prevUploadedSize/1024)/1024).toFixed(2)+'MB',
          text:"上传完成"
        }
      },
      complete(file) {
        console.log("complete file:",file)
        // 上传完毕。
      },
      filesAdded(file, fileList, event) {
        this.fileData = {
          name:file[0].name,
          size:"",
          text:"上传中..."
        }
        console.log("file",file)
        console.log("fileList",fileList)
        console.log("event",event)
        // this.$refs.uploader.fileList = [];
        // this.$refs.uploader.files = [];
        this.fileList=[];
        file.forEach((e) => {
          this.fileList.push(e);
          this.computeMD5(e);
        });
      },
      computeMD5(file) {
        let fileReader = new FileReader();
        let time = new Date().getTime();
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
        let currentChunk = 0;
        const chunkSize = 1024 * 1024;
        let chunks = Math.ceil(file.size / chunkSize);
        let spark = new SparkMD5.ArrayBuffer();
        // 文件状态设为"计算MD5"
        file.cmd5 = true; //文件状态为“计算md5...”
        file.pause();
        loadNext();
        fileReader.onload = (e) => {
          spark.append(e.target.result);
          if (currentChunk < chunks) {
            currentChunk++;
            loadNext();
            // 实时展示MD5的计算进度
          } else {
            let md5 = spark.end();
            spark.destroy(); //释放缓存
            file.uniqueIdentifier = md5; //将文件md5赋值给文件唯一标识
            file.cmd5 = false; //取消计算md5状态
            file.resume(); //开始上传
          }
        };
        fileReader.onerror = function () {
          this.error(`文件${file.name}读取出错，请检查该文件`);
          file.cancel();
        };
        function loadNext() {
          let start = currentChunk * chunkSize;
          let end = start + chunkSize >= file.size ? file.size : start + chunkSize;
          fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
        }
      },
      allStart() {
        this.fileList.map((e) => {
          if (e.paused) {
            e.resume();
          }
        });
      },
      allStop() {
        this.fileList.map((e) => {
          if (!e.paused) {
            e.pause();
          }
        });
      },
      allRemove() {
        this.fileList.map((e) => {
          e.cancel();
        });
        this.fileList = [];
      },
      // 取消按钮
      cancelUp() {
        if (this.loading){
          return
        }
        this.fileList=[];
        this.fileData = {};
        this.openUp = false;
      },
      //上传apk提交按钮
      submitFormUp(){
        if(this.loading){
          return
        }
        if(this.upForm.id){//编辑
          this.$refs["upForm"].validate(valid => {
            if (valid) {
              let obj = {
                id:this.upForm.id,
                versionName:this.upForm.versionName,
                version:this.upForm.version,
                apkInfo:this.upForm.apkInfo,
                onepcType:this.upForm.onepcType,
                apkFileUpload:this.upForm.apkFileUpload,
                fileData:JSON.stringify(this.fileData),
              };
              editApkList(obj).then( response => {
                this.msgSuccess("编辑成功");
                this.getList()
                this.openUp = false;
                this.upForm = {};
                this.fileList=[];
                this.fileData = {};
              });
            }
          });

        }else{//添加
          this.$refs["upForm"].validate(valid => {
            if (valid) {
              let obj = {
                versionName:this.upForm.versionName,
                version:this.upForm.version,
                apkInfo:this.upForm.apkInfo,
                onepcType:this.upForm.onepcType,
                apkFileUpload:this.upForm.apkFileUpload,
                fileData:JSON.stringify(this.fileData),
              };
              addApkUpload(obj).then( response => {
                this.msgSuccess("新增成功");
                this.getList()
                this.openUp = false;
                this.upForm = {};
                this.fileList=[];
                this.fileData = {};
              });
            }
          });
        }

      },
    }
  };
</script>

<style scoped lang="scss">
  .apkfile {
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:20px 20px 20px!important;
    .button-box{
      width:90px;
      display: flex;
      margin:0 auto;
    }
  }
</style>
<style lang="scss">
  .dialog-up-data-box{
    .text-box{
      width:360px;
      display: flex;
      p:nth-child(1){
        width:200px;
        display:block;
        overflow:hidden;
        text-overflow:ellipsis;
        white-space:nowrap;
      }
      p:nth-child(2){
        width:100px;
        text-align: center;
      }
      p:nth-child(3){
        width:60px;
        text-align: right;
      }
    }
    .dialog-up-data-min-box{
      height:500px;
    }
    .uploader-drop{
      width:360px;
      .el-icon-upload{
        color:#0183FA;
        display: block;
        font-size:78px;
        width:78px;
        height:78px;
        margin:0 auto;
      }
      .el-upload__text{
        width:210px;
        margin:0 auto;
      }
      .uploader-btn{
        border:none;
        color:#0183FA;
      }
    }
    .uploader-files{
      width:360px;
    }
  }
</style>
