<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 22023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\team\teamMr\AddOrEditDialog.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-form :model="form" ref="form" :rules="rules" label-width="150px">
        <!-- <el-form-item label="授信余额:" prop="grantSurplus">
          <span>{{ form.grantSurplus }}元</span>
        </el-form-item> -->
        <el-form-item label="授信欠款:" prop="grantUsed">
          <span>{{ form.grantUsed }}元</span>
        </el-form-item>
        <el-form-item label="还款金额:" prop="balanceValue">
          <div style="display: flex;">
            <el-input-number v-model="form.balanceValue" controls-position="right" placeholder="请输入还款金额"></el-input-number>
            <span>元</span> 
          </div>
        </el-form-item>
        <el-form-item label="还款凭证" prop="voucherUrl">
            <div style="display: flex;">
              <div 
              v-for="(item,index) in form.voucherUrl" 
              :key="index"
              style="width: 100px; height: 100px;position: relative;border: 1px solid #999;border-radius: 5px;margin-right: 20px;">
                <el-image 
                  style="width: 100%; height: 100%"
                  :src="item" 
                  :preview-src-list="form.voucherUrl">
                </el-image>
                <span @click="handleRemove(index)" style="position: absolute;top: -15px;right: -15px;color: red;font-size: 24px;z-index: 999;cursor: pointer;">
                  <i class="el-icon-error"></i>
                </span>
              </div>
              <div 
              style="width: 100px; height: 100px;" 
              v-if="!form.voucherUrl||form.voucherUrl.length<1"
              v-loading="actionUrlLoading"
              element-loading-text="上传中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              >
                <el-upload
                  class="avatar-uploader"
                  :action="uploadObj.url"
                  :headers="uploadObj.headers"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :on-progress="handleAvatarProgress"
                  :disabled="actionUrlLoading"
                  :on-error="handleAvatarError"
                  >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
              
            </div>
            <span><span>支持jpg、png的图片上传</span></span>
          </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-loading.fullscreen.lock="loading"
        element-loading-text="提交中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
// import { updateNoticeMgr } from "@/api/system/noticeMgr";
import { creditGrantingBoxApi, getSelectById } from "@/api/team/teamMr";
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
export default {
  name: "addAndEdit",
  components: {
    Editor,
  },
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      activeName: '01',
      open: false,
      loading: false,
      form: {
        id: undefined,
        type: "",
      },
      rules: {
        balanceValue: [{ required: true, message: "请输入还款金额", trigger: ["change","blur"] }],
        voucherUrl: [{ required: true, message: "请输入还款凭证图片", trigger: ["change","blur"] }],
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      actionUrlLoading: false,
    };
  },
  methods: {
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj) {
      this.open = true;
      this.title = title;
      this.reset();
      if (obj){
        this.getSelectByIdApi(obj);
      }else{
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /** 获取详情 */
    getSelectByIdApi(row) {
      const id = row.id
      getSelectById(id).then(response => {
        const obj = {
          ...response.data,
          voucherUrl: [],
        }
        this.form = obj
      });
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const { code } = await creditGrantingBoxApi({ 
              id: this.form.id,
              balanceValue: this.form.balanceValue,
              voucherUrl: this.form.voucherUrl ? this.form.voucherUrl.join(','):''
             });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      this.form = {}
      if(this.$refs["form"]) {
        this.$refs["form"].clearValidate();
      }
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
     /**  上传图片 单张  */
     handleAvatarSuccess(response, file, fileList) {
      console.log("res, file",response, file, fileList)
      this.actionUrlLoading = false
      if(response.code == 200) {
        this.form.voucherUrl.push(response.data.url)
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 100;
      let testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
      let typeList = ['png','jepg','jpg']
      const isJPG = typeList.includes(testmsg);
      if (!isJPG) {
        this.$message.error(`上传图片图片只能是 ${typeList} 格式!`);
      }
      if (!isLt2M) {
        this.$message.error('上传图片图片大小不能超过 100MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarProgress(){
      this.actionUrlLoading = true
    },
    handleAvatarError() {
      this.actionUrlLoading = false
    },
    handleRemove(index) {
      this.form.voucherUrl.splice(index,1)
    },

  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 65vh;
  overflow-y: auto;
}
.dialog {
  padding: 0 30px;
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  ::v-deep .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
