<script src="configData.js"></script>
<template>
  <div class="wrap">
    <div class="btn">
      <div class="chunk">
        <el-button icon="el-icon-back" @click="
            $router.replace({ path: '/applicationList/applicationListAdmin' })
          ">返回</el-button>
      </div>
      <div class="chunk">
        <el-button icon="el-icon-first-aid-kit" type="primary" @click="saveHandle">保存</el-button>
      </div>
    </div>
    <div class="main" >
      <div class="upload">
        <div class="title">应用信息</div>
        <div class="uploadMain">
          <div class="left">
            <div class="title">应用logo</div>
            <el-upload class="avatar-uploader" ref="upload" action="https://jsonplaceholder.typicode.com/posts/" :on-preview="handlePreview" :on-progress="handleProgress" :before-upload="beforeUpload" list-type="picture" :limit="1" :disabled="lookFlag" :on-success="handleAvatarSuccess" :show-file-list="false">
              <div class="line">
                <div class="left">
                  <img v-if="imgUrl" :src="imgUrl" class="avatar" @error="handleImageError">
                  <!-- <el-image style="width: 64px; height: 64px" :src="iconBase64" fit="cover" alt="点击上传">
                    <template v-slot:error>
                      <div style="line-height: 64px; font-size: 12px">
                        logo上传
                      </div>
                    </template>
                  </el-image> -->
                </div>
                <div class="right" v-if="!lookFlag">
                  <el-button size="small" type="primary" v-if="!loading">点击上传</el-button>
                  <el-button size="small" type="primary" :loading="loading" v-else>上传中</el-button>
                </div>
              </div>
              <div slot="tip" class="el-upload__tip" v-if="!lookFlag">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </el-upload>
          </div>
          <div class="right">
            <el-switch active-value="1" inactive-value="2" v-model="appStatus" active-text="启用" active-color="#60c958" :disabled="lookFlag">
            </el-switch>
          </div>
        </div>
      </div>
      <div class="form">
        <baseNewForm ref="mainForm" :spanNumber="24" :isFunBtn="false" :lookFlag="lookFlag" :formRule="!lookFlag" :formRow="formRow" :ruleForm="ruleForm" @onSubmit="onSubmit"></baseNewForm>
      </div>
    </div>
  </div>
</template>

<script>
import { getApiModuleApi } from "@/api/apiChunks/index.js";
import { uploadLogo } from "@/api/apis/logo.js";
import configData from "./configData";
import baseNewForm from "@/views/intergrationTask/compoments/baseNewForm";
import request from "@/utils/request";

export default {
  data() {
    return {
      fileList: [],
      iconBase64: "",
      imgUrl: "",
      loading: false,
      appLogo: "",
      appStatus: 1,
      ruleForm: {
        accessMode: [],
      },
      lookFlag: false,
      formRow: configData.addForm,
    };
  },
  methods: {
    handleImageError(row) {
      this.imgUrl = require('./images/1.png')
    },
    // 文件上传相关时间
    handleProgress(file, fileList) {
      this.loading = true
      this.handleAvatarSuccess({}, fileList).then(res => {
        this.loading = false
      })
    },
    handlePreview(file) {
    },
    async handleAvatarSuccess(res, file) {
      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");
      // console.log(formData);
      // const el = await uploadLogo(formData)
      // if (el.status === '200') {
      //   this.$vmNews("上传成功", "success")
      //   this.appLogo = el.id
      // }
      return request({
        url: "/kangarooDataCenterV3/entranceController/fileUpload",
        method: "post",
        data: formData,
      }).then((res) => {
        if (res.status === '200') {
          this.$vmNews("上传成功", "success")
          this.appLogo = res.attribute.id
        }
        return true

        // this.loading = false
      })
    },
    async beforeUpload(file) {
      if (
        file.type.split("/")[1] != "jpeg" &&
        file.type.split("/")[1] != "png"
      ) {
        this.$message({
          type: "warning",
          message: "只能上传jpg/png文件",
        });
        return
      } else {
        if (file.size >= 2000000) {
          this.$message({
            type: "warning",
            message: "文件大小不超过2MB",
          });
          return
        }
        // let reader = new FileReader();
        // let that = this;
        // reader.onloadend = function () {
        //   // 将文件转换成base64字符串
        //   var base64String = reader.result;
        //   that.iconBase64 = base64String;
        // };
        // reader.readAsDataURL(file);
        // return false;
      }
    },
    // 保存按钮、列表验证
    saveHandle() {
      this.$refs.mainForm.submitForm();

    },
    //验证成功准备上传
    async onSubmit() {
      if (this.$route.query.flag === "add") {
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "saveApp"
        }, { ...this.ruleForm, appStatus: this.appStatus, appLogo: this.appLogo })
        if (res.status === '200') {
          this.$vmNews("保存成功", "success")
          this.$router.replace({ path: '/applicationList/applicationListAdmin' })
        }
      } else if (this.$route.query.flag === "copy") {
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "copyApp"
        }, { ...this.ruleForm, appStatus: this.appStatus, appLogo: this.appLogo })
        if (res.status === '200') {
          this.$vmNews("复制成功", "success")
          this.$router.replace({ path: '/applicationList/applicationListAdmin' })
        }
      } else if (this.$route.query.flag === "setting") {
        const res = await getApiModuleApi({
          tl: "sysApplicationService",
          as: "application",
          dj: "updateApp"
        }, { updateType: 1, ...this.ruleForm, appStatus: this.appStatus, appLogo: this.appLogo })
        if (res.status === '200') {
          this.$vmNews("保存成功", "success")
          this.initEditFormData()
          this.getLogoUrl()
          this.$emit("saveSuccess")
        }
      }
    },
    // 获取下拉数据
    async initSelectOptions() {
      let params = {
        tab_name: "sys_product",
        column_name: "classify",
      };
      const res = await getApiModuleApi({
        tl: "generalServiceImpl",
        as: "dictionaryshop",
        dj: "selectDictionaryshop"
      }, params)
      this.formRow[3].elCol[0].options = []
      res.attribute.forEach((item) => {
        this.formRow[3].elCol[0].options.push({
          label: item.column_content,
          id: item.column_value
        })
      })
    },
    // 复制-获取表单数据
    async initCopyFormData() {
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "getCopyApp"
      }, { id: this.$route.query.id })
      this.ruleForm = res.attribute
      this.ruleForm.accessMode = JSON.parse(res.attribute.accessMode)
      this.appStatus = res.attribute.appStatus
    },
    async initEditFormData() {
      const res = await getApiModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "getApp"
      }, { id: this.$route.query.id })
      this.ruleForm = res.attribute
      this.ruleForm.accessMode = JSON.parse(res.attribute.accessMode)
      this.appStatus = res.attribute.appStatus
    },
    //下载logo
    getLogoUrl() {
      let id = this.appLogo ? this.appLogo : this.$route.query.appLogo
      return request({
        url: "/kangarooDataCenterV3/entranceController/fileDownloadNew?id=" + id,
        method: "get",
        responseType: 'arraybuffer'
      }).then((res) => {
        this.imgUrl =
          "data:image/png/jpg;base64," + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ""));
      })
    }

  },
  components: {
    baseNewForm,
  },
  created() {
    // 请求下拉options
    this.initSelectOptions()
    // 判断是什么类型进来的
    if (this.$route.query.flag === "setting") {
      this.formRow[0].elCol[0].disabled = false;
    } else {
      this.formRow[0].elCol[0].disabled = false;
    }
    if (this.$route.query.flag === "copy") {
      this.initCopyFormData()
      this.getLogoUrl()
    } else if (this.$route.query.flag === "setting") {
      this.initEditFormData()
      this.getLogoUrl()
    }
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-button {
  border-radius: 16px;
}
::v-deep .el-form-item {
  display: block !important;
}
.wrap {
  background-color: #fbfbfb;
  width: 100%;
  overflow: auto;
  > .btn {
    display: flex;
    justify-content: flex-end;
    > .chunk {
      margin-left: 10px;
    }
  }
  > .main {
    margin-top: 10px;
    > .upload {
      background-color: #fff;
      border-radius: 16px;
      padding: 24px 30px;
      > .title {
        font-size: 18px;
        font-weight: 600;
      }
      > .uploadMain {
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        > .left {
          > .title {
            font-size: 18px;
            color: #999999;
            margin-bottom: 10px;
          }
          .line {
            display: flex;
            align-items: center;
            .left {
              border: 1px dashed #999999;
              width: 64px;
              height: 64px;
              display: flex;
              justify-content: center;
              align-items: center;
              > img {
                width: 100%;
                // height: 100%;
              }
            }
            .right {
              margin-left: 15px;
            }
          }
        }
      }
    }
    > .form {
      overflow: auto;
      margin-top: 10px;
      background-color: #fff;
      border-radius: 16px;
      width: 100%;
      padding: 10px 20px;
    }
  }
}
</style>
