<template>
  <el-dialog :title="brand.BrandID?'品牌修改':'添加品牌'" :visible.sync="outerVisible" class="add-brand" width="600px">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="top" class="reset-form">
      <el-form-item label="中文名称：" prop="BrandCname">
        <el-input v-model.trim="ruleForm.BrandCname" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="英文名称：">
        <el-input v-model.trim="ruleForm.BrandName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="品牌LOGO：">
        <div class="logo">
          <el-upload style="flex: 1;" class="avatar-uploader" action="#" :http-request="uploadAndSubmit"
            :show-file-list="false" :before-upload="beforeAvatarUpload">
            <i v-if="ruleForm.BrandLogo" class="el-icon-error delete-image" @click.stop="handleClickDelImg"></i>
            <img v-if="ruleForm.BrandLogo" :src="`/image-service/common/image_get?systemId=dataPlatform&key=${ruleForm.BrandLogo}`" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span class="imgTip">支持格式GIF、JPG、JPEG、PNG，文件80K以内，建议尺寸80PX*80PX</span>
        </div>

      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="brand.BrandID" @click="innerVisible = true" type="text" style="padding-right: 10px;color: #646C73">删除品牌</el-button>
      <el-button @click="outerVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">{{brand.BrandID?'保 存':'添 加'}}</el-button>
    </div>

    <el-dialog width="420px" title="确定要删除该品牌吗？" :visible.sync="innerVisible" :show-close="false" class="child-dialog"
      append-to-body>
      <div slot="title" class="header-title">
        <span class="el-icon-info" style="font-size: 24px;color: #F54E45;margin-right: 10px"> </span>
        <span class="del-text">确定要删除该品牌吗？</span>
        <p class="del-tip">删除后该品牌的所有信息将被删除，不可恢复</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleClickDelete">删除</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { brandCreate, brandDelete, brandUpdate } from "@/api/brand"
export default {
  name: "addBrand",
  props: {
    brand: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      outerVisible: false,
      innerVisible: false,
      ruleForm: {
        BrandCname: '',
        BrandName: '',
        BrandLogo: '',
      },
      rules: {
        BrandCname: [{ required: true, message: '请输入中文名称', trigger: 'blur' }],
      },
      key: "",
    }
  },
  methods: {
    uploadAndSubmit(item) {// 上传图片
      let file = item.file
      let _this = this
      //获取文件后缀名
      let fileType = file.name.split('.')
      let type = fileType[fileType.length -1]
      this.key = `${file.uid}.${type}`

      let reader = new FileReader();
      reader.onloadend = function () {
        // 这个事件在读取结束后，无论成功或者失败都会触发
        if (reader.error) {
        } else {
          var xhr = new XMLHttpRequest();
          xhr.open(
            "POST",
            `/image-service/common/image_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&overwrite=true&key=${_this.key}`
          );
          xhr.send(reader.result);
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                _this.ruleForm.BrandLogo = _this.key
              }
            }
          };
        }
      };
      reader.readAsArrayBuffer(file);
    },
    beforeAvatarUpload(file) {
      const typeList = ['image/jpeg','image/png','image/gif']
      const isType = typeList.some(item => {return item === file.type});
      const isLt80K = file.size / 1024 <= 80;
      if (!isType) {
        this.$message.error('上传头像图片格式不支持!')
        return false
      }
      if (!isLt80K) {
        this.$message.error('上传头像图片大小不能超过 80K!')
        return false
      }
      return isType && isLt80K;
    },
    handleClickDelImg() {
      this.ruleForm.BrandLogo = ""
    },
    submitForm(formName) { //(添加/修改)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            Content: [{
              BrandCname: this.ruleForm.BrandCname,
              BrandName: this.ruleForm.BrandName,
              BrandLogo: this.ruleForm.BrandLogo,
            }]
          }
          if (this.brand.BrandID) { //修改品牌
            params.Content[0].BrandID = this.brand.BrandID
            brandUpdate(params, res => {
              this.outerVisible = false
              this.$emit("refresh")
              this.$message.success('保存成功！')
            })
          } else { //添加品牌
            brandCreate(params, res => {
              this.outerVisible = false
              this.ruleForm = { BrandCname: '', BrandName: '', BrandLogo: '' }
              this.$emit("refresh",res.EntityList)
              this.$message.success('添加成功！')
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      });
    },
    handleClickDelete() { //删除品牌
      brandDelete([{BrandID: this.brand.BrandID}], res => {
        this.innerVisible = false
        this.outerVisible = false
        this.$emit("refresh")
        this.$message.success('删除成功！')
      })
    },
  },
  watch: {
    outerVisible: {
      handler(newName, oldName) {
        if (this.brand.BrandID && newName) {
          this.ruleForm.BrandCname = this.brand.BrandCname
          this.ruleForm.BrandName = this.brand.BrandName || ''
          this.ruleForm.BrandLogo = this.brand.BrandLogo || ''
        } else if (!newName && this.brand.BrandID) {
          this.ruleForm = { BrandCname: '', BrandName: '', BrandLogo: '' }
        }
      },
      immediate: true,
    }
  }
}
</script>

<style scoped lang="less">
.add-brand {
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #e4e5e7;
  }
  .reset-form {
    width: 320px;
    margin: 0 auto;

    .logo {
      display: flex;
      .imgTip {
        font-size: 12px;
        color: #c3c7cb;
        line-height: 18px;
        margin-left: 8px;
        margin-bottom: 78px;
      }
      .delete-image {
        color: rgba(31,36,41,0.5);
        position:absolute;
        top:5px;
        right:5px;
      }
      .delete-image:hover {
        color: #F56C6C;
      }
    }
  }
}

.child-dialog {
  /deep/ .el-dialog__body {
    padding: 0;
  }
}

.header-title {
  .del-text {
    color: #1f2329;
    font-size: 16px;
    font-weight: 500;
    display: inline-block;
  }

  .del-tip {
    margin-left: 39px;
    color: #646a73;
  }
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 112px;
  height: 112px;
  line-height: 112px !important;
  text-align: center;
}

.avatar {
  width: 112px;
  height: 112px;
  display: block;
}
</style>
