<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <el-button type="text" size="small" icon="el-icon-upload2" @click.stop="handleAdd(scope.row,scope.index)">升级
        </el-button>
      </template>
    </avue-crud>

    <!-- 升级 -->
    <el-dialog class="app-upload-dialog" title="App升级" :visible.sync="dialogUpload" append-to-body center>
      <avue-crud :option="option1"
                 :table-loading="loadingDeail"
                 :data="dataDetail"
                 ref="crud"
                 v-model="form"
                 :page.sync="pageDetail"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 @row-del="rowDelDetail"
                 @row-update="rowUpdateDetail"
                 @row-save="rowSaveDetail"
                 @current-change="currentChangeDetail"
                 @size-change="sizeChange"
                 @refresh-change="refreshChangeDetail"
                 @on-load="onLoadDetail">

        <div slot-scope="{}" slot="fileUrlForm" style="display: inline-block;width: 100%;">
          <el-input v-model="form.fileUrl">
            <el-upload slot="append" action="/api/blade-resource/oss/endpoint/put-file3" accept=".apk,.wgt" :disabled="isLoading"
                       :on-remove="handleRemove" :limit="1" :headers='headers' :show-file-list="false"
                       :on-exceed="handleExceed" :on-success="handleSuccess" :on-progress="handleProgress" :on-error="handleError"
            >
              <el-button size="small" type="primary" :loading="isLoading" style="display: inline-block">上传</el-button>
            </el-upload>
          </el-input>
        </div>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  remove,
  update,
  add,
  getDetailList,
  updateDetail,
  addDetail,
  removeDetail


} from "@/api/system/app";
import {getDetail as packageDetail} from "@/api/system/tenantpackage";
import {mapGetters} from "vuex";
import {getMenuTree} from "@/api/system/menu";
import {validatenull} from "@/util/validate";
import website from '@/config/website';
import {Base64} from 'js-base64';
import {getToken} from '@/util/auth';

export default {
  data() {
    return {
      form: {},
      selectionList: [],
      query: {},
      loading: true,
      box: false,
      datasourceBox: false,
      packageBox: false,
      packageSettingBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      pageDetail: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: false,
        viewBtn: false,
        dialogWidth: 600,
        dialogClickModal: false,
        column: [
          {
            label: "应用平台",
            prop: "platform",
            span: 24,
            rules: [{
              required: true,
              message: "请输入应用平台",
              trigger: "blur"
            }]
          },
          {
            label: "应用名称",
            prop: "name",
            span: 24,
            rules: [{
              required: true,
              message: "请输入应用名称",
              trigger: "blur"
            }]
          },
          {
            label: "当前版本",
            prop: "currentVersion",
            span: 24,
            rules: [{
              required: true,
              message: "请输入当前版本号",
              trigger: "blur"
            }]
          },
          {
            label: "应用说明",
            prop: "appExplain",
            span: 24,
            minRows: 2,
            type: "textarea",
            hide: true,
          },
          {
            label: "更新时间",
            prop: "updateTime",
            span: 24,
            type: "time",
            display: false
          },
        ]
      },
      data: [],
      dataDetail: [],
      loadingDeail: false,
      settingForm: {},
      dialogUpload: false,
      isLoading: false,
      option1: {
        height: '100%',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        dialogWidth: 600,
        dialogClickModal: false,
        column: [
          {
            label: "当前版本",
            prop: "versionNumber",
            span: 24,
            rules: [{
              required: true,
              message: "请输入当前版本号",
              trigger: "blur"
            }]
          },
          {
            label: "软件类型",
            prop: "softwareType",
            type: "radio",
            span: 24,
            search: true,
            dicData: [
              {
                label: "安卓",
                value: 1
              },
              {
                label: "ios",
                value: 2
              }
            ],

            value: 1,
            rules: [
              {
                required: true,
                message: "请选择软件类型",
                trigger: "blur"
              }
            ],
          },

          {
            label: "文件类型",
            prop: "fileType",
            type: "radio",
            span: 24,
            search: true,
            dicData: [
              {
                label: "完整安装包",
                value: 0
              },
              {
                label: "wgt热更新包",
                value: 1
              }
            ],
            value: 1,
            rules: [
              {
                required: true,
                message: "请选择资源类型",
                trigger: "blur"
              }
            ],
          },
          {
            label: "更新内容",
            prop: "updateContent",
            span: 24,
            minRows: 3,
            type: "textarea",
            hide: true,
            rules: [{
              required: true,
              message: "请填写更新内容",
              trigger: "blur"
            }]
          },
          {
            label: "文件地址",
            prop: "fileUrl",
            span: 24,
            hide: true,
            rules: [{
              required: false,
              message: "请上传文件",
              trigger: "blur"
            }]
          },
          {
            label: "强制更新",
            prop: "constraintUpdate",
            type: "radio",
            span: 24,
            search: true,
            dicData: [
              {
                label: "是",
                value: 1
              },
              {
                label: "否",
                value: 0
              }
            ],
            value: 1,
            rules: [
              {
                required: true,
                message: "请选择是否强制更新",
                trigger: "blur"
              }
            ],
          },
          {
            label: "更新时间",
            prop: "updateDate",
            span: 24,
            type: "time",
            display: false
          },
        ]
      },
      versionId: '',
      headers: {},
    };
  },
  watch: {
    'packageForm.packageId'() {
      if (!validatenull(this.packageForm.packageId)) {
        packageDetail(this.packageForm.packageId).then(res => {
          this.packageForm.menuId = res.data.data.menuId;
          this.initData();
        });
      }
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tenant_add, false),
        delBtn: this.vaildData(this.permission.tenant_delete, false),
        editBtn: this.vaildData(this.permission.tenant_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    tenantId() {
      return this.selectionList[0].tenantId;
    }
  },
  methods: {
    setHeaders() {
      this.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
      this.headers[website.tokenHeader] = 'bearer ' + getToken()
    },
    initData() {
      getMenuTree().then(res => {
        const column = this.findObject(this.packageOption.column, "menuId");
        column.dicData = res.data.data;
      });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },

    rowSaveDetail(row, done, loading) {
      row.versionId = this.versionId
      addDetail(row).then(() => {
        this.onLoadDetail(this.pageDetail);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdateDetail(row, index, done, loading) {
      updateDetail(row).then(() => {
        this.onLoadDetail(this.pageDetail);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    rowDelDetail(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeDetail(row.id);
        })
        .then(() => {
          this.onLoadDetail(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    beforeOpen(done, type) {
      if (["view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          const data = res.data.data;
          if (!(data.accountNumber > 0)) {
            data.accountNumber = "不限制";
          }
          if (!data.expireTime) {
            data.expireTime = "不限制";
          }
          this.form = data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },


    handlePackage() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      if (this.selectionList.length === 1) {
        packageInfo(this.selectionList[0].id).then(res => {
          const data = res.data.data;
          this.packageForm.packageId = data.id;
          this.packageForm.menuId = data.menuId;
        });
      } else {
        this.packageForm.menuId = '';
      }
      this.packageBox = true;
      //更新字典远程数据
      setTimeout(() => {
        const form = this.$refs.formPackage;
        form.updateDic('packageId');
      }, 10);
    },
    handlePackageSetting() {
      this.packageSettingBox = true;
    },
    handleSubmit(form, done, loading) {
      setting(this.ids, form).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "配置成功!"
        });
        done();
        this.box = false;
      }, error => {
        window.console.log(error);
        loading();
      });
    },


    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    currentChangeDetail(currentPage) {
      this.pageDetail.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    refreshChangeDetail() {
      this.onLoadDetail(this.pageDetail);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleAdd(row, index) {
      this.dialogUpload = true;
      this.versionId = row.id
      this.onLoadDetail(this.pageDetail)
      this.setHeaders()
    },
    onLoadDetail(page) {
      this.loadingDeail = true;
      getDetailList(page.currentPage, page.pageSize, this.versionId).then(res => {
        const data = res.data.data;
        this.pageDetail.total = data.total;
        this.dataDetail = data.records;
        this.loadingDeail = false;
      });
    },
    handleRemove(file) {
      this.form.fileUrl = '';
      this.form.fileSize = '';
    },
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件，请先移除后，再次上传`);
    },
    handleSuccess(res) {
      this.$message({
        type: "success",
        message: "上传成功!"
      });
      this.form.fileUrl = res.data.link;
      this.form.fileSize = res.data.fileSize
      this.isLoading = false
    },
    handleError() {
      this.isLoading = false
      this.$message({
        type: "error",
        message: "上传失败!"
      });
    },
    handleProgress() {
      this.isLoading = true
    },
  },
  created() {
    this.setHeaders()
  },
};
</script>

<style lang="scss">
.el-dialog__wrapper.app-upload-dialog .el-dialog {
  width: 80%;
}
</style>
