<template>
  <div style="display: inline-block; overflow: auto">
    <div>
      <div v-if="showFlagBtn">
        <el-radio v-model="mode" label="view">预览模式</el-radio>
        <el-radio v-model="mode" label="edit">编辑模式</el-radio>
      </div>

      <div style="border: 2px solid pink; display: inline-block;margin-right: 5px;" v-for="(item, index) in cardItemList" :key="item.cardItemId">
        <el-row :gutter="12" style="padding-top: 5px">
          <el-col :span="12">
            <el-card :body-style="{ padding: '0px' }">
              <div style="padding: 3px; text-align: center">
                <span>正面</span>
              </div>
              <el-image style="width: 100px; height: 100px;" v-if="mode=='view'" :src="resourcesUrl + item.frontPic" @click="previewPic(item, item.frontPic, item.prodName, 'front')"/>
              <el-upload v-else
                class="avatar-uploader"
                accept="image/jpg"
                :before-upload="(file, fileList)=>handleBeforeUpload(file, fileList,item)"
                :action="$http.adornUrl('/admin/file/simpleUpload')"
                :headers="{Authorization: $cookie.get('Authorization_vs'),locale:lang}"
                :on-success="(res,file)=>{onFrontUploadSuccess(item,res,file)}"
                :show-file-list="false">
                <img v-if="item.frontPic" :src="resourcesUrl + item.frontPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card :body-style="{ padding: '0px' }">
              <div style="padding: 3px; text-align: center">
                <span>背面</span>
              </div>
              <el-image v-if="mode=='view'" :src="resourcesUrl + item.backPic" style="width: 100px; height: 100px;" @click="previewPic(item, item.backPic, item.prodName, 'back')"/>
              <el-upload v-else
                         class="avatar-uploader"
                         :before-upload="(file, fileList)=>handleBeforeUpload(file, fileList,item)"
                         :action="$http.adornUrl('/admin/file/simpleUpload')"
                         :headers="{Authorization: $cookie.get('Authorization_vs'),locale:lang}"
                         :on-success="(res,file)=>{onBackUploadSuccess(item,res,file)}"
                         :show-file-list="false">
                <img v-if="item.backPic" :src="resourcesUrl + item.backPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-card>
          </el-col>
        </el-row>
        <el-row style="width: 210px; height: 30px; text-align: center ;color: red; font-weight: bold">
          <span v-if="showFlagBtn">
          <el-button v-if="item.flag==0 && mode=='view'" type="success" size="mini" style="margin-right: 20px" @click="handleFlag(item, index)">待标记</el-button>
          <el-button v-if="item.flag==1 && mode=='view'" type="warning" size="mini" style="margin-right: 5px" @click="handleFlag(item, index)">已标记</el-button>
          <el-button v-if="mode==='edit'" type="primary" size="mini" style="margin-right: 5px" @click="addOrUpdateCardItem(item)">保存</el-button>
          <el-button v-if="mode==='edit' && item.cardItemId" type="danger" size="mini" style="margin-right: 5px" @click="deleteCardItem(item, index)">删除</el-button>
        </span>
        </el-row>
        <el-row style="width: 210px; height: 30px; text-align: center ;color: red; font-weight: bold">
          <span>No.{{index + 1}}</span>
          <span v-if="showFlagBtn" style="color: white">
            __________
          </span>
          <span>X</span>
          <span v-if="mode=='view'">{{item.prodCount}}</span>
          <el-input type="number" size="mini" style="width: 60px;height: 20px" v-if="mode=='edit'" v-model="item.prodCount"></el-input>
        </el-row>
      </div>
      <div v-if="mode=='edit'" style="display: inline-block;">
        <el-button
          circle
          icon="el-icon-plus"
          @click="addCardItem">
        </el-button>
      </div>
    </div>
    <CanvasPreview v-if= "previewPicDialogVisible" ref="canvasPreviewRef"></CanvasPreview>
  </div>
</template>

<script>
  import CanvasPreview from "../canvas-preview/index";
  export default {
    components: {CanvasPreview},
    data () {
      return {
        lang: localStorage.getItem('lang') || 'zh_CN',
        cardItemList:[],
        previewPicUrl: null,
        prodType: null,
        previewPicDialogVisible: false,
        side:null,
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
        mode: 'view',
        previewWidth: 0,
        previewHeight: 0,
        bloodWidth: 0
      }
    },
    props: {
      orderItem: {
        default: null,
        type: Object
      },
      showFlagBtn:{
        default: true,
        type: Boolean
      }
    },
    created() {
      this.$nextTick(() => {
        this.getDataList();
      })
    },
    methods: {
      previewLoad(event){
        this.previewWidth = event.srcElement.clientWidth;
        this.previewHeight = event.srcElement.clientHeight;
      },
      handleBeforeUpload(file, fileList, item){
        let fileType = file.type;
        let isJpg = fileType === 'image/jpg' || fileType === 'image/jpeg';
        if(!isJpg){
          this.$message.error("只允许上传JPG格式的图片");
          return false;
        }
        let isSize = true;
        //如果当前是编辑的小卡，就需要判断是否符合尺寸
        let width = 709;
        let height = 1087;
        let prodName = item.prodName;
        isSize = new Promise(function(resolve, reject) {
          if(prodName.indexOf("小卡") !== -1 || prodName.indexOf("仿拍立得") !== -1){
            width = 709;
            height = 1087;
          }else if(prodName.indexOf("票根") !== -1){
            width = 780;
            height = 1489;
          }else if(prodName.indexOf("直拍封面") !== -1){
            width = 709;
            height = 1228;
          }else if(prodName.indexOf("明信片") !== -1){
            width = 1252;
            height = 1819;
          }else if(prodName.indexOf("三宫格") !== -1){
            width = 673;
            height = 1547;
          }else if(prodName.indexOf("流砂书签") !== -1){
            width = 638;
            height = 1819;
          }else if(prodName.indexOf("方卡") !== -1){
            width = 1217;
            height = 1217;
          }else if(prodName.indexOf("手幅") !== -1){
            width = 1252;
            height = 3614;
          }else if(prodName.indexOf("毛绒徽章") !== -1){
            width = 827;
            height = 827;
          }else if(prodName.indexOf("圆形徽章") !== -1){
            width = 850;
            height = 850;
          }else if(prodName.indexOf("手幅") !== -1){
            width = 1252;
            height = 3614;
          }else if(prodName.indexOf("方形贴纸") !== -1){
            width = 662;
            height = 662;
          }
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的图片宽高必须是" + width + "*" + height);
            return Promise.reject();
          }
        );
        return isJpg && isSize;
      },
      deleteCardItem(item, index){
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/prod/orderCardItem/' + item.cardItemId),
            method: 'delete',
          }).then(({ data }) =>{
            if(data){
              this.$delete(this.cardItemList, index);
              this.$message.success("删除成功");
            }else{
              this.$message.error("删除失败");
            }
          })
        });
      },
      addOrUpdateCardItem(item){
        this.$confirm('确定要更新吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.$http({
              url: this.$http.adornUrl('/prod/orderCardItem/saveOrUpdate'),
              method: 'post',
              data: this.$http.adornData(item)
            }).then(({ data }) =>{
              if(data){
                this.$set(item, 'cardItemId', data.cardItemId);
                this.$message.success("保存成功");
              }else{
                this.$message.error("保存失败");
              }
            })
        });
      },
      onFrontUploadSuccess (item, response, file) {
        this.$set(item,'frontPic',response.filePath);
        this.$forceUpdate()
      },
      onBackUploadSuccess (item, response, file) {
        this.$set(item,'backPic',response.filePath);
        this.$forceUpdate()
      },
      addCardItem(){
        if(this.cardItemList.length > 0){
          let item = this.cardItemList[0];
          let newItem = {orderNumber: item.orderNumber, orderItemId: this.orderItem.orderItemId, prodName: item.prodName, skuName: item.skuName, flag: 0, prodCount: 1 }
          this.cardItemList.push(newItem);
        }else{
          let newItem = {orderNumber: this.orderItem.orderNumber, orderItemId: this.orderItem.orderItemId, prodName: this.orderItem.prodName, skuName: this.orderItem.skuName, flag: 0, prodCount: 1}
          this.cardItemList.push(newItem);
        }
      },
      handleFlag(item, index){
        let fl = item.flag == 1? 0 : 1
          this.$http({
              url: this.$http.adornUrl('/prod/orderCardItem/flag'),
              method: 'post',
              data: this.$http.adornParams(
                  Object.assign({
                          cardItemId: item.cardItemId,
                          flag: fl
                      },
                  )
              )
          }).then(({data}) => {
            if(data){
              this.$message({
                message: "标记完成",
                type: 'success',
              });
              this.cardItemList[index].flag = fl;
            }else{
              this.$message({
                message: "标记失败",
                type: 'error',
              })
            }
          })
      },
      previewPic(cardItem, picUrl, prodName, side){
        this.previewPicUrl = this.resourcesUrl + picUrl
        this.previewPicDialogVisible = true;
        this.side = side;
        if(prodName.indexOf('小卡') != -1){
          this.prodType = '小卡';
        } else if(prodName.indexOf('仿拍立得') != -1){
          this.prodType = '仿拍立得';
        }else if(prodName.indexOf('直拍封面') != -1){
          this.prodType = '直拍封面';
        }else if(prodName.indexOf('票根') != -1){
          this.prodType = '票根';
        }else if(prodName.indexOf('明信片') != -1){
          this.prodType = '明信片';
        }else if(prodName.indexOf('方卡') != -1){
          this.prodType = '方卡';
        }else if(prodName.indexOf('流砂书签') != -1){
          this.prodType = '流砂书签';
        }else if(prodName.indexOf('徽章') != -1){
          this.prodType = '徽章';
        }else if(prodName.indexOf('手幅') != -1){
          this.prodType = '手幅';
        }else if(prodName.indexOf('毛绒徽章') != -1){
          this.prodType = '毛绒徽章';
        }else if(prodName.indexOf('方形贴纸') != -1){
          this.prodType = '方形贴纸';
        }else if(prodName.indexOf('三宫格') != -1){
          this.prodType = '三宫格';
        }
        this.$nextTick(() =>{
          this.$refs.canvasPreviewRef.init(cardItem, this.resourcesUrl + picUrl, this.prodType, side)
        })
      },
      getDataList () {
        this.$http({
          url: this.$http.adornUrl('/prod/orderCardItem/page'),
          method: 'get',
          params: this.$http.adornParams(
                  Object.assign({
                            size: 300,
                            orderNumber: this.orderItem.orderNumber,
                            orderItemId: this.orderItem.orderItemId,
                          },
                  )
          )
        }).then(({data}) => {
          this.cardItemList = data.records;
        })
      },
    }
  }
</script>
<style lang="scss" scoped>
  .previewClass{
    position:absolute;
    border-style:solid;
    border-color:red;
    opacity:0.3;
    z-index:3;
  }
  #cardBottom{
    position:absolute;
    z-index:1;
  }
  .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: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  /* .prods-select-body {
    height: 600px;
    overflow: auto;
    border-top: 1px solid #eeeeee;
    border-right: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
  } */
  .brand-select-pop {
    & ::v-deep .el-dialog__body {
      padding-top: 20px;
      padding-bottom: 20px;
    }
    .main-container {
      margin: 0;
      .pagination {
        text-align: right;
      }
    }
  }
</style>
