<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"></el-option>
          <el-option key="squarecard" label="方卡" value="squarecard"></el-option>
          <el-option key="badge" label="徽章" value="badge"></el-option>
          <el-option key="postcard" label="明信片" value="postcard"></el-option>
          <el-option key="bookmark" label="书签" value="bookmark"></el-option>
          <el-option key="tipscard" label="手幅" value="tipscard"></el-option>
          <el-option key="polaroid" label="拍立得" value="polaroid"></el-option>
          <el-option key="covercard" label="直拍封面" value="covercard"></el-option>
          <el-option key="stub" label="票根" value="stub"></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){
            width = 709;
            height = 1087;
          }else if(templateUsage.indexOf("stub") !== -1){
            width = 780;
            height = 1489;
          }else if(templateUsage.indexOf("bookmark") !== -1){
            width = 638;
            height = 1819;
          }else if(templateUsage.indexOf("postcard") !== -1){
            width = 1252;
            height = 1819;
          }
          if(isBack){
            let imageFormat = imageStr.split('.').pop();
            if(imageFormat != 'jpg'){
              reject(index);
            }
          }else if(!isBack && templateUsage.indexOf("polaroid") !== -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>
