<template>
  <div class="monitoring">
    <header>
      <div class="left">
        <el-input
            placeholder="插件名称、插件编号、插件版本"
            v-model="searchForm.name"
            @keyup.enter.native="searchBtnHandle"
        >
          <i slot="suffix" class="el-input__icon el-icon-search" @click="searchBtnHandle"></i>
        </el-input>
      </div>
      <div class="right">
        <el-button
          icon="el-icon-back"
          @click="
            $router.replace({ path: '/applicationList/applicationListAdmin' })
          "
        >返回</el-button
        >
        <el-button type="primary" icon="el-icon-plus" @click="inserterAdd"
        >添加插件
        </el-button
        >
      </div>
    </header>
    <main>
      <BaseTable
          ref="mainTable"
          :tableData="tableData"
          :tableColumn="tableColumn"
          :funData="funData"
          :funWidth="funWidth"
          :showIndex="true"
          :tabLoading="mainTabLoading"
          @onFunc="tableButtonHandle"
          :tableHeight="'70vh'"
          :border="false"
      >
      </BaseTable>
      <div class="page">
        <basePage
            :pageModel="pageModel"
            @update:pageModel="currentChangeHandle"
        ></basePage>
      </div>
    </main>
    <footer></footer>
    <baseDialog
        :title="'插件配置'"
        v-model="plugInDialog"
        @confirm="plugInConfirm"
        :width="'50%'"
    >
      <div v-if="plugInDialog">
        <baseNewForm
            ref="dataSettingForm"
            :spanNumber="24"
            :isFunBtn="false"
            :lookFlag="lookFlag"
            :formRule="!lookFlag"
            :formRow="formRow"
            :ruleForm="ruleForm"
            @onSubmit="onSubmit"
        >
        </baseNewForm>
        <div class="upload-download-container">
          <div class="c_left">
          <el-upload
          class="avatar-uploader"
          ref="upload"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :on-progress="handleProgress"
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          list-type="text"
          :limit="1"
          :disabled="lookFlag"
          :on-success="handleAvatarSuccess"
          :show-file-list="true"
        >
          <div class="line">
            <div class="left">
              <el-input v-model="uploadStatus" readonly placeholder="未上传附件">
              </el-input>
            </div>

            <div class="right" v-if="!lookFlag">
              <el-button size="small" type="primary" v-if="!loading"
              >点击上传</el-button
              >
              <el-button
                size="small"
                type="primary"

                v-else
              >点击上传</el-button
              >

            </div>


          </div>

        </el-upload>
            </div>
          <div class="c_right">
            <el-button
              size="small"
              type="primary"
              @click="downloadPlugin"
            >下载附件</el-button>
            </div>
        </div>

        <div slot="tip" class="el-upload__tip" v-if="!lookFlag">
          <p style="font-weight: bold;">注意：只能上传zip文件，第一层目录结构为com和cfgHome，且附件大小在20MB以内</p>
        </div>
      </div>
    </baseDialog>
  </div>
</template>

<script>
import {deepClone} from "@/utils/index.js";
import baseNewForm from "@/views/intergrationTask/compoments/baseNewForm";
import baseDialog from "@/views/integrationOption/compoments/baseDialog";
import configData from "./configData.js";
import dayjs from "dayjs";
import BaseTable from "@/views/intergrationTask/compoments/baseTable.vue";
import basePage from "@/views/intergrationTask/compoments/basePage.vue";
import {getApiModuleApi} from "@/api/apiChunks/index.js";
import request from "@/utils/request";
import axios from 'axios';
export default {
  data() {
    return {
      ruleForm: {
        pluginStatus: "1",
        attachmentId:"",
      },
      uploadStatus:"",
      formRow: configData.formRow,
      lookFlag: false,
      plugInDialog: false,
      refreshLoading: false,
      searchForm: {
        name: "",
      },
      mainTabLoading: false,
      funData: [
        {
          type: "view",
          text: "更新",
          color: "#5a9cf8",
        },
        {
          type:"publish",
          text:"发布",
          color:"#5ac918",
        },
        {
          type:"withdraw",
          text:"撤回",
          color:"#a9a9a9",
        },
        {
          type: "dele",
          text: "删除",
          color: "#e47470",
        },
      ],
      tableColumn: configData.tableColumn,
      tableData: [],
      pageModel: {
        pageIndex: 1,
        total: 10,
        limit: 10,
      },
      editFlag: false,
    };
  },

  methods: {
    // beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除 ${ file.name }？`);
    // },
    async downloadPlugin(){
      if(this.uploadStatus === "" || this.uploadStatus === null){
        this.$message({
          type: "warning",
          message: "请先上传附件",
        });
        return false;
      }
      let formData = new FormData();
      formData.append("id", this.ruleForm.attachmentId);
      const res = await axios({
        url: 'kangarooDataCenterV3/entranceController/fileDownloadNew',
        method: 'post',
        responseType: 'blob',// 重要：指示axios返回二进制数据
        data:formData
      });

      const blob = new Blob([res.data],{type:'application/x-zip-compressed'});

      const link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.setAttribute('download',this.ruleForm.attachmentId);
      document.body.appendChild(link);
      link.click();

      document.body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
      if(res.status === '200'){
        this.$vmNews("下载成功","success")
      }
    },

    // 文件上传相关时间
    handleProgress(file, fileList) {
      this.loading = true;
      this.handleAvatarSuccess({}, fileList).then((res) => {
        this.loading = false;
      });
    },

    async handleAvatarSuccess(res, file) {
      file.raw.type;
      if (
        file.name.split(".")[1] != "zip"
      ) {
        return false;
      } else if (file.size >= 20000000) {
        return false;
      }
      this.$refs.upload.clearFiles(); //清理文件上传状态

      this.imgUrl = URL.createObjectURL(file.raw);
      let formData = new FormData();
      formData.append("file", file.raw);
      formData.append("fileFlag", true);
      formData.append("businessType", "application");
      formData.append("fileType","2");
      formData.append("pluginPackageName",this.ruleForm.pluginPackageName);
      // console.log(formData);
      // const el = await uploadLogo(formData)
      // if (el.status === '200') {
      //   this.$vmNews("上传成功", "success")
      //   this.appLogo = el.id
      // }
      return request({
        url: "/kangarooDataCenterV3/entranceController/pluginfileUpload",
        method: "post",
        data: formData,
      }).then((res) => {
        if (res.status === "200") {
          this.$vmNews("上传成功", "success");
          //this.appLogo = res.attribute.id;
          this.ruleForm.attachmentId = res.attribute.id;
          this.uploadStatus = res.attribute.filename;
        }
        return true;

        // this.loading = false
      });
    },
    beforeUpload(file) {
      console.log(this.ruleForm.pluginPackageName)
      if (
        file.name.split(".")[1] != "zip"
      ) {
        this.$message({
          type: "warning",
          message: "只能上传zip文件",
        });
        return false;
      } else if(this.ruleForm.pluginPackageName === undefined || this.ruleForm.pluginPackageName === null || this.ruleForm.pluginPackageName === "") {
        this.$message({
          type: "warning",
          message: "请填写插件包名，用于校验附件是否合规",
        });
        return false;
      }else {
        if (file.size >= 20000000) {
          this.$message({
            type: "warning",
            message: "文件大小不超过20MB",
          });
          return false;
        }
      }
    },

    searchBtnHandle() {
      this.initMainTableData(this.searchForm)
    },
    async onSubmit() {
      if(!this.ruleForm.id){
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "saveAppPlugin"
        }, {appId: this.$route.query.id, ...this.ruleForm,})
        if(res.status==='200'){
          this.$vmNews("提交成功","success")
          this.plugInDialog =false
          this.ruleForm={}
          this.initMainTableData()
        }
      }else {
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "updateAppPlugin"
        }, {appId: this.$route.query.id, ...this.ruleForm})
        if (res.status === '200') {
          this.$vmNews("提交成功", "success")
          this.plugInDialog = false
          this.ruleForm = {}
          this.initMainTableData()
        }
      }
    },
    plugInConfirm() {
      this.$refs.dataSettingForm.submitForm();
    },
    // 添加应用
    inserterAdd() {
      this.uploadStatus = ""
      this.ruleForm = {}
      this.plugInDialog = true;
      // this.$router.push({ path: "/inserterAdmin/inserterAdd" });
    },
    // 时间处理
    getTimeHandler(time) {
      var days = parseInt(time / (1000 * 60 * 60 * 24));
      var hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = (time % (1000 * 60)) / 1000;
      return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
    },
    // 初始化表单
    async initMainTableData(obj = {}) {
      this.refreshLoading = true;
      const res = await getApiModuleApi(
          {
            tl: "sysApplicationService",
            as: "application",
            dj: "queryAppPlugin",
          },
          {
            pageNum: this.pageModel.pageIndex,
            pageSize: this.pageModel.limit,
            ...obj,
            appId:this.$route.query.id,
          }
      );
      this.refreshLoading = false;
      if (res.status == 200) {
        this.tableData = res.attribute.list;
        this.pageModel.total = res.attribute.total;
        console.log(res);
      }
    },
    // 点击提交
    submitsearchForm() {
      this.initMainTableData(this.searchForm);
    },
    // 表单操作
    tableButtonHandle(val, item) {
      if (item.type === "view") {
        this.ruleForm = deepClone(val)
        this.plugInDialog=true
        this.uploadStatus = val.attachmentId
        console.log(val)
      } else if (item.type === "dele") {
        this.$confirm("确认删除？（注意：需要重启服务器才能生效）")
            .then(
              async () => {
                const res1 =await getApiModuleApi({
                  tl:"sysApplicationService",
                  as:"application",
                  dj:"deleteAppPluginPackage"
                },{pluginPackageName:val.pluginPackageName,
                  id:val.id})
                if(res1.status === '200'){
                  this.$vmNews("撤回插件成功","success")
                  this.initMainTableData()
                }
              const res2 =await getApiModuleApi({
                tl:"sysApplicationService",
                as:"application",
                dj:"deleteAppPlugin"
              },{id:val.id})
              if(res2.status === '200'){
                this.$vmNews("删除插件成功","success")
                this.initMainTableData()
              }
            })
            .catch(() => {
            });
      }else if (item.type === "publish"){
        if(val.attachmentId==="" || val.attachmentId === null){
          this.$message({
            type: "warning",
            message: "该插件不存在附件",
          });
          return false;
        }
        this.$confirm("确认发布？（注意：需要重启服务器才能生效）")
          .then(async () => {
            let formData = new FormData();
            formData.append("id", val.attachmentId);
            const res = await request({
              url: 'kangarooDataCenterV3/entranceController/pluginZipUpdate',
              method: 'post',
              data: formData,
            })
            if(res.status === '200'){
              this.$vmNews("发布插件成功","success")
              this.initMainTableData()
            }
          })
          .catch(() => {
          });
      }else if (item.type ==="withdraw"){
        this.$confirm("确认撤回？（注意：需要重启服务器才能生效）")
          .then(async () => {
            const res =await getApiModuleApi({
              tl:"sysApplicationService",
              as:"application",
              dj:"deleteAppPluginPackage"
            },{pluginPackageName:val.pluginPackageName,
            id:val.id})
            if(res.status === '200'){
              this.$vmNews("撤回插件成功","success")
              this.initMainTableData()
            }
          })
          .catch(() => {
          });
      }
    },
    // 页码
    currentChangeHandle(pageModel) {
      this.pageModel = pageModel;
      this.$nextTick(() => {
        this.initMainTableData(this.searchForm);
      });
    },
  },
  computed: {
    // 操作框的宽度
    funWidth() {
      return this.funData.length * 70;
    },
  },
  components: {
    BaseTable,
    basePage,
    baseDialog,
    baseNewForm,
  },
  created() {
    this.initMainTableData();
    this.$emit("flashActive",5)
  },
};
</script>

<style scoped lang='scss'>
.monitoring {
  position: relative;
  width: 100%;
  background-color: #fafafa;

  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background-color: #fff;
    border-radius: 20px;

    .left {
      width: 20vw;
      align-items: center;
      display: flex;

      .search {
        margin-left: 30px;
        display: flex;

        > .chunk {
          margin-left: 10px;
        }
      }
    }
  }

  main {
    margin-top: 10px;
    padding: 20px 20px 5px;
    border-radius: 20px;
    background-color: #fff;
  }

  footer {
    margin-top: 20px;
  }
}

/* 为了确保下载按钮始终位于右侧 */
.el-upload__tip {
  margin-top: 10px; /* 与上方元素保持一定间距 */
  margin-bottom: 10px;
  margin-left: 20px;
}

.line {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left {
  //flex-grow: 1; /* 让文本框占据剩余空间 */
  margin-right: 10px; /* 与按钮保持一定间距 */
}

.right {
  display: flex;
  align-items: center;
  margin-right:10px
}

.upload-download-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-left:20px;
}

.c_left, .c_right {
  display: flex;
  align-items: center;
}

.c_right {
  margin-right: auto; /* 将下载按钮推到最右边 */
}
</style>
