<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <div style="float: right; margin-right: 2%">
        <el-button style="margin: 10px 0" :disabled="!isAuth('app:add')" size="mini" type="primary" icon="document"
          v-if="upgradeData1.records.length <= 0" @click="addUpgrade">添加升级</el-button>
      </div>
      <el-table v-loading="tableDataLoading" :data="upgradeData1.records">
        <el-table-column fixed prop="id" label="编号" width="80">
        </el-table-column>
        <!-- <el-table-column prop="wgtUrl" label="统一地址"> </el-table-column> -->
        <el-table-column prop="androidWgtUrl" label="安卓"> </el-table-column>
        <!-- <el-table-column prop="iosWgtUrl" label="苹果"> </el-table-column> -->
        <el-table-column prop="version" label="安卓版本"> </el-table-column>
        <el-table-column prop="iosVersion" label="ios版本"> </el-table-column>
        <el-table-column prop="content" label="升级方式">
          <template slot-scope="scope">
            <span>{{
              scope.row.method == "true" ? "强制升级" : "普通升级"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createAt" label="创建时间"> </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" :disabled="!isAuth('app:update')"
              @click="upgradebj(scope.$index, scope.row)">编辑
            </el-button>
            <el-button size="mini" type="danger" :disabled="!isAuth('app:delete')" @click="upgradelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center; margin-top: 10px">
        <el-pagination @size-change="handleSizeChange2" @current-change="handleCurrentChange2"
          :page-sizes="[10, 20, 30, 40]" :page-size="limit" :current-page="page"
          layout="total,sizes, prev, pager, next,jumper" :total="upgradeData1.total">
        </el-pagination>
      </div>
      <!-- 添加修改升级弹框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible4" center @close="resetFormupgrad">
        <el-form :model="formupgrad">
          <!-- <el-form-item
            label="统一地址："
            :label-width="formLabelWidth"

          >
            <el-input v-model="formupgrad.wgtUrl" style="width: 65%"></el-input>
          </el-form-item> -->
          <div class="file-box" style="margin-bottom: 10px; display: flex">
            <span style="width: 200px; display: inline-block; text-align: right"><i
                style="color: #f56c6c; margin-right: 2px">*</i>安卓包：</span>
            <div style="
                width: 200px;
                height: 148px;
                border: 1px dashed #c0ccda;
                border-radius: 6px;
                text-align: center;
              ">
              <el-upload class="avatar-uploader" v-model="formupgrad.androidWgtUrl" action="" :auto-upload="false"
                :onChange="onChooseAndriod" :show-file-list="false" :multiple="false">
                <div v-if="formupgrad.androidWgtUrl" class="flex flex-col flex-xy-center">
                  <img src="../../assets/img/android.png" style="width: 50px; height: 50px" />
                  <span style="margin-top: 10px">{{
                    formupgrad.androidWgtUrl | name
                  }}</span>
                </div>
                <i v-if="!formupgrad.androidWgtUrl && percentage <= 0"
                  class="el-icon-plus avatar-uploader-icon iconss"></i>
                <el-progress type="circle" v-if="
                  !formupgrad.androidWgtUrl &&
                  percentage > 0 &&
                  percentage <= 100 &&
                  key == 'andriod'
                " :percentage="percentage" color="#efefef"></el-progress>
              </el-upload>
            </div>
          </div>
          <el-form-item label="安卓地址：" :label-width="formLabelWidth" required>
            <el-input v-model="formupgrad.androidWgtUrl" style="width: 65%"></el-input>
          </el-form-item>
          <!-- <div class="file-box" style="margin-bottom: 10px; display: flex">
            <span style="width: 200px; display: inline-block; text-align: right"
              >苹果包：</span
            >
            <div
              style="
                width: 200px;
                height: 148px;
                border: 1px dashed #c0ccda;
                border-radius: 6px;
                text-align: center;
              "
            >
              <el-upload
                class="avatar-uploader"
                v-model="formupgrad.iosWgtUrl"
                action=""
                :auto-upload="false"
                :onChange="onChooseIos"
                :show-file-list="false"
                :multiple="false"
              >
                <div
                  v-if="formupgrad.iosWgtUrl"
                  class="flex flex-col flex-xy-center"
                >
                  <img
                    src="../../assets/img/ios.png"
                    style="width: 50px; height: 50px"
                  />
                  <span style="margin-top: 10px">{{
                    formupgrad.iosWgtUrl | name
                  }}</span>
                </div>
                <i
                  v-if="!formupgrad.iosWgtUrl && percentage <= 0"
                  class="el-icon-plus avatar-uploader-icon iconss"
                ></i>
                <el-progress
                  type="circle"
                  v-if="
                    !formupgrad.iosWgtUrl && percentage > 0 && percentage <= 100&&key=='ios'
                  "
                  :percentage="percentage"
                  color="#efefef"
                ></el-progress>
              </el-upload>
            </div>
          </div>
          <el-form-item
            label="苹果地址："
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="formupgrad.iosWgtUrl"
              style="width: 65%"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="安卓版本号：" :label-width="formLabelWidth" required>
            <el-input v-model="formupgrad.version" style="width: 65%"></el-input>
          </el-form-item>
          <el-form-item label="ios版本号：" :label-width="formLabelWidth" required>
            <el-input v-model="formupgrad.iosVersion" style="width: 65%"></el-input>
          </el-form-item>
          <el-form-item label="升级方式：" :label-width="formLabelWidth" required>
            <el-select v-model="formupgrad.method" placeholder="请选择升级方式" style="width: 65%">
              <el-option v-for="item in methods" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="升级内容：" :label-width="formLabelWidth" required>
            <el-input v-model="formupgrad.des" style="width: 65%"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible4 = false">取 消</el-button>
          <el-button type="primary" @click="upgradbjTo()">确 定</el-button>
        </div>
      </el-dialog>
    </el-tabs>
  </div>
</template>

<script>
import { getUUID } from "@/utils";
import OSS from "@/utils/oss-upload.js";
import { $getCredentials } from "@/api/oss.js";
import config from "@/config/index.js";

export default {
  data() {
    return {
      dialogTitle: "",
      limit: 10,
      page: 1,
      state: 1,
      url: "",
      title: "",
      type: "",
      id: "",
      nav: "",
      keyword: "",
      image_url: "",
      androidWgtUrl: "",
      key: "",
      //文件上传进度
      percentage: 0,
      iosWgtUrl: "",
      wgtUrl: "",
      version: "",
      iosVersion: "",
      des: "",
      checkBoxData: [], //多选框选择的值
      method: "false",
      methods: [
        {
          value: "false",
          label: "普通升级",
        },
        {
          value: "true",
          label: "强制升级",
        },
      ],
      formupgrad: {
        id: "",
        androidWgtUrl: "",
        iosWgtUrl: "",
        wgtUrl: "",
        version: "",
        des: "",
        method: "",
        iosVersion: "",
      },
      formLabelWidth: "200px",
      activeName: "first",
      tableDataLoading: true,
      dialogFormVisible3: false,
      dialogFormVisible4: false,
      tableData: [],
      homeData: [],
      choicenData2: [],
      upgradeData: [],
      upgradeData1: {
        records: []
      },
      choicenData: [],
      types: [
        {
          value: "word",
          label: "文字",
        },
        {
          value: "url",
          label: "链接",
        },
      ],
      bannerData: [],
      form1: {
        id: "",
        url: "",
        image_url: "",
      },
      form: {
        id: "",
        title: "",
        url: "",
        type: "",
        state: "",
        types: [
          {
            value: "word",
            label: "文字",
          },
          {
            value: "url",
            label: "链接",
          },
        ],
      },
      formcomp: {
        id: "",
        state: "",
        title: "",
        url: "",
        image_url: "",
      },
    };
  },
  filters: {
    name(str) {
      if (!str) {
        return "";
      }
      return str.substr(str.lastIndexOf("/") + 1);
    },
  },
  methods: {
    resetFormupgrad() {
      for (let i in this.formupgrad) {
        this.formupgrad[i] = "";
      }
    },
    async initOssClient() {
      console.log("initOssClient");
      const { data } = await $getCredentials();
      if (data.code == 0) {
        const res = data.data;
        console.log(res);
        this.ossClient = new OSS({ ...res, stsToken: res.securityToken });
      }
    },
    onFileIosCHange(data) {
      this.onFileCHange(data);
    },
    async onChooseAndriod(data) {
      this.formupgrad.androidWgtUrl = "";
      this.percentage = 0;
      this.key = "andriod";
      const url = await this.uploadFie(data);
      this.percentage = 0;
      console.log(url);
      if (url) {
        this.formupgrad.androidWgtUrl = url;
      }
    },
    async onChooseIos(data) {
      this.formupgrad.iosWgtUrl = "";
      this.percentage = 0;
      this.key = "ios";
      const url = await this.uploadFie(data);
      console.log(url);
      this.percentage = 0;
      if (url) {
        this.formupgrad.iosWgtUrl = url;
      }
    },
    async uploadFie(data) {
      console.log(data);
      const date = new Date();
      const houzhui = "." + data.name.substr(data.name.lastIndexOf(".") + 1);
      const isTest = config.baseUrl.includes('web.hnsiyao.cn') ? false : true
      const appName = isTest ? 'test-duanju' : 'sy-duanju'
      const name = "app/" + appName + houzhui;
      console.log(name);
      const fileRes = await this.ossClient.partUpload(name, data.raw, (p) => {
        this.percentage = Math.floor(p * 100);
        console.log(this.percentage);

        // 这里可以根据进度做相应的处理，例如更新UI等
      });
      console.log("fileRes");
      console.log(fileRes);
      if (!fileRes) {
        this.percentage = 0;
        this.$notify({
          title: "失败",
          message: `上传阿里云失败`,
          type: "error",
        });
        return;
      }
      if (fileRes.name == "cancel") {
        return;
      }
      return fileRes.replace(
        "https://sy-duanju.oss-cn-chengdu.aliyuncs.com/",
        "https://short-video.hnsiyao.cn/"
      );
    },
    handleSizeChange2(val) {
      this.limit = val;
      this.upgradeSelect();
    },
    handleCurrentChange2(val) {
      this.page = val;
      this.upgradeSelect();
    },

    handleClick(tab, event) {
      this.upgradeSelect();
    },
    // 添加升级弹框
    addUpgrade() {
      this.initOssClient();
      this.dialogFormVisible4 = true;
      this.dialogTitle = "添加升级";
    },
    // 添加升级
    upgradaddTo() {
      if (this.formupgrad.wgtUrl == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请输入统一地址",
          type: "warning",
        });
        return;
      }
      if (this.formupgrad.androidWgtUrl == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请输入安卓地址",
          type: "warning",
        });
        return;
      }
      if (this.formupgrad.iosWgtUrl == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请输入苹果地址",
          type: "warning",
        });
        return;
      }

      if (this.formupgrad.version == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请输入安卓版本号",
          type: "warning",
        });
        return;
      }
      if (this.formupgrad.iosVersion == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请输入苹果版本号",
          type: "warning",
        });
        return;
      }

      if (this.formupgrad.method == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请选择升级方式",
          type: "warning",
        });
        return;
      }
      if (this.formupgrad.des == "") {
        this.$notify({
          title: "提示",
          duration: 1800,
          message: "请输入升级内容",
          type: "warning",
        });
        return;
      }
      if (this.dialogTitle == "添加升级") {
        return this.$http({
          url: this.$http.adornUrl("appinfo/save"),
          method: "post",
          data: this.$http.adornData({ ...this.formupgrad, id: "" }),
        }).then(({ data }) => {
          this.dialogFormVisible3 = false;
          this.upgradeSelect();
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => { },
          });
        });
      }
      this.upgradbjTo();
    },
    // 修改升级弹框
    upgradebj(index, rows) {
      this.initOssClient();
      this.dialogFormVisible4 = true;
      this.dialogTitle = "修改";
      Object.assign(this.formupgrad, rows);
    },
    // 修改升级
    upgradbjTo() {
      this.$http({
        url: this.$http.adornUrl("appinfo/save"),
        method: "post",
        data: this.$http.adornData({
          id: this.formupgrad.id,
          androidWgtUrl: this.formupgrad.androidWgtUrl,
          iosWgtUrl: this.formupgrad.iosWgtUrl,
          wgtUrl: this.formupgrad.wgtUrl,
          version: this.formupgrad.version,
          iosVersion: this.formupgrad.iosVersion,
          des: this.formupgrad.des,
          method: this.formupgrad.method,
        }),
      }).then(({ data }) => {
        this.dialogFormVisible4 = false;
        this.upgradeSelect();
        this.$message({
          message: "操作成功",
          type: "success",
          duration: 1500,
          onClose: () => { },
        });
      });
    },
    // 删除升级
    upgradelete(row) {
      let delid = row.id;
      this.id = delid;
      this.$confirm(`确定删除此条信息?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`appinfo/delete/${this.id}`),
            method: "get",
            params: this.$http.adornParams({}),
          }).then(({ data }) => {
            this.$message({
              message: "删除成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.name = "";
                this.upgradeSelect();
              },
            });
          });
        })
        .catch(() => { });
    },

    // 升级配置数据列表
    upgradeSelect() {
      this.tableDataLoading = true;
      this.$http({
        url: this.$http.adornUrl(
          `appinfo/list?page=${this.page}&limit=${this.limit}`
        ),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        this.tableDataLoading = false;
        let returnData = data.data;
        this.upgradeData1 = returnData;
      });
    },
  },
  mounted() {
    console.log("···························");
    this.upgradeSelect();
    this.initOssClient();
  },
};
</script>

<style scoped>
::v-deep .file-box .el-upload {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .avatar-uploader {
  width: 100%;
  box-sizing: border-box;
  height: 100%;
}

.el-upload {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.customWidth {
  width: 80% !important;
}

.adver_main.box {
  display: block;
  max-width: 100%;
  text-align: center;
  border: 1px dotted rgba(67, 79, 103, 0.4);
}

.margin-auto {
  margin: auto;
}

.cards {
  padding: 0 8px;
  margin-bottom: 15px;
}

.adver_main.box a {
  display: flex;
  justify-content: center;
  height: 150px;
  line-height: 150px;
  text-decoration: none;
}

.bannerManin {
  border: 1px solid #e8e8e8;
  font-size: 14px;
  padding: 0 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 113px;
  color: rgba(0, 0, 0, 0.65);
}

.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.flex-xy-center {
  justify-content: center;
  align-items: center;
}

.bannerManin span {
  display: inline-block;
  margin-left: 5px;
}

.bannerManin img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
}

.bannerbtn {
  display: flex;
  border-top: none !important;
  border: 1px solid #e8e8e8;
  padding: 11px;
  font-size: 14px;
  color: #3e8ef7;
}

.bannerbtn a {
  flex: 1;
  text-align: center;
  color: #3e8ef7 !important;
  text-decoration: none;
}
</style>
