<template>
  <el-dialog
    :title="!dataForm.templateId ? this.$i18n.t('crud.addTitle') : this.$i18n.t('temp.modify')"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item label="模板正反面" prop="templateSide">
        <el-select v-model="dataForm.templateSide" clearable filterable>
          <el-option key="Front" label="正面" value="Front"></el-option>
          <el-option key="Back" label="背面" value="Back"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板用途" prop="templateUsage">
        <el-select v-model="usageList" clearable filterable multiple>
          <el-option key="smallcard" label="小卡" value="smallcard,YXK,ZJXK,DBYXK,DBZJXK"></el-option>
          <el-option key="squarecard" label="大方卡" value="squarecard,FK"></el-option>
          <el-option key="XFK" label="小方卡" value="XFK"></el-option>
          <el-option key="badge" label="徽章" value="badge,HZ"></el-option>
          <el-option key="postcard" label="明信片" value="postcard,MXP"></el-option>
          <el-option key="bookmark" label="书签" value="bookmark,SQ"></el-option>
          <el-option key="tipscard" label="手幅" value="tipscard,SF"></el-option>
          <el-option key="covercard" label="直拍封面" value="covercard,ZP"></el-option>
          <el-option key="stub" label="票根" value="stub,PG"></el-option>
          <el-option key="FP" label="3寸花式拍立得" value="FP,polaroid"></el-option>
          <el-option key="4CFP" label="4寸花式拍立得" value="4CFP"></el-option>
          <el-option key="5CFP" label="5寸花式拍立得" value="5CFP"></el-option>
          <el-option key="SBSGG" label="竖版四宫格" value="SBSGG"></el-option>
          <el-option key="TZSGG" label="田字四宫格" value="TZSGG"></el-option>
          <el-option key="EGG" label="横版二宫格" value="EGG"></el-option>
          <el-option key="3CFZFP" label="3寸仿真拍立得" value="3CFZFP"></el-option>
          <el-option key="4CFZFP" label="4寸仿真拍立得" value="4CFZFP"></el-option>
          <el-option key="5CFZFP" label="5寸仿真拍立得" value="5CFZFP"></el-option>
          <el-option key="XL3CFZFP" label="撕拉3寸花式仿真拍立得" value="XL3CFZFP"></el-option>
          <el-option key="XL4CFZFP" label="撕拉4寸花式仿真拍立得" value="XL4CFZFP"></el-option>
          <el-option key="YOUXK" label="游戏卡" value="YOUXK"></el-option>
          <el-option key="YYK" label="语音卡" value="YYYXK,YYZJXK"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板风格" prop="templateStyle">
        <el-select v-model="dataForm.templateStyleId" clearable filterable>
          <el-option
                  v-for="node in styleList"
                  :key="node.styleId"
                  :label="node.styleName"
                  :value="node.styleId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板系列" prop="templateSeries">
        <el-select v-model="dataForm.templateSeriesId" clearable filterable>
          <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 label="模板图片" prop="templatePic">
        <img-upload v-model="dataForm.templatePic" :limit="20"></img-upload>
      </el-form-item>
      <!--<el-form-item label="商家ID" prop="shopId">
        <el-input v-model="dataForm.shopId"></el-input>
      </el-form-item>-->
      <el-form-item label="是否禁用" prop="status">
        <el-select v-model="dataForm.status" clearable filterable>
          <el-option key="1" label="启用" :value=1 ></el-option>
          <el-option key="0" label="禁用" :value=0 ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="seq">
        <el-input v-model="dataForm.seq" type="number"/>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button class="default-btn" @click="visible = false">{{$t("crud.filter.cancelBtn")}}</el-button>
      <el-button class="default-btn primary-btn" type="primary" @click="dataFormSubmit()">{{$t("crud.filter.submitBtn")}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import ImgUpload from '@/components/imgs-upload'
  // import uploadPic from './upload-pic.vue'
export default {
  components: {
    ImgUpload
  },
  data () {
    return {
      visible: false,
      dataForm: {
        templateId: null,
        templateSide: null,
        templateStyleId: null,
        templateSeriesId: null,
        templateStyle: null,
        templateSeries: null,
        templatePic: null,
        shopId: this.$store.state.user.shopId,
        status: null,
        createTime: null,
        templateUsage: null,
        seq: 1
      },
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      seriesList: [],
      styleList: [],
      usageList:[],
      dataRule: {
      }
    }
  },
  created () {
    this.getStyleList()
    this.getSeriesList()
  },
  methods: {
    init (templateId) {
      this.dataForm.templateId = templateId || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.templateId) {
          this.$http({
            url: this.$http.adornUrl('/prod/prodTemplate/info/' + this.dataForm.templateId),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            this.dataForm = data;
            this.usageList = data.templateUsage.split(",");
          })
        }
      })
    },
    //验证图片尺寸
    checkImageSize(imageStr, index) {
      let width = 0;
      let height = 0;
      let templateUsage = this.usageList.join(",");
      let isBack = this.dataForm.templateSide === 'Back';
      return new Promise((resolve, reject) => {
        let image = new Image();
        image.onload = function() {
          if(templateUsage.indexOf("smallcard") !== -1 || templateUsage.indexOf("polaroid") !== -1 || templateUsage.indexOf("YYYXK") !== -1 || templateUsage.indexOf("YYZJXK") !== -1){
            width = 709;
            height = 1087;
          }else if(templateUsage.indexOf("stub") !== -1 || templateUsage.indexOf("PG") !== -1){
            width = 780;
            height = 1489;
          }else if(templateUsage.indexOf("bookmark") !== -1 || templateUsage.indexOf("SQ") !== -1){
            width = 638;
            height = 1796;
          }else if(templateUsage.indexOf("postcard") !== -1 || templateUsage.indexOf("MXP") !== -1){
            width = 1229;
            height = 1796;
          }else if(templateUsage.indexOf("4CFP") !== -1 || templateUsage.indexOf("4CFZFP") !== -1 || templateUsage.indexOf("XL4CFZFP") !== -1){
            width = 921;
            height = 1087;
          }else if(templateUsage.indexOf("5CFP") !== -1 || templateUsage.indexOf("5CFZFP") !== -1){
            width = 1346;
            height = 1087;
          }else if(templateUsage.indexOf("FP") !== -1 || templateUsage.indexOf("3CFZFP") !== -1 || templateUsage.indexOf("XL3CFZFP") !== -1){
            width = 709;
            height = 1087;
          }else if(templateUsage.indexOf("EGG") !== -1){
            width = 1228;
            height = 709;
          }else if(templateUsage.indexOf("SBSGG") !== -1){
            width = 638;
            height = 1796;
          }else if(templateUsage.indexOf("TZSGG") !== -1){
            width = 1229;
            height = 1796;
          }else if(templateUsage.indexOf("XFK") !== -1){
            width = 673;
            height = 673;
          }else if(templateUsage.indexOf("FK") !== -1){
            width = 1229;
            height = 1229;
          }else if(templateUsage.indexOf("YOUXK") !== -1){
            width = 803;
            height = 1098;
          }
          if(isBack){
            let imageFormat = imageStr.split('.').pop();
            if(imageFormat != 'jpg'){
              reject(index);
            }
          }else if(!isBack && (templateUsage.indexOf("polaroid") !== -1 || templateUsage.indexOf("FP") !== -1 || templateUsage.indexOf("EGG") !== -1)){
            let imageFormat = imageStr.split('.').pop();
            if(imageFormat != 'png'){
              reject(index);
            }
          }
          if ((image.width === width && image.height === height)) {
            resolve();
          } else {
            reject(index);
          }
        };
        image.src = this.resourcesUrl + imageStr;
      });
    },
    // 表单提交
    async dataFormSubmit () {
      try{
        let imgUrlArr = this.dataForm.templatePic.split(",");
        await Promise.all(imgUrlArr.map(this.checkImageSize));
        this.handleStyleName(this.dataForm.templateStyleId);
        this.handleSeriesName(this.dataForm.templateSeriesId);
        this.dataForm.templateUsage = this.usageList.join(",");
        this.$http({
          url: this.$http.adornUrl('/prod/prodTemplate'),
          method: this.dataForm.templateId ? 'put' : 'post',
          data: this.$http.adornData(this.dataForm)
        }).then(({data}) => {
          this.$message({
            message: this.$i18n.t('publics.operation'),
            type: 'success',
            duration: 200,
            onClose: () => {
              this.visible = false;
              this.$emit('refreshDataList')
            }
          })
        })
      }catch (error) {
        this.$message.error(`第 ${error + 1} 张图片不符合尺寸要求。`)
      }
    },
    getStyleList () {
      this.$http({
        url: this.$http.adornUrl('/prod/prodTemplateStyle/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign({
              size: 100,
              shopId: this.$store.state.user.shopId
            }
          )
        )
      }).then(({data}) => {
        this.styleList = data.records
      })
    },
    getSeriesList () {
      this.$http({
        url: this.$http.adornUrl('/prod/prodTemplateSeries/page'),
        method: 'get',
        params: this.$http.adornParams(
                Object.assign({
                  size: 100,
                  shopId: this.$store.state.user.shopId
                }
                )
        )
      }).then(({data}) => {
        this.seriesList = data.records
      })
    },
    handleStyleName (styleId) {
      this.styleList.forEach(style =>{
        if (style.styleId == styleId) {
          this.dataForm.templateStyle = style.styleName
          return;
        }
      })
    },
    handleSeriesName (seriesId) {
      this.seriesList.forEach(series =>{
        if (series.seriesId == seriesId) {
          this.dataForm.templateSeries = series.seriesName
        }
      })
    },
  }
}
</script>
