<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>
        <el-radio v-model="mode" label="choose">选图模式</el-radio>
        <el-button @click="openCanvasParamPicFormByOrderNumber(orderItem)" size="mini" type="text" v-if="orderItem.prodName.indexOf('简约') !== -1 || orderItem.prodName.indexOf('高阶') !== -1">查看工艺</el-button>
      </div>

      <div style="border: 2px solid pink; display: inline-block;margin-right: 5px;" v-for="(item, index) in cardItemList" :key="item.cardItemId">
        <div :style="mode === 'choose' && item.isSelected? divLightStyle : {border: '3px solid #fff'}" @click="cardItemSelect(item, index)">
          <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>
                <div v-if="mode=='view' || mode === 'choose'" style="width: 100px;height: auto">
                  <img :src="resourcesUrl + item.frontPic" @click="previewPic(item, item.frontPic, item.prodName, 'front')"/>
                </div>
                <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_vp'),locale:lang}"
                           :on-success="(res,file)=>{onFrontUploadSuccess(item,res,file)}"
                           :show-file-list="false">
                  <img v-if="item.frontPic" style="width: 100px;height: auto" :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>
                <div v-if="mode=='view' || mode === 'choose'" style="width: 100px;height: auto">
                  <img :src="resourcesUrl + item.backPic" @click="previewPic(item, item.backPic, item.prodName, 'back')"/>
                </div>
                <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_vp'),locale:lang}"
                           :on-success="(res,file)=>{onBackUploadSuccess(item,res,file)}"
                           :show-file-list="false">
                  <img v-if="item.backPic" style="width: 100px;height: auto" :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==='choose'" type="text" size="mini" @click="openAddToCardLibDialog(item)">加入图集</el-button>-->
          <el-button v-if="mode==='view'" type="text" size="mini" @click="openOrgPicForm(item, index)">原图</el-button>
          <el-button v-if="mode==='view' && (orderItem.prodName.indexOf('简约') !== -1 || orderItem.prodName.indexOf('高阶') !== -1)" type="text" size="mini" @click="openCanvasParamPicFormByItem(item, index)">工艺</el-button>
          <el-button v-if="(item.prodName.indexOf('语音') !== -1 || item.prodName.toLowerCase().indexOf('ar') !== -1) && mode=='view'" type="text" size="mini" @click="openYYForm(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>
      <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>
    <YuyinPreview ref="yuYinPreviewRef"></YuyinPreview>
    <OrgPicPreview ref="orgPicPreviewRef"></OrgPicPreview>
    <CanvasParamPicPreview ref="canvasParamPicPreviewRef"></CanvasParamPicPreview>
    <el-dialog title="加入图集" :visible.sync="addToCardLibVisible" :modal="false" width="80%">
      <el-form
        :model="cardLibItemDataForm"
        size="small"
        ref="dataForm"
        label-width="80px">
        <el-form-item prop="seriesId" label="团队组合">
          <el-select v-model="cardLibItemDataForm.seriesId" clearable filterable @change="selectSeries">
            <el-option
              v-for="node in seriesList"
              :key="node.seriesId"
              :label="node.seriesName"
              :value="node.seriesId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="personId" label="成员名称" class="search-form-item">
          <el-select v-model="cardLibItemDataForm.personId" placeholder="请选择爱豆" clearable filterable>
            <el-option v-for="person in personList" :label="person.personName" :value="person.id"></el-option>
          </el-select>
        </el-form-item>
        <div class="create-card-lib" v-for="(card, index) in cardLibItemDataForm.orderCardItemList" :key="index">
          <el-row :gutter="12" style="padding-top: 5px">
            <span class="num">{{card.num}}</span>
            <el-col :span="12">
              <el-card :body-style="{ padding: '0px' }">
                <div style="padding: 3px; text-align: center">
                  <span>正面</span>
                </div>
                <div style="width: 100px;height: auto">
                  <img :src="resourcesUrl + card.frontPic"/>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card :body-style="{ padding: '0px' }">
                <div style="padding: 3px; text-align: center">
                  <span>背面</span>
                </div>
                <div style="width: 100px;height: auto">
                  <img :src="resourcesUrl + card.backPic"/>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="default-btn">{{$t("crud.filter.cancelBtn")}}</el-button>
        <el-button :loading="addToCardLibLoading" class="default-btn primary-btn" type="primary" @click="addToCardLibSubmit()">{{$t("crud.filter.submitBtn")}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import CanvasPreview from "../canvas-preview/index";
  import YuyinPreview from "../yuyin-preview/index";
  import OrgPicPreview from "../org-pic-preview/index";
  import CanvasParamPicPreview from "../canvas-param-pic-preview/index";
  export default {
    components: {CanvasPreview, YuyinPreview,OrgPicPreview, CanvasParamPicPreview},
    data () {
      return {
        addToCardLibLoading: false,
        cardLibItemDataForm:{},
        lang: localStorage.getItem('lang') || 'zh_CN',
        cardItemList:[],
        previewPicUrl: null,
        prodType: null,
        previewPicDialogVisible: false,
        previewYuyinDialogVisible: false,
        side:null,
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
        mode: 'view',
        previewWidth: 0,
        previewHeight: 0,
        bloodWidth: 0,
        addToCardLibVisible: false,
        seriesList:[],
        personList:[],
        divLightStyle: {border: '3px solid red'},
      }
    },
    props: {
      orderItem: {
        default: null,
        type: Object
      },
      showFlagBtn:{
        default: true,
        type: Boolean
      }
    },
    created() {
      this.$nextTick(() => {
        this.getDataList();
      })
    },
    methods: {
      cardItemSelect(cardItem, index){
        if (cardItem.isSelected) {
          cardItem.isSelected = false
        } else {
          cardItem.isSelected = true
        }
        this.$set(this.cardItemList, index, cardItem)
      },
      addToCardLibSubmit(){
        this.$http({
          url: this.$http.adornUrl('/prod/orderCardItem/addToCardLib'),
          method: 'POST',
          data: this.cardLibItemDataForm
        }).then(({data}) => {
          this.addToCardLibLoading = false
          this.$message({
            message: '加入成功',
            type: 'success',
            duration: 300,
            onClose: () => {
              this.addToCardLibLoading = false
              this.cardLibItemDataForm = {}
              this.addToCardLibVisible = false
            }
          })
        })
      },
      getSeriesList () {
        this.$http({
          url: this.$http.adornUrl('/prod/prodTemplateSeries/page'),
          method: 'get',
          params: this.$http.adornParams(
            Object.assign({
                size: 100,
                shopId: 1
              },
            )
          )
        }).then(({data}) => {
          this.seriesList = data.records
        })
      },
      selectSeries(seriesId){
        this.personList = []
        this.getPersonList(seriesId)
      },
      getPersonList (seriesId) {
        this.$http({
          url: this.$http.adornUrl('/cardLib/cardPerson/page'),
          method: 'get',
          params: this.$http.adornParams(
            Object.assign({
                size: 100,
                seriesId: seriesId
              },
            )
          )
        }).then(({data}) => {
          this.personList = data.records
        })
      },
      openAddToCardLibDialog(cardItem){
        let addToCardLibList = this.cardItemList.filter(item => item.isSelected === true)
        this.cardLibItemDataForm.orderCardItemList = addToCardLibList
        this.addToCardLibVisible = true
        this.getSeriesList()
      },
      openYYForm(item, index){
        this.$nextTick(() =>{
          this.$refs.yuYinPreviewRef.init(item)
        })
      },
      openOrgPicForm(item, index){
        this.$nextTick(() =>{
          this.$refs.orgPicPreviewRef.init(item)
        })
      },
      openCanvasParamPicFormByOrderNumber(orderItem, index){
        this.$nextTick(() =>{
          this.$refs.canvasParamPicPreviewRef.initByOrderNumber(orderItem)
        })
      },
      openCanvasParamPicFormByItem(cardItem, index){
        this.$nextTick(() =>{
          this.$refs.canvasParamPicPreviewRef.initByItem(cardItem)
        })
      },
      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("3寸花式拍立得") !== -1 || prodName.indexOf("3寸仿真拍立得") !== -1){
            width = 709;
            height = 1087;
          }else if(prodName.indexOf("票根") !== -1){
            width = 780;
            height = 1489;
          }else if(prodName.indexOf("直拍封面") !== -1){
            width = 732;
            height = 1252;
          }else if(prodName.indexOf("二宫格") !== -1){
            width = 1252;
            height = 732;
          }else if(prodName.indexOf("AR明信片") !== -1){
            width = 1252;
            height = 1819;
          }else if(prodName.indexOf("明信片") !== -1){
            width = 1229;
            height = 1796;
          }else if(prodName.indexOf("田字四宫格") !== -1){
            width = 1229;
            height = 1796;
          }else if(prodName.indexOf("三宫格") !== -1){
            width = 673;
            height = 1547;
          }else if(prodName.indexOf("书签") !== -1){
            width = 638;
            height = 1796;
          }else if(prodName.indexOf("小方卡") !== -1){
            width = 709;
            height = 709;
          }else if(prodName.indexOf("方卡") !== -1){
            width = 1229;
            height = 1229;
          }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 = 720;
            height = 720;
          }else if(prodName.indexOf("亚克力小邮票") !== -1){
            width = 602;
            height = 602;
          }else if(prodName.indexOf("亚克力小卡") !== -1){
            width = 709;
            height = 1087;
          }else if(prodName.indexOf("4寸直角卡") !== -1 || prodName.indexOf("4寸花式拍立得") !== -1 || prodName.indexOf("4寸仿真拍立得") !== -1){
            width = 921;
            height = 1087;
          }else if(prodName.indexOf("5寸直角卡") !== -1 || prodName.indexOf("5寸花式拍立得") !== -1 || prodName.indexOf("5寸仿真拍立得") !== -1){
            width = 1346;
            height = 1087;
          }else if(prodName.indexOf("长方形贴纸") !== -1){
            width = 780;
            height = 1134;
          }else if(prodName.indexOf("方形贴纸") !== -1){
            width = 662;
            height = 662;
          }else if(prodName.indexOf("撕拉3寸") !== -1){
            width = 709;
            height = 1087;
          }else if(prodName.indexOf("撕拉") !== -1){
            width = 768;
            height = 768;
          }else if(prodName.indexOf("5寸直角卡") !== -1){
            width = 1087;
            height = 1347;
          }else if(prodName.indexOf("60x180") !== -1){
            width = 780;
            height = 2197;
          }else if(prodName.indexOf("70x210") !== -1){
            width = 898;
            height = 2551;
          }else if(prodName.indexOf("游戏") !== -1 || prodName.indexOf("永夜星河") !== -1 || prodName.indexOf("珠帘玉幕") !== -1 || prodName.indexOf("双城之战") !== -1){
            width = 803;
            height = 1098;
          }else if(prodName.indexOf("大3寸") !== -1){
            width = 803;
            height = 1098;
          }else if(prodName.indexOf("透明胶片拍立得") !== -1){
            width = 768;
            height = 768;
          }
          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('3寸花式拍立得') != -1){
          this.prodType = '3寸花式拍立得';
        }else if(prodName.indexOf('4寸花式拍立得') != -1){
          this.prodType = '4寸花式拍立得';
        }else if(prodName.indexOf('4寸仿真拍立得') != -1){
          this.prodType = '4寸仿真拍立得';
        }else if(prodName.indexOf('5寸花式拍立得') != -1){
          this.prodType = '5寸花式拍立得';
        }else if(prodName.indexOf('5寸仿真拍立得') != -1){
          this.prodType = '5寸仿真拍立得';
        }else if(prodName.indexOf('直拍封面') != -1){
          this.prodType = '直拍封面';
        }else if(prodName.indexOf('票根') != -1){
          this.prodType = '票根';
        }else if(prodName.indexOf('AR明信片') != -1){
          this.prodType = 'AR明信片';
        }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 = '方形贴纸';
        }else if(prodName.indexOf('二宫格') != -1){
          this.prodType = '二宫格';
        }else if(prodName.indexOf('撕拉') != -1){
          this.prodType = '撕拉';
        }else if(prodName.indexOf('5寸直角卡') != -1){
          this.prodType = '5寸直角卡';
        }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('大3寸') != -1){
          this.prodType = '大3寸';
        }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;
      }
    }
  }
  .create-card-lib{
    border: 2px solid pink;
    display: inline-block;
    margin-right: 15px;
    .num{
      position: absolute;
      display:flex;
      justify-content: center;
      align-items: center;
      left: 5px;
      top: 0px;
      color: white;
      border-radius: 100%;
      background-color: red;
      width: 20px;
      height: 20px
    }
  }
</style>
