<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.searchValue"
          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-select>
      </el-form-item>
      <el-form-item label="状态" prop="logStatus" label-width="45px">
        <el-select v-model="queryParams.logStatus" placeholder="请选择状态" clearable size="small">
          <el-option label="安装成功" value="1" />
          <el-option label="安装失败" value="0" />
          <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"
             @click="handleAdd"
             v-hasPermi="['laboratory:apkfile:add']"
          >批量升级</p>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <p class="add-button-one-90"-->
<!--             style="margin-left:10px;"-->
<!--             @click="upPage"-->
<!--             v-hasPermi="['laboratory:apkfile:add']"-->
<!--          >上传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 v-loading="loading" :data="logList">
      <el-table-column label="所属实验室" align="left" prop="subName" />
      <el-table-column label="设备名称" align="left" prop="hardName" />
      <el-table-column label="设备类型" align="left" prop="onepcType" >
        <template slot-scope="scope">
          <p>{{scope.row.onepcType==1?'管控一体机':(scope.row.onepcType==2?'考试一体机':'')}}</p>
        </template>
      </el-table-column>
      <el-table-column label="版本名称" align="left" prop="versionName" />
      <el-table-column label="版本编号" align="left" prop="version" />
      <el-table-column label="状态" align="left" prop="logStatus" >
        <template slot-scope="scope">
          <p>{{scope.row.logStatus==0?'安装失败':(scope.row.logStatus==1?'安装成功':(scope.row.logStatus==2?'安装中':(scope.row.logStatus==3?'上传成功':'')))}}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div class="button-box">
            <p class="table-button-one-90"
               @click="handleUpdate(scope.row)"
               v-hasPermi="['laboratory:apkfile:edit']"
            ><i class="el-icon-edit-outline"></i>修改</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"
    />

    <!-- 批量升级 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="院系" prop="deptId" v-if="!form.id">
          <el-select v-model="form.deptId" placeholder="请选择院系" @change="handleNodeClick">
            <el-option
              v-for="dict in deptOptions"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验室" prop="subjectId" v-if="!form.id">
          <el-select v-model="form.subjectId" multiple placeholder="请选择实验室">
            <el-option
              v-for="item in subjectOptions"
              :key="item.subjectId"
              :label="item.name"
              :value="item.subjectId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验室" v-if="form.id" style="width:297px;">
          <el-input
            v-model="form.subName"
            disabled
            placeholder=""
            clearable

          />
        </el-form-item>

        <el-form-item label="设备类型" prop="onepcType2" style="width:297px;" v-if="!form.id">
          <el-select v-model="form.onepcType2" placeholder="请选择设备类型" @change="handleNodeClick2">
            <el-option v-for="dict in onepcTypeList" :key="dict.id" :label="dict.name" :value="dict.id" ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备名称" v-if="form.id" style="width:297px;">
          <el-input
            v-model="form.hardName"
            disabled
            placeholder=""
            clearable

          />
        </el-form-item>
        <el-form-item label="设备类型" prop="onepcType" v-if="form.id" style="width:297px;">
          <el-select v-model="form.onepcType" disabled placeholder="请选择设备类型" @change="handleNodeClick">
            <el-option v-for="dict in onepcTypeList" :key="dict.id" :label="dict.name" :value="dict.id" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本名称" prop="apkId">
          <el-select v-model="form.apkId" placeholder="请选择版本">
            <el-option
              v-for="item in apkIdOptions"
              :key="item.apkId"
              :label="item.versionName"
              :value="item.apkId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--上传APK-->
    <el-dialog title="上传APK" class="dialog-up-data-box" :visible.sync="openUp" v-if="openUp" width="570px" append-to-body>
      <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="version" label-width="90px">
            <el-input
              type="textarea"
              v-model="upForm.apkInfo"
              maxLength="1000"
              placeholder="请输入版本描述"
              clearable
              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-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-list></uploader-list> -->
              <!--<uploader-files></uploader-files>-->
            </uploader>
          </el-form-item>



            <!--<el-form-item label="安装包" prop="apkFileUpload" label-width="90px">-->
              <!--<el-upload-->
                <!--style="margin:0 auto;width:120px;"-->
                <!--class="avatar-uploader"-->
                <!--:action="uploadImgUrl"-->
                <!--accept="application/vnd.android.package-archive"-->
                <!--:show-file-list="false"-->
                <!--:on-progress="progressUp"-->
                <!--:on-success="handleAvatarSuccess"-->
                <!--:on-error="errorUp"-->
                <!--:headers="headers"-->
                <!--:before-upload="beforeAvatarUpload">-->
                <!--<img v-if="upForm.apkFileUpload" src="@/assets/ZDimages/icon_apk.png">-->
                <!--<i v-if="!upForm.apkFileUpload" class="el-icon-plus avatar-uploader-icon" style="height:40px;line-height:40px;width:40px;text-align: center"></i>-->
              <!--</el-upload>-->
            <!--</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>
      <!--<div v-loading="loading">-->
      <!--<el-table :data="apkLogList">-->
      <!--<el-table-column label="版本名称" align="left" prop="versionName" />-->
      <!--<el-table-column label="版本编号" align="left" prop="version" />-->
      <!--<el-table-column label="上传时间" align="left" prop="createTime" />-->
      <!--</el-table>-->
      <!--<pagination-->
      <!--style="height:50px;"-->
      <!--v-show="apkTotal>0"-->
      <!--:total="apkTotal"-->
      <!--:page.sync="apkQueryParams.pageNum"-->
      <!--:limit.sync="apkQueryParams.pageSize"-->
      <!--@pagination="apkGetList"-->
      <!--/>-->
      <!--</div>-->
    </el-dialog>
  </div>
</template>

<script>
  import { listLog, getLog, delLog, addLog, updateLog, getApkUploadList,apkFileAddApkLog,updateApkLog,getApkUploadListByLimit,addApkUpload } from "@/api/laboratory/apkfile";
  import { subjectDictList } from "@/api/laboratory/record";
  import { listDepartments } from "@/api/system/dept";
  import { getToken } from "@/utils/auth";
  import axios from "axios";
  import SparkMD5 from "spark-md5";
  let httpHeader=window.location.href.split('://')[0]+'://'

  export default {
    name: "Log",
    data() {
      return {
        // 上传相关
        uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // apk需要对应升级的日志表格数据
        logList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize:20,
          searchValue: null,
          onepcHardwareNum: null,
          apkUploadId: null,
          logStatus: null,
          onepcType: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          deptId: [
            { required: true, message: "请选择院系", trigger: "blur" }
          ],
          apkId: [
            { required: true, message: "分类名称不能为空", trigger: "blur" }
          ],
          onepcType2: [
            { required: true, message: "设备类型不能为空", trigger: "blur" }
          ],
        },
        // 院系列表
        deptOptions: [],
        onepcTypeList:[
          {id:1,name:"管控一体机",},
          {id:2,name:"考试一体机",}
        ],
        //实验室列表
        subjectOptions: [],
        //文件列表
        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;
          },
        },
        //  上传页面开关
        openUp:false,
        //apk列表
        apkIdOptions:[],
        //apk 列表查询参数
        apkQueryParams: {
          pageNum: 1,
          pageSize:20,
        },
        //上传数据
        upForm:{},
        // apk上传表单校验
        apkRules: {
          versionName: [
            { 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)
        });
      },
      /** 查询院系列表 */
      getDeptList() {
        listDepartments().then(response => {
          this.$set(this, 'deptOptions', response.data)
        });
      },
      /** 查询apk列表 */
      getApkUploadList(row) {
        let params = {};
        if(row){
          params.onepcType = row.onepcType;
        }
        console.log("params",params)
        getApkUploadList(params).then(response => {
          this.$set(this, 'apkIdOptions', response.data)
        });
      },
      /** 查询实验室字典列表 */
      getSubjectDictList (deptId) {
        this.subjectOptions = null;
        this.loading = true;
        let params = {};
        params.deptId = deptId;
        subjectDictList(params).then(response => {
          this.form.subjectId = [];
          for(let i=0;i<response.data.length;i++){
            response.data[i].subjectId = response.data[i].id;
          }
          this.subjectOptions = response.data;
          this.loading = false;
        });
      },
      /** 查询apk需要对应升级的日志列表 */
      getList() {
        this.loading = true;
        listLog(this.queryParams).then( response => {
          this.logList =  response.rows;
          this.total =  response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      // 取消按钮
      cancelUp() {
        if (this.loading){
          return
        }
        this.fileList=[];
        // this.$refs.uploader.files = [];
        // this.$refs.uploader.fileList = [];
        //this.$refs.uploader.allRemove();
        this.fileData = {};
        this.openUp = false;
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          onepcHardwareNum: null,
          apkUploadId: null,
          logStatus: 0,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.searchValue='';
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.form = {
          deptId:"",
          subjectId:[],
          apkId:"",
        };
        this.open = true;
        this.getDeptList();
        this.getApkUploadList();
        this.subjectOptions = [];
        this.title = "批量升级";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.getApkUploadList(row);
        this.form =  row;
        this.open = true;
        this.title = "修改";
      },
      //上传apk提交按钮
      submitFormUp(){
        if(this.loading){
          return
        }
        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,
            };
            addApkUpload(obj).then( response => {
              this.msgSuccess("新增成功");
              this.openUp = false;
              this.upForm = {};
              this.fileList=[];
              // this.$refs.uploader.files = [];
              // this.$refs.uploader.fileList = [];
              // this.$refs.uploader.cancel()
              this.fileData = {};
            });
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              let obj = {
                id:this.form.id,
                apkId:this.form.apkId,
              };
              updateApkLog(obj).then( response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              let obj = {
                deptId:this.form.deptId,
                apkId:this.form.apkId,
                onepcType:this.form.onepcType2,
              };
              if(this.form.subjectId[0]){
                obj.subId = this.form.subjectId
              }else{
                obj.subId = null
              }
              apkFileAddApkLog(obj).then( response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLog(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('laboratory/apkfile/export', {
          ...this.queryParams
        }, `laboratory_log.xlsx`)
      },
      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 = [];
      },
    }
  };
</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>
