<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item :label="$t('系统类型')" prop="appType">
        <el-select v-model="queryParams.appType" :placeholder="$t('请选择系统类型')" clearable="">
          <el-option v-for="type in this.getDictDatas(DICT_TYPE.ECW_DATA_SOURCE)" :key="type.value" :label="$l(type, 'label')" :value="type.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('强制更新')">
        <el-select v-model="queryParams.forceUpdate" :placeholder="$t('请选择更新条件')" clearable="">
          <el-option v-for="item in forceUpdateArray" :key="item.type" :label="$l(item, 'value')" :value="item.type"></el-option>
        </el-select>  
      </el-form-item>
      <el-form-item :label="$t('内部版本')" prop="versionCode">
        <el-input v-model.number="queryParams.versionCode" :placeholder="$t('请输入内部版本')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      
    
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:version:create']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['system:version:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">

      <el-table-column label="系统类型" align="center" prop="appType">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_DATA_SOURCE" :value="row.appType" />
        </template>  
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="appVersion">
        <template slot-scope="scope">
          <el-link icon="el-icon-link" type="primary" :href="scope.row.appUrl">{{ scope.row.appVersion  }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="内部号" align="center" prop="versionCode" />
      <el-table-column label="强制更新" align="center" prop="forceUpdate">
        <template slot-scope="scope">
          <span>{{ getName(scope.row.forceUpdate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="desp" />
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:version:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:version:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :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="$t('系统')" prop="appType">
          <el-select v-model="form.appType" :placeholder="$t('请选择系统类型')">
            <el-option v-for="type in this.getDictDatas(DICT_TYPE.ECW_DATA_SOURCE)" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('版本号')" prop="appVersion">
          <el-input v-model="form.appVersion" :placeholder="$t('请输入版本号')" />
        </el-form-item>

        <el-form-item :label="$t('内部号')" prop="versionCode">
          <el-input v-model.number="form.versionCode" :placeholder="$t('请输入内部号')" />
        </el-form-item>

        <el-form-item :label="$t('链接方式')">
          <el-radio v-model="linkType" :label="1">链接</el-radio>
          <el-radio v-model="linkType" :label="2">上传</el-radio>
        </el-form-item>

        <el-form-item v-if="linkType==2">
          <el-upload 
          ref="upload"
          :limit="1"
          :headers="upload.headers" 
          :action="upload.url" 
          :data="upload.data"
          :disabled="upload.isUploading"
          :show-file-list="true" 
          :on-change="handleFileChange"
          :on-progress="uploadProcess"
          :on-success="handleFileSuccess"
          >
            <el-button size="small">{{ $t('上传') }}<i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
         
        </el-form-item>

        <el-form-item :label="$t('版本链接')" prop="appUrl">
          <el-input v-model="form.appUrl" :placeholder="$t('请输入版本链接')" :disabled="linkType==2"/>
        </el-form-item>

        <el-form-item :label="$t('强制更新')" prop="forceUpdate">
          <el-select v-model="form.forceUpdate" :placeholder="$t('请选择更新条件')">
            <el-option v-for="item in forceUpdateArray" :key="item.type" :label="$l(item, 'value')" :value="item.type"></el-option>
          </el-select>  
        </el-form-item>
        <el-form-item :label="$t('说明')" prop="desp">
          <el-input type="textarea"  v-model="form.desp" :placeholder="$t('请输入说明')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('确 定')}}</el-button>
        <el-button @click="cancel">{{$t('取 消')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createVersion, updateVersion, deleteVersion, getVersion, getVersionPage, exportVersionExcel } from "@/api/system/version";
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
import { uploadFile } from "@/api/infra/file";
import {getToken} from "@/utils/auth";
export default {
  name: "Version",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // app版本管理列表
      list: [],

      linkType:1,

      forceUpdateArray:[
        {type:1, value:this.$t('是')},
        {type:0, value:this.$t('否')}
      ],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeForceUpdate: [],
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        appUrl: null,
        appType: null,
        appVersion: null,
        versionCode: null,
        desp: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        appType: [{ required: true, message: this.$t("系统类型不能为空"), trigger: "change" }],
        appVersion: [{ required: true, message: this.$t("版本号不能为空"), trigger: "blur" }],
        versionCode: [{ required: true, message: this.$t("内部号不能为空"), trigger: "blur" }],
        appUrl: [{ required: true, message: this.$t("版本链接不能为空"), trigger: "blur" }],
        forceUpdate: [{ required: true, message: this.$t("强制更新不能为空"), trigger: "change" }],
      },

      // 用户导入参数
      upload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
        headers: { Authorization: "Bearer " + getToken() }, // 设置上传的请求头部
        data: {} // 上传的额外数据，用于文件名
      },
    };
  },

  computed: {
    getName() {
      return forceUpdate => {
        for (let index in this.forceUpdateArray) {
          let item = this.forceUpdateArray[index];
          if (item.type == forceUpdate) {
            return this.$l(item, 'value');
          }
        }
      }
    },
  },

  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeForceUpdate, 'forceUpdate');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getVersionPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.linkType = 1;
      this.form = {
        id: undefined,
        appUrl: undefined,
        appType: undefined,
        appVersion: undefined,
        versionCode: undefined,
        forceUpdate: undefined,
        desp: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeForceUpdate = [];
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // console.log(this.form);
      this.title = "添加app版本管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getVersion(id).then(response => {
        this.form = response.data;
        this.linkType = 1;
        this.open = true;
        this.title = "修改app版本管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateVersion(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createVersion(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除app版本管理编号为"' + id + '"的数据项?').then(function() {
          return deleteVersion(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },

    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {
      this.upload.data.path = this.uuid() + "/" + file.name;
    },

    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      // 清理
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 提示成功，并刷新
      this.$modal.msgSuccess("上传成功");
      this.$set(this.form, 'appUrl', response.data);
    },

    uploadProcess(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },

    // 覆盖默认的上传行为
    requestUpload(params) {

    },
    // 上传预处理
    beforeUpload(file) {
      // if (file.type.indexOf("image/") == -1) {
      //   this.$modal.msgError(this.$t("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。"));
      // } else {
        //上传
        let formData = new FormData();
        // console.log(file);
        formData.append("file", file);
        formData.append("path", this.uuid() + "/" + file.name);
        uploadFile(formData).then(response => {
          this.$set(this.form, 'appUrl', response.data);
          // this.form.img = response.data;
        })
      // }
    },
    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },

    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeForceUpdate, 'forceUpdate');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有app版本管理数据项?').then(() => {
          this.exportLoading = true;
          return exportVersionExcel(params);
        }).then(response => {
          this.$download.excel(response, '${table.classComment}.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
