<template>
	<div class="app-container">
	  <div class="main-right-box">
		<!--    搜索条件    -->
		<div class="main-search-box">
		  <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" size="small">
			<el-form-item label="版本" prop="version">
			  <el-input v-model="queryParams.version" :maxlength="50" clearable placeholder="请输入版本"
						style="width: 240px"
						@keyup.enter.native="handleQuery"/>
			</el-form-item>

			<el-form-item label="平台" prop="type">
			  <el-select v-model="queryParams.type" clearable placeholder="请选择平台" style="width: 240px">
				<el-option v-for="dict in dict.type.sys_version_type" :key="dict.value" :label="dict.label"
						   :value="dict.value"/>
			  </el-select>
			</el-form-item>

		  </el-form>

		  <el-row :gutter="10">
			<el-col :span="1.5">
			  <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery"
			  >搜索
			  </el-button>
			</el-col>
			<el-col :span="1.5">
			  <el-button icon="el-icon-refresh" size="mini" type="primary" @click="resetQuery"
			  >重置
			  </el-button>
			</el-col>

			<el-col :span="1.5">
			  <el-button v-hasPermi="['system:version:add']" icon="el-icon-plus" size="mini" type="primary"
						 @click="handleAdd">新增
			  </el-button>
			</el-col>

			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		  </el-row>
		</div>

		<el-table
		  v-loading="loading"
		  :data="versionList"
		  border
		  height="646" size="small" @selection-change="handleSelectionChange">
		  <!-- <el-table-column type="selection" width="50" align="center" /> -->
		  <el-table-column align="center" label="序号" width="100">
			<template v-slot:default="scope">
			  <span v-text="getPageIndex(scope.$index)"> </span>
			</template>
		  </el-table-column>
		  <el-table-column :show-overflow-tooltip="true" label="版本" prop="version"/>
		  <el-table-column align="center" label="平台" prop="type">
			<template slot-scope="scope">
			  <dict-tag :options="dict.type.sys_version_type" :value="scope.row.type"/>
			</template>
		  </el-table-column>
		  <el-table-column  align="center" label="当前使用" prop="isUse">
			<template slot-scope="scope">
				<div>
					<span class="el-tag el-tag--medium" v-if="scope.row.isUse">是</span>
					<span class="el-tag el-tag--danger" v-else>否</span>
				</div>
			</template>
		  </el-table-column>
		  <el-table-column  align="center" label="强制更新" prop="isForce">
			<template slot-scope="scope">
				<div>
					<span class="el-tag el-tag--medium" v-if="scope.row.isForce">是</span>
					<span class="el-tag el-tag--danger" v-else>否</span>
				</div>
			</template>
		  </el-table-column>
		  <el-table-column  align="center" label="下载地址" prop="path">
			<template v-if="scope.row.type !== 3" slot-scope="scope">
				<el-button size="mini" type="text"
						 @click="downloadVersionFile(scope.row)">点击下载
			    </el-button>
			</template>
		  </el-table-column>
		  <el-table-column align="center" label="说明" prop="note" width="200">
		  </el-table-column>
		  <el-table-column align="center" label="创建时间" prop="createTime" width="200">
		  </el-table-column>
		  <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
			<template v-if="scope.row.id !== 1" slot-scope="scope">
			  <el-button v-hasPermi="['system:version:edit']" icon="el-icon-edit-outline" size="mini" type="text"
						 @click="handleUpdate(scope.row)">编辑
			  </el-button>
			</template>
		  </el-table-column>
		</el-table>

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

	  </div>


	  <!-- 添加或修改版本号对话框 -->
	  <DialogCom :title="title" :visible.sync="open" append-to-body width="750px">
		<el-form ref="form" :model="form" :rules="rules" label-width="100px">

			<el-form-item label="版本" prop="version">
			<el-input v-model="form.version" :maxlength="50" placeholder="请输入角色名称"/>
			</el-form-item>

			<el-form-item label="类型" prop="type">
			<el-select v-model="form.type"
						placeholder="请选择类型"
						@change="selectedType()"
						style="width: 100%">
				<el-option
					v-for="dict in dict.type.sys_version_type"
					:key="dict.value"
					:label="dict.label"
					:value="dict.value"
				></el-option>
			</el-select>
			</el-form-item>

			<el-form-item label="使用" prop="isUse">
				<el-checkbox v-model="form.isUse"></el-checkbox>
			</el-form-item>

			<el-form-item label="强制更新" prop="isForce">
				<el-checkbox v-model="form.isForce"></el-checkbox>
			</el-form-item>

			<el-form-item v-if="form.type!=='3'" label="上传文件" ref="files" prop="fileList">
              <K-file-upload
                ref="upload"
                :defaultValue="formFileListDefualtValue"
                v-model="form.fileList"
                :limit="1"
                :fileType="['apk']"
                :packageName="packageNameList"
				:fileSize="50"
                @input="fileListChanged"
              />
            </el-form-item>

			<el-form-item label="说明" prop="note">
				<k-textarea
					v-model="form.note"
					placeholder="请输入说明"
					:length="200"
				/>
			</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>
	  </DialogCom>
	</div>
  </template>

  <script>
  import {
    listVersion,
    getVersionDetail,
    addVersion,
    updateVersion,
    downloadFile,
    getAllPackageName
  } from "@/api/system/version";
  import KFileUpload from "@/components/K-FileUpload/index.vue";
  import KTextarea from "@/components/common/textarea.vue";

  export default {
    name: "Version",
    components: {KFileUpload,KTextarea},
    dicts: ['sys_version_type','sys_true_false'],
    data() {
      return {
      // 遮罩层
      loading: true,
      formFileListDefualtValue: [],
      // 选中数组
      ids: [],
      // 非单个停用
      single: true,
      // 非多个停用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表数据
      versionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
        packageNameList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        version: null,
        type: null
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 表单校验
      rules: {
        version: [
        {required: true, message: "版本号不能为空", trigger: "blur"},
        {validator: validatorVersion, trigger: "blur"}
        ],
        type: [
        {required: true, message: "请选择机构类型", trigger: "blur"}
        ],
        isUse: [
        {required: true, message: "请输入使用", trigger: "blur"}
        ],
        isForce: [
        {required: true, message: "请输入强制更新", trigger: "blur"}
        ],
        note: [
        {required: true, message: "请输入说明", trigger: "blur"}
        ]
      },
      };
    },
    created() {
      this.getList();
    },
      methods: {
      fileListChanged(list) {
          this.$refs.files.clearValidate();
        },
      selectedType() {
          this.$refs["form"].clearValidate(["type"]);
        },
      handleSelectionChange(selection) {
          this.$emit('handleSelectionChange', selection)
        },
      async downloadVersionFile(row) {
      if(row.type === 3){
        return;
      }

		  await downloadFile(row.id,row.packageName);

      },
	    getPageIndex($index) {
		    //表格序号
		    return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
	    },
	    /** 查询角色列表 */
	    getList() {
		    this.loading = true;
		    listVersion(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
			    this.versionList= response.rows;
			    this.total = response.total;
			    this.loading = false;
		    }
		    );
        getAllPackageName().then(response => {
          this.packageNameList=response.data;
        });
	    },

      // 取消按钮
	    cancel() {
		    this.open = false;
		    this.reset();
	    },
	    // 表单重置
	    reset() {
		    this.formFileListDefualtValue = [],
		    this.form = {
          version: null,
          type: null,
          note: null,
          isUse: false,
          isForce: false
		    };
        this.resetForm("form");
	    },
	    /** 搜索按钮操作 */
	    handleQuery() {
		    this.queryParams.pageNum = 1;
		    this.getList();
	    },
	    /** 重置按钮操作 */
	    resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
	    },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增版本号";
	    },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id;
        getVersionDetail(id).then(response => {
          this.form = response.data;
          let file = {url:this.form.path,name:this.form.packageName};
            let fileList = [];
            fileList.push(JSON.stringify(file));
            this.form.fileList = fileList;
            this.formFileListDefualtValue = fileList;
			      this.form.type = this.form.type + '';
		  	    this.open = true;
		  	    this.title = "编辑版本号";
		    });
	    },
	    /** 提交按钮 */
	    submitForm: function () {
		    this.$refs["form"].validate(valid => {
		    if (valid) {
			    if(this.form.type !== `3` &&  this.form.fileList.length === 0){
            	this.$modal.msgError("请上传文件！");
            	throw new Error("请上传文件！");
            }
			    if (this.form.type !== `3`) {
				    let file = JSON.parse(this.form.fileList[0]);
            	this.form.path = file.url;
            	this.form.packageName = file.name;
			  }
			  if (this.form.id != undefined) {
			  	updateVersion(this.form).then(response => {
					this.$modal.msgSuccess("处理成功");
					this.open = false;
					this.getList();
			  	});
			  } else {
			  	addVersion(this.form).then(response => {
					this.$modal.msgSuccess("处理成功");
					this.open = false;
					this.getList();
			  	});
			  }
		  }
		});
	  }
	}
  };

  export function validatorVersion(rule, value, callback) {
	const reg = /^(?!0)\d+\.(?!0)\d+\.(?!0)\d+$/ ;
		if(value == '' || value == undefined || value ==null){
			callback();
		}else{
			if(!reg.test(value)){
				callback(new Error("请输入正确的版本号! 例如: 1.12.1"));
			}else{
				callback();
			}
		}
  }
  </script>
  <style lang="scss">
 .el-checkbox {
	display: -webkit-box !important;
  }
  </style>
