<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">

      <el-form-item label="APP类型" prop="appType">
          <el-select v-model="queryParams.appType" placeholder="APP类型" clearable size="small">
               <el-option
                 v-for="dict in appTypeOptions"
                 :key="dict.dictValue"
                 :label="dict.dictLabel"
                 :value="dict.dictValue"
               />
             </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="['his:appVersion:add']"
        >发布版本</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:appVersion:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="appList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="versionId" />
      <el-table-column label="版本名称" align="center" prop="versionName" />
      <el-table-column label="版本CODE" align="center" prop="versionCode" />
      <el-table-column label="更新描述" align="center" prop="note" />
      <el-table-column label="下载地址" align="center" prop="url"  width="150px"/>
      <el-table-column label="h5下载地址" align="center" prop="h5Url"  width="150px"/>
      <el-table-column label="APP系统类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="是否强制更新" align="center" prop="isForce">
        <template slot-scope="scope">
          <dict-tag :options="isForceOptions" :value="scope.row.isForce"/>
        </template>
      </el-table-column>
      <el-table-column label="APP类型" align="center" prop="appType" >
        <template slot-scope="scope">
          <dict-tag :options="appTypeOptions" :value="scope.row.appType"/>
        </template>
      </el-table-column>
           <el-table-column label="发布时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:appVersion:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:appVersion:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改安卓版本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="APP类型" prop="appType">
          <el-radio-group v-model="form.appType">
            <el-radio
              v-for="dict in appTypeOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="版本CODE" prop="versionCode">
            <el-input-number v-model="form.versionCode" :min="1" label="请输入版本CODE"></el-input-number>

        </el-form-item>
        <el-form-item label="更新描述" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="安装包上传" prop="url" v-if="form.appType!==4">
          <el-upload
            accept=".apk"
            class="upload-demo"
            :action="uploadUrl"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传APK文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="压缩包上传" prop="url" v-if="form.appType===4">
          <el-upload
            accept=".zip"
            class="upload-demo"
            :action="uploadUrl"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传Zip压缩文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="下载地址" prop="url" v-if="form.url!==null">
          <el-input v-model="form.url" readonly />
        </el-form-item>

        <el-form-item label="baidu安装包上传" prop="baiduUrl" v-if="form.appType===3">
          <el-upload
            accept=".apk"
            class="upload-demo"
            :action="uploadUrl"
            :before-upload="beforeUploadBaidu"
            :on-success="handleSuccessBaidu"
            :on-preview="handlePreviewBaidu"
            :on-remove="handleRemoveBaidu"
            :before-remove="beforeRemoveBaidu"
            :limit="1"
            :on-exceed="handleExceedBaidu"
            :file-list="fileList1">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传APK文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="h5下载地址" prop="h5Url" v-if="form.appType===3">
          <el-input v-model="form.h5Url" label="请输入h5下载地址"></el-input>
        </el-form-item>
        <el-form-item label="baidu下载地址" prop="baiduUrl" v-if="form.baiduUrl!==null">
          <el-input v-model="form.baiduUrl" readonly />
        </el-form-item>
        <el-form-item label="APP系统类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否强制更新"  prop="isForce">
          <el-radio-group v-model="form.isForce">
            <el-radio
              v-for="dict in isForceOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="强制更新渠道" prop="uploadConfig" v-if="form.appType===3">
          <el-checkbox v-model="updateConfig.appstore" >应用宝</el-checkbox>
          <el-checkbox v-model="updateConfig.xiaomi" >小米</el-checkbox>
          <el-checkbox v-model="updateConfig.huawei" >华为</el-checkbox>
          <el-checkbox v-model="updateConfig.oppo" >oppo</el-checkbox>
          <el-checkbox v-model="updateConfig.vivo" >vivo</el-checkbox>
          <el-checkbox v-model="updateConfig.baidu" >百度</el-checkbox>
        </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>
  </div>
</template>
<script>
import { listApp, getApp, delApp, addApp, updateApp, exportApp } from "@/api/his/appVersion";

export default {
  name: "App",
  data() {
    return {
      updateConfig: { },
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 安卓版本表格数据
      appList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // APP类型 1android 2ios字典
      typeOptions: [],
      // 是否强制更新字典
      isForceOptions: [],
      // APP 类型 1医生端 2药师端字典
      appTypeOptions: [],
       fileList:[],
      fileList1:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionName: null,
        versionCode: null,
        note: null,
        url: null,
        type: null,
        isForce: null,
        appType: null
      },
      // 表单参数
      form: {},
      // 表单校验
    rules: {
      versionName: [
        { required: true, message: "版本名不能为空", trigger: "blur" }
      ],
      versionCode: [
        { required: true, message: "版本CODE不能为空", trigger: "blur" }
      ],
      // url: [
      //   { required: true, message: "上传地址不能为空", trigger: "blur" }
      // ],
      type: [
        { required: true, message: "APP类型不能为空", trigger: "blur" }
      ],
      isForce: [
        { required: true, message: "是否强制更新不能为空", trigger: "blur" }
      ],
      note: [
        { required: true, message: "描述不能为空", trigger: "blur" }
      ],
      appType: [
        { required: true, message: "APP类型不能为空", trigger: "blur" }
      ],

    }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_app_phone_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.isForceOptions = response.data;
    });
    this.getDicts("sys_app_type").then(response => {
      this.appTypeOptions = response.data;
    });
  },
  methods: {
    beforeUpload(file){
        this.myloading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
    },
    handleSuccess(res, file) {
        this.myloading.close();
        if(res.code==200){
          this.form.url=res.url;
        }
        else{
          this.msgError(res.msg);
        }

    },
    handleRemove(file, fileList) {
      console.log(this.fileList);
      this.form.url=null;

    },
    handlePreview(file) {

      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {

      return this.$confirm(`确定移除 ${ file.name }？`);
    },

    beforeUploadBaidu(file){
      this.myloading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    handleSuccessBaidu(res, file) {
      this.myloading.close();
      if(res.code==200){
        this.form.baiduUrl=res.url;
      }
      else{
        this.msgError(res.msg);
      }

    },
    handleRemoveBaidu(file, fileList) {
      console.log(this.fileList);
      this.form.baiduUrl=null;

    },
    handlePreviewBaidu(file) {

      console.log(file);
    },
    handleExceedBaidu(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemoveBaidu(file, fileList) {

      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    /** 查询安卓版本列表 */
    getList() {
      this.loading = true;
      listApp(this.queryParams).then(response => {
        this.appList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        versionId: null,
        versionName: null,
        versionCode: null,
        note: null,
        url: null,
        baiduUrl: null,
        type: 1,
        isForce: 1,
        createTime: null,
        appType: 1,
        appStoreUpdate:false,
        updateConfig: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.versionId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "发布版本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const versionId = row.versionId || this.ids
      getApp(versionId).then(response => {
        this.form = response.data;
        this.updateConfig = JSON.parse(response.data.updateConfig)
        this.open = true;
        this.title = "修改版本";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.updateConfig = JSON.stringify(this.updateConfig)
          if (this.form.versionId != null) {
            updateApp(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApp(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const versionIds = row.versionId || this.ids;
      this.$confirm('是否确认删除安卓版本编号为"' + versionIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApp(versionIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有安卓版本数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportApp(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
