<!--应用列表-->
<template>
  <div class="app-container applyList">
    <div class="page-container applyListPage">
      <div class="page-form-title-box">
        <el-form :model="queryParams" class="form-box" ref="queryForm"
                 :inline="true" style="width:100%;">
          <el-form-item label="" prop="name" label-width="90px">
            <el-input
              maxLength="30"
              v-model="queryParams.name"
              placeholder="请输入应用名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="" prop="type">
            <el-select v-model="queryParams.type" clearable placeholder="请选择设备类型" style="width: 200px">
              <el-option
                v-for="item in optionList"
                :key="item.type"
                :label="item.name"
                :value="item.type">
              </el-option>
            </el-select>
          </el-form-item>
          <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
          <p class="page-submit-common-style-button"
             style="float: right;"
             @click="handleClick()"
             v-hasPermiRouter="['system:appManage:add']"
          >添加应用</p>
        </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box" v-loading="loading" border :data="tableList" ref="multipleTable">
          <el-table-column label="应用名" align="center" prop="name" show-overflow-tooltip/>
          <el-table-column label="版本号" align="center" prop="version" show-overflow-tooltip width="100"/>
          <el-table-column label="文件尺寸(MB)" align="center" prop="size" show-overflow-tooltip width="120"/>
          <el-table-column label="版本描述" align="center" prop="info" show-overflow-tooltip width="300"/>
          <el-table-column label="设备类型" align="center" prop="type" show-overflow-tooltip width="140">
            <template slot-scope="scope">
              <p v-for="item in optionList" v-if="item.type == scope.row.type">{{item.name}}</p>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="state" show-overflow-tooltip width="100">
            <template slot-scope="scope">
              {{scope.row.state?'启用':'禁用'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip width="180">
            <template slot-scope="scope">
              {{parseTime(scope.row.createTime,"{y}-{m}-{d} {h}:{i}")}}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" prop="deptName" width="200" v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   @click="tableButton(1,scope.row)"
                >下载</p>
                <p class="table-button-p"
                   @click="tableButton(2,scope.row)"
                   v-hasPermiRouter="['system:appManage:edit']"
                >编辑</p>
                <p class="table-button-p"
                   @click="tableButton(3,scope.row)"
                   v-hasPermiRouter="['system:appManage:edit']"
                >删除</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
                    v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
      </div>
    </div>
    <el-dialog :title="dialogTitle" class="applyList-dialog-box" :visible.sync="dialogType" v-if="dialogType"
               width="700px" append-to-body :close-on-click-modal="false">
      <div class="applyList-dialog-min-box scrollbar-box">
        <el-form  v-loading="loading" :rules="dialogRules" :model="dialogForm" ref="dialogForm">
          <el-form-item label="应用名称" prop="name" label-width="90px">
            <el-input
              :disabled="!!dialogForm.id"
              v-model="dialogForm.name"
              maxLength="20"
              placeholder="请上传应用"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="版本号" prop="version" label-width="90px">
            <el-input-number
              :disabled="!!dialogForm.id"
              v-model="dialogForm.version"
              :precision="2"
              :step="0.01"
              maxLength="20"
              placeholder="请输入版本号"
              clearable
              style="width: 500px"
              controls-position="right"
              :min="minVersion" :max="100">
            </el-input-number>
          </el-form-item>
          <el-form-item label="版本描述" prop="info" label-width="90px">
            <el-input
              resize="none"
              type="textarea"
              v-model="dialogForm.info"
              maxLength="200"
              placeholder="请输入版本描述"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="设备类型" prop="type" style="display: block" label-width="90px">
            <el-radio-group :disabled="!!dialogForm.id" v-model="dialogForm.type" @change="typeChange">
              <el-radio v-for="item in optionList" :label="item.type">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="state" style="display: block" label-width="90px">
            <el-radio v-model="dialogForm.state" :label="true">启用</el-radio>
            <el-radio v-model="dialogForm.state" :label="false">禁用</el-radio>
          </el-form-item>
          <el-form-item label="安装包" prop="state" style="display: block" label-width="90px" v-if="upDataType">
            <p class="up-data-p" @click="upDataButton">重新上传</p>
          </el-form-item>
          <el-form-item label="安装包" prop="url" label-width="90px" v-if="!upDataType">
            <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}}MB</p>
                <p>{{fileData.text}}</p>
              </div>
            </uploader>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="dialogCancel">取消</p>
        <p class="dialog-footer-button-primary" @click="dialogSubmit">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { appInfoList,appInfoAdd,appInfoUpdate,appInfoDelete,getVersionByType,appInfoType } from "@/api/serviceCenter/index";
  import { getToken } from "@/utils/auth";
  import axios from 'axios'
  import SparkMD5 from 'spark-md5'
  let httpHeader=window.location.href.split('://')[0]+'://'
  export default {
    name: 'applyList',
    data(){
      return{
        tableButtonType:this.hasPermiDom(['system:appManage:edit','system:appManage:detail','system:appManage:edit']),
        loading:false,
        optionList:[],
        queryParams:{
          page:1,
          pageSize:20,
          name:"",
          type:"",
        },
        tableList:[],
        total:0,
        dialogTitle:"",
        dialogType:false,
        upDataType:false,
        dialogForm:{
          name:"",
          version:"",
          info:"",
          type:1,
          state:true,
          url:'',
        },
        //版本号最小值
        minVersion:null,
        //文件列表
        fileList:[],
        options: {
          target: httpHeader+this.judgmentNetworkReturnAddress()+"/system/file/upload/apk/chunk",
          // 开启服务端分片校验功能
          testChunks: true,
          single: true,
          fileParameterName: 'file',
          headers: {
            Authorization: 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;
          },
        },
        attrs: {
          accept: [".apk"]
        },
        statusText: {
          success: "上传成功",
          error: "上传出错了",
          uploading: "上传中...",
          paused: "暂停中...",
          waiting: "等待中...",
          cmd5: "计算文件MD5中...",
        },
        fileData:{
          name:"",
          size:"",
          text:"",
        },
        dialogRules:{
          name: [
            { required: true, message: "请输入应用名称", trigger: "blur" }
          ],
          version: [
            { required: true, message: "请输入版本编号", trigger: "blur" },
            // { required: true, message: "只能输入数字", validator: this.isNum, trigger: "blur" },
          ],
          info: [
            { required: true, message: "请输入版本描述", trigger: "blur" }
          ],
          type: [
            { required: true, message: "请选择设备类型", trigger: "blur" }
          ],
          state: [
            { required: true, message: "请选择状态", trigger: "blur" }
          ],
          url: [
            { required: true, message: "请上传安装包", trigger: "blur" }
          ],
        },
      }
    },
    created(){

    },
    mounted(){
      this.getList();
      this.appInfoType();
    },
    methods:{
      fileSuccess(rootFile, file, response, chunk) {
        const result = JSON.parse(response);
        if (result.code == 200 && !this.skip) {
          axios.post(httpHeader+this.judgmentNetworkReturnAddress()+"/system/file/upload/merge", {
            identifier: file.uniqueIdentifier,
            filename: file.name,
            totalChunks: chunk.offset,
          },{
            headers: {
              Authorization: getToken(),
            }
          }).then((res) => {
            if (res.data.code==200) {
              this.dialogForm.url=res.data.data;
            } else {
            }
          }).catch(function (error) {
          });
        } else if(result.code == 200){
        }else{
          this.msgError(result.code+result.message)
        }
        if (this.skip) {
          this.skip = false;
        }
      },
      fileComplete(rootFile) {
        // 一个根文件（文件夹）成功上传完成。
        this.fileName=rootFile.name;
        this.fileSize=rootFile.size;
        this.fileData = {
          name:rootFile.name,
          size:(parseInt(rootFile._prevUploadedSize/1024)/1024).toFixed(2),
          text:"上传完成"
        }
      },
      complete(file) {
        // 上传完毕。
      },
      filesAdded(file, fileList, event) {
        if(file[0].fileType !== "application/vnd.android.package-archive"){
          this.msgError('请上传APK文件')
          return
        }
        this.fileData = {
          name:file[0].name,
          size:"",
          text:"上传中..."
        }
        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));
        }
      },
      dialogSubmit(){
        if(this.loading){
          return
        }
        if(this.dialogForm.id){//编辑
          this.$refs["dialogForm"].validate(valid => {
            if (valid) {
              let obj = {
                id:this.dialogForm.id,
                name:this.dialogForm.name,
                version:this.dialogForm.version,
                info:this.dialogForm.info,
                type:this.dialogForm.type,
                url:this.dialogForm.url,
                state:this.dialogForm.state,
                // fileData:JSON.stringify(this.fileData),
              };
              appInfoUpdate(obj).then( response => {
                this.msgSuccess("编辑成功");
                this.getList()
                this.dialogType = false;
                this.dialogForm = {};
                this.fileList=[];
                this.fileData = {};
              });
            }
          });

        }else{//添加
          this.$refs["dialogForm"].validate(valid => {
            if (valid) {
              let obj = {
                name:this.dialogForm.name,
                version:this.dialogForm.version,
                info:this.dialogForm.info,
                type:this.dialogForm.type,
                state:this.dialogForm.state,
                url:this.dialogForm.url,
                size:this.fileData.size,
                // fileData:JSON.stringify(this.fileData),
              };
              appInfoAdd(obj).then( response => {
                this.msgSuccess("新增成功");
                this.getList()
                this.dialogType = false;
                this.dialogForm = {};
                this.fileList=[];
                this.fileData = {};
              });
            }
          });
        }
      },
      dialogCancel(){
        this.$set(this,'dialogType',false);
      },
      //新增
      handleClick(){
        this.$set(this,'dialogForm',{
          name:"",
          version:"",
          info:"",
          type:1,
          state:true,
          url:"",
        });
        this.$set(this,'fileList',[]);
        this.$set(this,'fileData',{
          name:"",
          size:"",
          text:"",
        });
        this.getVersionByType();
        this.$set(this,'dialogTitle','上传APK');
        this.$set(this,'upDataType',false);
        this.$set(this,'dialogType',true);
      },
      //查询
      handleQuery(){
        this.$set(this.queryParams,'page',1);
        this.getList();
      },
      //重置
      resetQuery(){
        this.$set(this,'queryParams',{
          page:1,
          pageSize:20,
          name:"",
          type:"",
        });
        this.getList();
      },
      //获取数据列表
      getList(){
        this.$set(this,'loading',true);
        let obj = JSON.parse(JSON.stringify(this.queryParams))
        appInfoList(obj).then(response => {
          this.$set(this,'loading',false);
          this.$set(this,'tableList',response.data.records);
          this.$set(this,'total',response.data.total);
        });
      },
      //获取设备类型
      appInfoType(){
        appInfoType().then(response => {
          this.$set(this,'optionList',response.data);
        });
      },
      //重新上传开关
      upDataButton(){
        this.$set(this.dialogForm,'url','');
        this.$set(this,'upDataType',!this.upDataType);
      },
      //操作按钮
      tableButton(type,row){
        let self = this;
        if(type == 1){
          let regex = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/g;
          let info = row.info.replace(regex, '_');
          let format = row.url.split('.');
          let name = row.name+'-'+info+'.'+format[format.length-1];
          this.downloadGet(row.url,name);
          // this.downloadUrl(url,row.name+'.apk');
        }else if(type == 2){
          let obj = JSON.parse(JSON.stringify(row));
          this.$set(this,'dialogForm',{
            id:obj.id,
            name:obj.name,
            version:obj.version,
            info:obj.info,
            type:obj.type,
            url:obj.url,
            state:obj.state,
          });
          this.$set(this,'minVersion',obj.version);
          this.$set(this,'fileList',[]);
          this.$set(this,'fileData',{
            name:"",
            size:"",
            text:"",
          });
          this.$set(this,'dialogTitle','上传APK');
          this.$set(this,'upDataType',true);
          this.$set(this,'dialogType',true);
        }else if(type == 3){
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            appInfoDelete({id:row.id}).then(response => {
              self.msgSuccess(response.message)
              self.getList();
            });
          }).catch(() => {});
        }
      },
      //选中设备类型
      typeChange(val){
        this.getVersionByType();
      },
      //通过类型获取当前APK版本号
      getVersionByType(){
        getVersionByType({type:this.dialogForm.type?this.dialogForm.type:1}).then(response => {
          let minVersion = Number(this.accAdd(response.data,0.01));
          this.$set(this,'minVersion',minVersion);
          this.$set(this.dialogForm,'version',minVersion);
          // this.$set(this,'minVersion',Number(this.accAdd(response.data,0.01)));
          // this.$set(this.dialogForm,'version',response.data);
          // this.$set(this.dialogForm,'version',response.data);
        });
      },
      //加法
      accAdd(arg1,arg2){
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2))
        return ((arg1*m+arg2*m)/m).toFixed(2);
      },
    },
  }
</script>

<style scoped lang="scss">
  .applyList{
    .applyListPage{

    }
  }
</style>

<style lang="scss">
  .applyList-dialog-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;
      }
    }
    .applyList-dialog-min-box{
      height:500px;
    }
    .uploader-drop{
      width:500px;
      .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;
    }
    .up-data-p{
      width:80px;
      text-align: center;
      background-color:#0183fa;
      cursor:pointer;
      border-radius:4px;
      color:#fff;
      margin-top:2px;
    }
  }
</style>
