<template>
  <div>
        <div class="wrap">
          <div class="tip" v-show="showTip">
            <i class="el-icon-close close" @click="showTip= !showTip"></i>
            <p>
              <i class="el-icon-question"></i>操作提示
            </p>
            <p>1、首页banner图最多添加上限为3张</p>
            <!-- <p v-if="isPc">2、图片大小为1920*480px，大小不得超过2M</p> -->
            <p>2、图片大小为{{uploadWH[0]}}*{{uploadWH[1]}}，大小不得超过{{uploadSize}}M</p>
          </div>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="序号" width="80">
              <template slot-scope="scope">
                <p>{{scope.$index+1}}</p>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="banner名称" width="250">
              <template slot-scope="scope">
                <div>
                  <el-input v-model="scope.row.name" placeholder="请输入内容"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="banner展示" width="160">
              <template slot-scope="scope">
                <div v-if="scope.row.path">
                  <div class="updateShowImg">
                      <div class="imgBox">
                        <img :src="scope.row.path" class="preview imageLen" alt />
                      </div>
                      <div class="btnBox">
                        <span
                          class="editdelBtn el-icon-zoom-in"
                          @click="handlePictureCardPreview(scope.row.path)"
                        ></span>
                        <span @click="onUploadIndex(scope.$index)">
                          <el-upload
                            class="avatar-uploader-edit"
                            :action="uploadData.host|| ''"
                            :data="uploadData"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeUpload"
                      
                          >
                            <i
                              class="editdelBtn el-icon-refresh"
                            ></i>
                          </el-upload>
                        </span>
                      </div>
                      <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                      </el-dialog>
                    </div>
                </div>
                <div @click="onUploadIndex(scope.$index)" v-else>
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadData.host|| ''"
                    :data="uploadData"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeUpload"
              
                  >
                    <img v-if="scope.row.path" :src="scope.row.path" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="链接跳转">
              <template slot-scope="scope">
                <span v-if="scope.row.productNum">
                  已选中商品：{{scope.row.productNum}}
                </span>
                <el-button style="margin-left:20px" @click="selectProduct(scope.$index,scope.row)">{{scope.row.productNum?'更换商品':'选择商品'}}</el-button>
                <!-- <div style="display: flex;min-width:220px">
                  <el-input
                    v-model="scope.row.url"
                    style="flex:6;width:120px;margin-left: 4px;"
                    placeholder="请输入内容"
                  ></el-input>
                </div> -->
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="120">
              <template slot-scope="scope">
                <div class="caozuo">
                  <i
                    v-show="scope.$index!=tableData.length-1"
                    class="el-icon-arrow-down"
                    @click="down(scope.$index)"
                  ></i>
                  <i v-show="scope.$index!=0" class="el-icon-arrow-up" @click="up(scope.$index)"></i>
                  <i class="el-icon-close" @click="del(scope.$index)"></i>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <p class="add" @click="add" v-show="tableData.length<3">
            <i class="el-icon-plus"></i>继续添加
          </p>
        </div>
        
        <!-- 弹框 -->
        <sel-pro-dialog
          :dialogVisiblePro="proBoxVisible"
          :title="'选择链接商品'"
          @changeDia="changeDialogV"
          :ids="checkIds"
          :list="checkList"
          :max="0"
          :min="0"
          :isMultiple="false"
          ref="proBox"
          ></sel-pro-dialog>
  </div>
</template>

<script>
import { _getStorage, _getOssToken, _uuid } from "@/utils/utils";
import FileVerification from "@/utils/FileVerification"
import selProDialog from "./selectProductMultipleDialog"
export default {
  props: {
    bannerList:{
      type:Array,
      default:function(){
        return []
      }
    },
    // isPc: {
    //   type: Boolean,
    //   default: true
    // },
    isVipBrand:{
      type:Boolean,
      default:true
    },
    uploadWH:{
      type:Array,
      default:()=>{ return []} //图片宽度+高度
    },
    uploadSize:{
      type:Number,
      default:100 //上传文件大小,单位mb
    },
  },
  data() {
    return {
      dialogVisible:false,
      dialogImageUrl:'',
      tableData:[],
      input: "",
      isUpload: false,
      uploadIndex: -1,
      uploadData: {},
      input: "",
      showTip: true,
      value: "",
      activeName: "1",
      // 商品跳转
      proBoxVisible:false,
      checkIds:[],
      checkList:[],
      activeCategory:-1
    };
  },
  components: {
    selProDialog
  },
  watch: {
    bannerList (newName, oldName) {
      this.tableData=this.bannerList;
    },
  },
  mounted() {
  },
  methods: {
    selectProduct(index,row) {
      this.activeCategory = index;
      this.checkIds=[row.productId];

      var obj={
        productId:row.productId,
        productNum:row.productNum
      }

      this.checkList=[obj];
      this.proBoxVisible = true;
    },
    changeDialogV(e,ids,list){
      this.proBoxVisible =e;
      var i=Number(this.activeCategory);
      if(ids){
        this.tableData[i].productId=ids[0];
      }
      if(list){
        this.tableData[i].productNum=list[0].productNum;
      }
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      this.tableData[this.uploadIndex]["path"] =
        this.uploadData.host + "/" + this.uploadData.key;
      this.isUpload = false;
    },
    onUploadIndex(index) {
      this.uploadIndex = index;
    },
    beforeUpload(file) {

      // 文件上传
      return new Promise((resolve, reject) => {

        // 校验上传文件属性
        this.beforeUploadCheck(file).then(res => {
          if(!res){
            this.$notify.error(
              "请按要求上传文件"
            );
            this.beforeUploadErr()
            reject();
          }else if (typeof(res) == 'object' && !res.result) {
            let err = res.h?res.w + "*" + res.h:res.w
            this.beforeUploadErr()
            if(res.msg){
                this.$notify.error(res.msg);
            }else{
              this.$notify.error(
                "请上传" + err + "像素的图片格式文件"
              );
            }
            reject();
          }else{
           _getOssToken.call(this, null).then(res => {
              var fileExt = /\.[^\.]+$/.exec(file.name);
              this.uploadData = res;
              this.uploadData.key = "ewy/resource/image/" + _uuid() + fileExt;

              resolve();
            })
            .catch(err => {
              this.isUpload = false;

              reject(err);
            });
          }
        });

      })
    },
    // beforeAvatarUpload(file,label) {
    //   // console.log(file,label);
    //   if (this.isUpload) {
    //     this.$message.error("正在上传，请稍后");
    //     return false;
    //   }
    //   this.isUpload = true;
    //   const isLt1M = file.size / 1024 / 1024 < 1;
    //   const isLt3M = file.size / 1024 / 1024 < 3;
    //   if (file.type.indexOf("image/") == -1) {
    //     this.$message.error("请上传图片格式文件");
    //     this.isUpload = false;
    //     return false;
    //   }
    //   if(this.isPc){
    //     if (!isLt3M) {
    //       this.$message.error("上传图片大小不能超过 3MB!");
    //       this.isUpload = false;
    //       return false;
    //     }
    //   }else{
    //     if (!isLt1M) {
    //       this.$message.error("上传图片大小不能超过 1MB!");
    //       this.isUpload = false;
    //       return false;
    //     }
    //   }
   
    //   return new Promise((resolve, reject) => {
  
    //         _getOssToken.call(this, null).then(res => {
    //             var fileExt = /\.[^\.]+$/.exec(file.name);
    //             this.uploadData = res;
    //             this.uploadData.key = "ewy/resource/image/" + _uuid() + fileExt;

    //             resolve();
    //           })
    //           .catch(err => {
    //             this.isUpload = false;

    //             reject(err);
    //           });

        
    //   });
    // },
      beforeUploadErr(){
        // this.$refs.bannerImgs.clearFiles()
        this.uploadData.keys = []
        this.uploadData.successNum = 0
        this.uploadData.beforeNum = 0
    },
    beforeUploadCheck(file){
      let self = this
      const fv = new FileVerification(file);
      let rules;
   
      if(this.uploadWH && this.uploadWH.length){
         if(this.uploadWH.length==1){
          //[00]只传一个默认设置宽度vImgW
            rules = {
                vSize:this.uploadSize * 1024,
                vImgW:this.uploadWH
            }
         }else{
            rules = {
                vSize:this.uploadSize * 1024,
                vImgWH:this.uploadWH
            }
         }
      }else{
        rules = {
            vSize:this.uploadSize * 1024
        }
      }
      async function getResult(rule){
        let res = true
        for(let i in rule){
          let val = rule[i]
          if(['vImgPercentage','vImgWH','vImgW','vImgH'].indexOf(i) != -1){
            let r = await fv[i](val[0],val[1])
            res = r
          }else{
            res = fv[i](val)
          }
          //只要有一个条件不满足就弹出
          if(res && !res.result){
            return res
          }
        }
        return res
      }

      return getResult(rules)

    },
    up(index) {
      this.tableData.splice(
        index - 1,
        1,
        ...this.tableData.splice(index, 1, this.tableData[index - 1])
      );
    },
    down(index) {
      this.tableData.splice(
        index + 1,
        1,
        ...this.tableData.splice(index, 1, this.tableData[index + 1])
      );
    },
    gotoVip(){
       const h = this.$createElement;
          this.$msgbox({
            message: h('p', { style: 'padding:40px 0' }, [
              h('span', null, "您当前不是铂金品牌，无法进行当前操作，请前往升级" ),
            ]),
            showCancelButton: true,
            center:true,
            confirmButtonText: '前往升级',
            cancelButtonText: '我知道了',
                      showConfirmButton:false, //先隐藏掉升级按钮
          }).then(action => {
              this.$router.push('/vippay');
          }).catch(() => {
          });
    },
    del(index) {
      this.tableData.splice(index, 1);
    },
    add() {
      if(!this.isVipBrand){
        this.gotoVip();
        return false
      }
      this.tableData.push({
        name: "",
        path: "",
        url:"",
        productNum:"",
        num: this.tableData.length
      });
    },
    onSave() {
      this.tableData.map((item, index) => {
        item.num = index + 1;
      });
      this.$axios.post("/resource/saveSupBanner", this.tableData).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.$message({
            type: "success",
            message: msg
          });
        } else {
          this.$message.error(msg);
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
img{
    max-width: 100%;
    max-height: 100%;
}
.wrap {
  .updateShowImg{
    width: 148px;
    height: 86px;
    position: relative;
    border: 1px dashed #d9d9d9;
    text-align: center;
    .imgBox{
      position: relative;
      display: block;
      width: 100%;
      height: 100%;
      /* margin-bottom: 10px; */
    }
    .btnBox{
      position: absolute;
      bottom: 0;
      /* right: 10px; */
      z-index: 1;
      display: none;
      background: rgba(0,0,0,0.4);
      border-radius: 4px;
      padding: 4px 2px 2px;
      width: 148px;
      text-align: center;
    }
    .avatar-uploader-edit {
      display: inline-block;
    }
    .avatar-uploader-edit >>> .el-upload--text {
      width: 29px;
      height: 26px;
      background: inherit;
      border: none;
    }
    .editdelBtn {
      display: inline-block;
      cursor: pointer;
      color: #fff;
      font-size: 18px;
    }
  }
  .updateShowImg:hover .btnBox {
    display: block;
  }
  .tip {
    position: relative;
    background: #f7f5f6;
    padding: 15px;
    color: #525051;
    line-height: 19px;
    font-size: 14px;
    .el-icon-question {
      color: #ff6600;
      font-size: 16px;
    }
    .close {
      position: absolute;
      right: 15px;
      top: 15px;
      cursor: pointer;
    }
  }
  .caozuo {
    font-size: 16px;
    font-weight: bold;
    i {
      cursor: pointer;
      &:hover {
        color: #ff6600;
      }
    }
  }
  .add {
    text-align: center;
    padding: 8px 0;
    border: 1px dotted #b4b4b4;
    font-size: 14px;
    color: #313131;
    margin-top: 10px;
    cursor: pointer;
    &:hover {
      color: #ff6600;
    }
  }
  .btns {
    margin-top: 20px;
    // margin-left: 180px;
  }
}
/deep/ .el-upload--text {
  width: 148px;
  height: 86px;
  padding: 5px;
  border: 1px dashed #d9d9d9;
}
.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: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: contain;
}
</style>