<template>
  <div class="upgradationBox">
    <div class="uploadForm">
      <div class="noteBox">
        <h3 class="lableBox">文件类型：</h3>
        <el-select v-model="reportData.type" placeholder="请选择">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="upgradeBox">
        <h3 class="lableBox">文件上传：</h3>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="#"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          :http-request="customUpload"
          :limit="1"
          :file-list="fileList"
          :data="reportData"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
        </el-upload>
      </div>
      <div class="noteBox">
        <h3 class="lableBox">文件备注：</h3>
        <el-input
          class="noteClass"
          v-model="reportData.title"
          placeholder="输入备注"
          clearable
        ></el-input>
        <el-button
          class="uploadBtn"
          size="small"
          type="primary"
          @click="submitUpload"
          >上传到服务器</el-button
        >
      </div>
    </div>
    <div class="uploadPressMask" v-if="progressLoading">
      <div class="centerClass">
        <el-progress type="circle" :percentage="progress"></el-progress>
      </div>
    </div>
    <div class="uploadList">
      <el-table
        :data="fileData"
        style="width: 100%"
        border
        stripe
        height="calc(100% - 0px)"
        v-loading="fileloading"
      >
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column prop="fileName" label="文件名称">
          <template slot-scope="scope">
            <span> {{ scope.row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小">
          <template slot-scope="scope">
            {{ scope.row.fileSize | changeType }}
          </template>
        </el-table-column>
        <el-table-column prop="path" label="文件路径">
          <template slot-scope="scope">
            <span @click="handleClick(scope.row)" class="buttonText">
              {{ scope.row.path }}</span
            >
          </template>
        </el-table-column>

        <el-table-column prop="title" label="备注"> </el-table-column>
        <!-- <el-table-column prop="path" label="文件路径"> </el-table-column> -->
        <el-table-column label="操作" width="300" class-name="editClass">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="handleEditClick(scope.row)"
              size="small"
              icon="el-icon-edit"
              >修改</el-link
            >
            <el-link
              type="danger"
              @click="handleDeleteClick(scope.row)"
              size="small"
              icon="el-icon-delete"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      class="titleDialog"
      title="修改备注"
      :visible.sync="titleShow"
      :close-on-click-modal="false"
      width="480px"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="文件备注" prop="notesNewVal">
          <el-input v-model="ruleForm.notesNewVal"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmClick">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  upgradeListApi,
  upgradeUpLoadApi,
  upgradeDeleteApi,
  upgradeTitleApi,
} from "@/utils/api/index";

export default {
  name: "deviceUpgrade",
  components: {},
  data() {
    return {
      //上传apk notesVal
      fileList: [],
      reportData: {
        title: "",
        type: 0,
      },
      typeOptions: [
        {
          value: 0,
          label: "APK",
        },
        {
          value: 1,
          label: "OTA",
        },
        {
          value: 3,
          label: "配置文件",
        },
      ],
      fileData: [], //数据列表
      fileloading: false,
      editShow: false,
      titleShow: false,
      ruleForm: {
        notesNewVal: "",
      },
      rules: {
        notesNewVal: [
          { required: true, message: "请输入备注信息", trigger: "blur" },
        ],
      },
      rowData: "", //选中数据
      progress: 0,
      progressLoading: false,
    };
  },
  computed: {},
  filters: {
    changeType(val) {
      if (val === 0) return "0B";

      var k = 1024;
      var sizes = ["B", "KB", "MB", "GB", "TB"];

      let i = 0;
      while (val >= k) {
        val /= k;
        i++;
      }

      let formattedVal = parseFloat(val.toFixed(2))
        .toString()
        .replace(/(\.\d*?)(0+)$/, function (m, $1, $2) {
          return $2.length > 0 ? $1 : val.toString();
        });

      return formattedVal + " " + sizes[i];
    },
  },
  mounted() {
    this.getUpgradeList();
  },
  methods: {
    //双击选中复制
    handleClick(row) {
      console.log(row);
      // 创建一个新的a标签元素
      const a = document.createElement("a");
      // 设置a标签的href属性为文件的URL
      a.href = row.path;
      console.log(a.href);
      // 设置文件名（可选，取决于服务器配置）
      a.download = row.fileName; // 你希望保存的文件名
      // 触发点击事件
      document.body.appendChild(a);
      a.click();
      // 然后移除a标签
      document.body.removeChild(a);
    },
    //上传进度
    handleProgress(event, file, fileList) {
      this.progressLoading = true;
      // 获取上传进度百分比
      if (event.percent == 100) {
        this.progress = 98;
      } else {
        this.progress = Math.round(event.percent);
      }
      // 显示上传进度
      console.log(this.progress); // 或者你可以使用其他方式来显示进度，比如使用进度条组件等。
    },
    handleFileChange(file) {
      const titleName = file.name;
      console.log(titleName);
      // 正则表达式检查文件名是否符合模式
      // const regex =
      //   /^(mpapp|MpMaster)_v\d+\.\d+(\.\d+)?_rel_\d{8}_([a-zA-Z0-9-]+)?\.apk$/;
      const regex =
        /^(mpapp|MpMaster)_v(\d+\.\d+(\.\d+)?)_rel_\d{8}(_([a-zA-Z0-9-]+))?\.apk$/;

      if (regex.test(titleName)) {
        console.log(titleName);
        // 提取版本号（v后面的数字）
        const versionMatch = titleName.match(regex);
        if (versionMatch) {
          console.log(versionMatch);
          // 构造新的文件名（去掉V和_rel_日期部分）
          const baseName = titleName.startsWith("mpapp") ? "mpapp" : "mpmst"; // 注意：这里假设mpmaster应该改为mpmst
          const version = versionMatch[2];
          // 提取架构信息（如果存在）
          const architecture = versionMatch[4] || ""; // 如果没有架构信息，则为空字符串
          this.reportData.title = `${baseName}_v${version}${architecture}`;
        }
      } else {
        this.reportData.title = "";
      }
      console.log(this.reportData.title);
    },
    beforeUpload(file) {
      const fileName = file.name;
      console.log(fileName);

      if (fileName.toLowerCase().includes("apk")) {
        this.reportData.type = 0;
      }
      if (fileName.toLowerCase().includes("zip")) {
        this.reportData.type = 1;
      }
      // if (fileName.length > 19) {
      //   this.$message.error("文件名长度不能超过 19 个字符！");
      //   return false; // 阻止文件自动上传
      // }
      return true; // 允许文件继续上传
    },

    //上传apk
    submitUpload() {
      //console.log();
      this.$refs.upload.submit();
    },
    customUpload(options) {
      console.log(options);
      const formData = new FormData();
      formData.append("file", options.file);
      formData.append("title", this.reportData.title); // 假设后端需要这个字段
      formData.append("type", this.reportData.type); // 假设后端需要这个字段
      console.log(formData);
      upgradeUpLoadApi(formData, (progressEvent) => {
        // 计算上传进度百分比
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        this.progressLoading = true;
        // 更新UI或执行其他逻辑，比如显示进度条
        console.log(`上传进度: ${percentCompleted}%`);
        this.progress = Math.round(percentCompleted);
        // 你可以通过其他方式将进度信息传递给组件或Vue实例
        // this.uploadProgress = percentCompleted; // 假设你有一个data属性来存储进度
      })
        .then((res) => {
          console.log(res);
          // this.progressLoading = true;
          if (res.code == 200) {
            this.$message({
              duration: 1500,
              showClose: true,
              message: "文件上传成功",
              type: "success",
            });
            this.reportData.title = "";
            this.$refs.upload.clearFiles();
            this.getUpgradeList();
            this.progressLoading = false;
          } else {
            this.$message({
              duration: 1500,
              showClose: true,
              message: res.msg,
              type: "error",
            });
            this.progressLoading = false;
            this.reportData.title = "";
            this.$refs.upload.clearFiles();
          }
        })
        .catch((error) => {
          this.progressLoading = false;
        });
    },

    getUpgradeList() {
      this.fileloading = true;
      upgradeListApi()
        .then((res) => {
          console.log(res);
          this.fileData = res.data;
          this.fileloading = false;
        })
        .catch((err) => {});
    },
    handleDeleteClick(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          upgradeDeleteApi({
            id: row.id,
          })
            .then((res) => {
              console.log(res);
              this.$message({
                duration: 1500,
                showClose: true,
                message: "文件删除成功",
                type: "success",
              });
              this.getUpgradeList();
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    handleEditClick(row) {
      console.log(row);
      this.titleShow = true;
      this.ruleForm.notesNewVal = row.title;
      this.rowData = row;
    },
    confirmClick() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log(this.ruleForm.notesNewVal);
          upgradeTitleApi({
            id: this.rowData.id,
            title: this.ruleForm.notesNewVal,
          })
            .then((res) => {
              console.log(res);
              this.$message({
                duration: 1500,
                showClose: true,
                message: "修改备注成功",
                type: "success",
              });
              this.titleShow = false;
              this.getUpgradeList();
            })
            .catch((err) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style lang="less">
.upgradationBox {
  height: calc(100% - 24px);
  width: calc(100% - 24px);
  padding: 12px;

  .upgradeBox {
    height: 32px;
    line-height: 32px;
    display: flex;
    margin-bottom: 16px;
    // align-items: center;
    // flex-direction: column;
    .lableBox {
      font-size: 14px;
      font-weight: normal;
      width: 78px;
    }

    .upload-demo {
      position: relative;
      display: flex;
      flex-direction: row-reverse;
      margin-right: 32px;
      .el-upload-list {
        width: 320px;
        height: 32px;
        line-height: 32px;
        border: 1px solid #ddd;
        margin-right: 12px;
        border-radius: 4px;
        .el-upload-list__item {
          transition: none;
          font-size: 14px;
          color: #606266;
          position: relative;
          box-sizing: border-box;
          border-radius: 4px;
          width: 100%;
          height: 32px;
          line-height: 32px;
          margin-top: 0px !important;
          .el-icon-close {
            top: 10px;
          }
        }
      }
    }
  }
  .noteBox {
    height: 32px;
    line-height: 32px;
    display: flex;
    margin-bottom: 16px;
    .noteClass {
      width: 322px;
    }
    .lableBox {
      font-size: 14px;
      font-weight: normal;
      width: 78px;
    }
  }
  .uploadBtn {
    margin-left: 12px;
  }
  .uploadForm {
    .el-button--default,
    .el-button--primary {
      width: auto;
    }
  }
  .uploadList {
    margin-top: 20px;
    height: calc(100% - 148px);
    .el-table {
      .el-table__cell {
        text-align: center;
      }
    }
  }
  .editClass {
    .el-link.el-link--primary {
      margin-right: 14px;
    }
  }
  .uploadPressMask {
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: hsla(0, 0%, 100%, 0.9);
    margin: 0;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 3;
    .centerClass {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }
  }

  .el-table::before {
    height: 1px !important;
  }
  .buttonText {
    color: #169e8c;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
.el-dialog__headerbtn {
  top: 18px;
  .el-dialog__close {
    font-size: 26px;
    &:hover {
      background: #e2e2e2;
    }
  }
}
</style>
