<template>
  <div class="app-container" v-loading="loading">
    <div style="margin: auto">
      <p><span class="tipH4">商品主图</span><span class="tipText"><i class="el-icon-question tipIcon"></i>要求上传高清图片，大小在2M以内，支持png、jpg格式，尺寸要求为正方形。</span>
      </p>
      <el-upload
        class="uploadData"
        action="#"
        list-type="picture-card"
        :file-list="ruleFormdialogImageUrlplus"
        :http-request="uploadGoodsMain"
        :limit="1"
        :on-exceed="limitCount1"
        :before-upload = "beforeUpGoodsMainImg"
        :before-remove = "beforeRemoveMainImg"
        :on-remove="removeMainImg"
        :on-preview="handleMainImgPreview"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisibleplus">
        <img width="100%" :src="dialogImageUrlplus" alt=""/>
      </el-dialog>
    </div>
    <div>
      <p><span class="tipH4">商品轮播图</span><span class="tipText"><i class="el-icon-question tipIcon"></i>要求上传高清图片，大小在2M以内，支持png、jpg格式，尺寸要求为正方形。</span>
      </p>
      <el-upload
        class="uploadData"
        action="#"
        list-type="picture-card"
        :file-list="ruleFormdialogImageUrl"
        :http-request="uploadSectionFile"
        :limit="5"
        :on-exceed="limitCount5"
        :before-upload = "beforeUpCarouselImg"
        :before-remove="beforeRemoveCarouselImg"
        :on-remove="removeCarouseImg"
        :on-preview="handlePictureCardPreview"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt=""/>
      </el-dialog>
    </div>
    <div>
      <el-button style="margin: 20px 0;" @click="resetGoodsImgForm">重置</el-button>
    </div>
  </div>
</template>

<script>
  import {UploadImg} from '@/api/module/goods'

  export default {
    name: "goodsimg",
    props: {
      imgdata: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        loading: false, // 全屏加载
        picall: {
          ruleFormdialogImageUrl: [],
          ruleFormdialogImageUrlplus: [],  //主图
        },
        ruleFormdialogImageUrl: [],     //多图
        dialogImageUrl: "",
        dialogVisible: false,
        ruleFormdialogImageUrlplus: [],  //主图
        dialogImageUrlplus: "",
        dialogVisibleplus: false,
      };
    },
    components: {},
    mounted() {
    },
    watch: {
      imgdata(curVal, oldVal) {
        console.log(84,curVal);
        if (curVal) {
          if(curVal.ruleFormdialogImageUrl) {
            curVal.ruleFormdialogImageUrl.forEach((itemName, nindex) => {
              this.ruleFormdialogImageUrl.push({'url': itemName.thumbnailM})
            })
          }
          if(this.ruleFormdialogImageUrlplus) {
            this.ruleFormdialogImageUrlplus.push({'url': curVal.ruleFormdialogImageUrlplus});
          }
        }
      },
      picall: {
        handler(val, oldVal) {
          this.$emit('imgclicks', val)
        },
        deep: true
      },
      ruleFormdialogImageUrl: {
        handler(val, oldVal) {
          this.$set(this.picall, 'ruleFormdialogImageUrl', val)
        },
        deep: true
      },
      ruleFormdialogImageUrlplus: {
        handler(val, oldVal) {
          this.$set(this.picall, 'ruleFormdialogImageUrlplus', val)
        },
        deep: true
      },
    },
    methods: {
      // 商品主图 数量限制
      limitCount1(files,fileList){
        this.$message({message: '最多上传1张图片', type: 'warning'});
      },
      // 商品主图 大小格式样式校验
      beforeUpGoodsMainImg(file,fileList){
        if(file.type !== "image/png" && file.type !== "image/jpg" && file.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持png/png格式',
            type: "warning"
          });
          return false;
        }
        let isImgSize = (file.size / 1024 / 1024 ) > 2;
        if(isImgSize) {
          this.$message({
            message: '上传图片大小不能超过2MB',
            type: "warning"
          });
          return false;
        }
        // 图片宽高尺寸限制
        return new Promise(function(resolve, reject){
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function(){
            // 图片是否是正方形 宽高比为 1
            let valid = img.width / img.height === 1;
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(()=>{
          return file;
        }, ()=>{
          this.$message({
            message:'商品主图必须为正方形，请重新选择!',
            type: 'warning'
          });
          return Promise.reject();
        });
      },

      // 上传商品主图
      uploadGoodsMain(param) {
        this.loading = true;
        this.getBase64(param.file).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"image": this.Base64img}
          UploadImg(data).then(res => {
            this.loading = false;
            if (res && res.data.code == 1) {
              this.ruleFormdialogImageUrlplus.push({'url': res.data.data.imageUrl})
              this.$message({ message:'上传成功',type:'success'});
            }else {
              this.ruleFormdialogImageUrlplus = [];
              this.$message({ message:'上传失败，请重新上传',type:'error'});
            }
          })
        });
      },

      // 商品主图 删除移除前
      beforeRemoveMainImg(file,fileList) {
        if(file.status === "success") {
          return new Promise((res, rej) => {
            this.$confirm(`是否删除此图片`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return res();
            }).catch(() => {
              this.$message({
                type: 'success',
                message: '取消删除!'
              });
              return rej();
            });
          });
        }
      },
      // 主图删除
      removeMainImg(file) {
        if(file.status === "success") {
          for(let i = 0; i < this.ruleFormdialogImageUrlplus.length; i++) {
            if(file.uid === this.ruleFormdialogImageUrlplus[i].uid) {
              this.ruleFormdialogImageUrlplus.splice(i,1);
            }
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      },

      // 商品主图 预览
      handleMainImgPreview(file) {
        this.dialogImageUrlplus = file.url;
        this.dialogVisibleplus = true;
      },

      // 轮播图 数量限制
      limitCount5(files,fileList){
        this.$message({message: '最多上传5张图片', type: 'warning'});
      },
      // 轮播图 大小格式样式校验
      beforeUpCarouselImg(file) {
        if(file.type !== "image/png" && file.type !== "image/jpg" && file.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持png/png格式',
            type: "warning"
          });
          return false;
        }

        let isImgSize = (file.size / 1024 / 1024 ) > 2;
        if(isImgSize) {
          this.$message({
            message: '上传图片大小不能超过2MB',
            type: "warning"
          });
          return false;
        }

        // 图片宽高尺寸限制
        return new Promise(function(resolve, reject){
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function(){
            // 图片是否是正方形 宽高比为 1
            let valid = img.width / img.height === 1;
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(()=>{
          return file;
        }, ()=>{
          this.$message({
            message:'轮播图图必须为正方形，请重新选择!',
            type: 'warning'
          });
          return Promise.reject();
        });
      },

      // 轮播图上传
      uploadSectionFile(param) {
        this.loading = true;
        this.getBase64(param.file).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"image": this.Base64img}
          UploadImg(data).then(res => {
            if (res && res.data.code == 1) {
              this.ruleFormdialogImageUrl.push({'url': res.data.data.imageUrl});
              this.$message({ message:'上传成功',type:'success'});
            }else {
              this.$message({ message:'上传失败，请重新上传',type:'error'});
            }
            this.loading = false;
          })
        });
      },

      // 轮播图 删除前
      beforeRemoveCarouselImg(file,fileList) {
        if(file.status === "success") {
          return new Promise((res, rej) => {
            this.$confirm(`是否删除此图片`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return res();
            }).catch(() => {
              this.$message({
                type: 'success',
                message: '取消删除!'
              });
              return rej();
            });
          });
        }
      },
      // 商品轮播图删除
      removeCarouseImg(file){
        if(file.status === "success") {
          for(let i = 0; i < this.ruleFormdialogImageUrl.length; i++) {
            if(file.uid === this.ruleFormdialogImageUrl[i].uid) {
              this.ruleFormdialogImageUrl.splice(i,1);
            }
          }

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      },
      // 轮播图预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      handleinfomationclick() {
        let pic = {
          ruleFormdialogImageUrlplus: this.ruleFormdialogImageUrlplus,
          ruleFormdialogImageUrl: this.ruleFormdialogImageUrl
        }

        this.$emit('imgclicks', pic)
      },
      // 重置
      resetGoodsImgForm() {
        this.ruleFormdialogImageUrl = [];
        this.ruleFormdialogImageUrlplus = [];
      },
      // -------------------------通用
      // 图片转换为 base64
      getBase64(file) {
        return new Promise(function (resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function () {
            imgResult = reader.result;
          };
          reader.onerror = function (error) {
            reject(error);
          };
          reader.onloadend = function () {
            resolve(imgResult);
          };
        });
      },
    },
  };
</script>
<style lang="scss" type="text/stylus" scoped>
  ul,
  li {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .tipH4{
    font-size: 18px;
    font-weight : 600;
  }
  .tipText {
    font-size : 14px;
    color: #c9c9c9;
  }
  .tipIcon {
    color: #e3c300;
    font-size:16px;
    padding: 0 8px;
  }

  .ullist {
    border: 1px solid #e7eaec;
    padding: 10px;
    margin-bottom: 10px;
  }

  .el-input-group {
    width: calc(100% - 60px);
  }
  // 上传图片样式重置 start
  .uploadData {
    display: inline-block;
    /deep/ .el-upload--picture-card {
      width: 100px;
      height: 100px;
    }

    /deep/ .el-upload {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/ .el-upload-list--picture-card .el-upload-list__item {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/ .avatar {
      width: 100px;
      height: 100px;
    }
  }
  // 上传图片样式 重置 end

  /deep/.el-upload-list__item .el-icon-close-tip {
    display :none!important;
  }
</style>
