<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: '/integrationOption/masterDataOptions' })
          ">返回
        </el-button>
      </div>
      <div class="chunk">
        <el-button icon="el-icon-first-aid-kit" type="primary" @click="saveHandle" :loading="saveLoading">保存
        </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" v-loading="imgLoading">
                  <img v-if="imgUrl" :src="imgUrl" class="avatar">
                  <img v-else src="./images/icon.png" alt="">
                </div>
                <div class="right" v-if="!lookFlag">
                  <el-button size="small" type="primary" :loading="loading">点击上传</el-button>
                </div>
              </div>
              <div slot="tip" class="el-upload__tip" v-if="!lookFlag">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </el-upload>
          </div>
          <div class="right">

          </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 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: "",
      ruleForm: {
        accessMode: [],
      },
      lookFlag: false,
      formRow: configData.addForm,
      imgLoading: false,
      saveLoading: false,
    };
  },
  methods: {
    // 文件上传相关时间
    handleProgress(file, fileList) {
      this.loading = true
      this.handleAvatarSuccess({}, fileList).then(res => {
        this.loading = false
      })
    },
    handlePreview(file) {
    },
    async handleAvatarSuccess(res, file) {
      this.loading = true
      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");
      return request({
        url: "/kangarooDataCenter/entranceController/fileUpload",
        method: "post",
        data: formData,
      }).then((res) => {

        if (res.status === '200') {
          console.log(res)
          this.$vmNews("上传成功", "success")
          this.appLogo = res.attribute.id
        }
      })
      return true

    },
    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
        }
      }
    },
    // 保存按钮、列表验证
    saveHandle() {
      this.$refs.mainForm.submitForm();

    },
    //验证成功准备上传
    async onSubmit() {
      this.saveLoading = true
      if (this.$route.query.flag === "add") {
        const res = await getApiModuleApi({
          tl: "mdmService",
          as: "mdmService",
          dj: "doSaveMdmModule"
        }, {...this.ruleForm, mdmLogo: this.appLogo})
        if (res.status === '200') {
          this.$vmNews("保存成功", "success")
          this.saveLoading = false
          this.$router.replace({path: '/integrationOption/masterDataOptions'})
        }
      } else if (this.$route.query.flag === "setting") {
        const res = await getApiModuleApi({
          tl: "mdmService",
          as: "mdmService",
          dj: "doSaveMdmModule"
        }, {updateType: 1, ...this.ruleForm, mdmLogo: this.appLogo})
        if (res.status === '200') {
          this.$vmNews("保存成功", "success")
          this.initEditFormData()
          this.getLogoUrl()
          this.saveLoading = false
          this.$emit("saveSuccess")
        }
      }
    },
    // 获取下拉数据
    async initSelectOptions() {
      let params = {
        tab_name: "mdm",
        column_name: "mdm_type",
      };
      const res = await getApiModuleApi({
        tl: "generalServiceImpl",
        as: "dictionaryshop",
        dj: "selectDictionaryshop"
      }, params)
      this.formRow[1].elCol[0].options = []
      res.attribute.forEach((item) => {
        this.formRow[1].elCol[0].options.push({
          label: item.column_content,
          id: item.column_value
        })
      })
      console.log(this.formRow[1].elCol[0].options)
    },
    // 复制-获取表单数据
    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)
    },
    async initEditFormData() {
      const res = await getApiModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmModule"
      }, {id: this.$route.query.id})
      this.ruleForm = res.attribute
      if (res.attribute.mdmLogo) {
        this.appLogo = res.attribute.mdmLogo
        this.getLogoUrl()
      } else {
        // this.imgUrl = false
      }
    },
    //下载logo
    getLogoUrl() {
      this.imgLoading = true
      let id = this.appLogo ? this.appLogo : this.$route.query.appLogo
      return request({
        url: "/kangarooDataCenter/entranceController/fileDownloadNew?id=" + id,
        method: "get",
        responseType: 'arraybuffer'
      }).then((res) => {
        this.imgLoading = false
        if (!res.byteLength) {
          this.imgUrl = false
          return
        }
        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 = [
        {
          elCol: [
            {
              type: "input",
              title: "主数据名称",
              id: "mdmName",
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16
            },
          ],
        },
        {
          elCol: [
            {
              type: "select",
              title: "主数据类型",
              id: "mdmType",
              row: 24,
              disabled: false,
              required: true,
              options: [],
              fontSize: 16,
            },
          ],
        },
        {
          elCol: [
            {
              type: "input",
              title: "服务名",
              id: "mdmCode",
              row: 24,
              disabled: true,
              required: false,
              fontSize: 16,
              placeholder: "编辑时自动带出"
            },
          ],
        },
        {
          elCol: [
            {
              type: "textrea",
              title: "备注",
              id: "remark",
              row: 24,
              disabled: false,
              fontSize: 16

            },
          ],
        },
      ]
    } else {

    }
    if (this.$route.query.flag === "copy") {
      this.initCopyFormData()
    } else if (this.$route.query.flag === "setting") {
      this.initEditFormData()
    }
  },
};
</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;

              > 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>
