<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="prodId">
        <el-select v-model="dataForm.prodId" clearable filterable @change="prodChange">
          <el-option v-for="(item, index) in prodList"
             :key="index"
             :label="item.prodName"
             :value="item.prodId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input v-model="dataForm.category" style="width: 185px" />
      </el-form-item>
      <el-row>
        <el-col :span="6">
            <el-form-item label="正面" prop="frontUrl">
              <img-upload v-model="dataForm.frontUrl" :limit="1"></img-upload>
            </el-form-item>
          </el-col>
        <el-col :span="6">
          <el-form-item label="背面" prop="backUrl">
            <img-upload v-model="dataForm.backUrl" :limit="1"></img-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="是否禁用" prop="isDelete">
        <el-select v-model="dataForm.isDelete" clearable filterable>
          <el-option key="1" label="启用" :value=0 ></el-option>
          <el-option key="0" label="禁用" :value=1 ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="seq">
        <el-input v-model="dataForm.seq" style="width: 185px" 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'
export default {
  components: {
    ImgUpload
  },
  data () {
    return {
      visible: false,
      dataForm: {
        id: null,
        frontUrl: null,
        backUrl: null,
        prodId: null,
        prodName: null,
        seq: null,
        isDelete: 0,
        category:null
      },
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      prodList: [],
      dataRule: {
      }
    }
  },
  created(){
    this.getProdList();
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl('/print/printPicLib/info/' + this.dataForm.id),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            this.dataForm = data
          })
        }
      })
    },
    prodChange(prodId){
      this.prodList.map(item =>{
        if(item.prodId === prodId){
          this.dataForm.prodName = item.prodName;
        }
      });
    },
    getProdTypeSize(){
      let width = 0;
      let height = 0;
      let prodName = this.dataForm.prodName;
      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 = 850;
        height = 850;
      }else if(prodName.indexOf("明信片") !== -1){
        width = 1252;
        height = 1819;
      }
      return {width, height};
    },
    //验证图片尺寸
    checkImageSize(imageStr, index) {
      let width = this.getProdTypeSize().width;
      let height = this.getProdTypeSize().height;
      return new Promise((resolve, reject) => {
        let image = new Image();
        image.onload = function() {
          let imageFormat = imageStr.split('.').pop();
          if(imageFormat !== 'jpg'){
            reject(index);
          }
          if ((image.width === width && image.height === height)) {
            resolve();
          } else {
            reject(index);
          }
        };
        image.src = this.resourcesUrl + imageStr;
      });
    },

    getProdList(){
      this.$http({
        url: this.$http.adornUrl('/prod/prod/simpleList'),
        method: 'GET',
        params: this.$http.adornParams({customized:0})
      }).then(({data}) => {
        this.prodList = data
      })
    },
    // 表单提交
    async dataFormSubmit () {
      try{
        let imgs = [];
        imgs[0] = this.dataForm.frontUrl ? this.dataForm.frontUrl:null;
        if(this.dataForm.backUrl){
          imgs[1] = this.dataForm.backUrl ? this.dataForm.backUrl:null;
        }
        await Promise.all(imgs.map(this.checkImageSize));
        this.$http({
          url: this.$http.adornUrl('/print/printPicLib'),
          method: this.dataForm.id ? '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} 张图片不符合尺寸要求。`)
      }

    }
  }
}
</script>
