<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryIds">
              <SelectCategory v-model="form.categoryIds" :multiple="multiple" :collapseTags="collapseTags"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="规格" prop="spec">
              <SelectSpecs v-model="form.spec" ref="selectSpecs" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制作时长" prop="takeTime">
              <el-input v-model="form.takeTime" placeholder="请输入时长,单位秒" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="折扣价" prop="discount">
              <el-input v-model="form.discount" placeholder="请输入折扣价,单位元" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="price">
              <el-input v-model="form.price" placeholder="请输入原价,单位元" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="缩略图点单屏" prop="thumbnail">
              <ImageUpload :value="form.pics.thumbnail" v-model="form.pics.thumbnail" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缩略图小程序" prop="thumbnailApplet">
              <ImageUpload :value="form.pics.thumbnailApplet" v-model="form.pics.thumbnailApplet" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="介绍图点单屏" prop="introImages">
              <ImageUpload :arrType="true" :value="form.pics.introImages" v-model="form.pics.introImages" :limit="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="介绍图小程序" prop="introImagesApplet">
              <ImageUpload :arrType="true" :value="form.pics.introImagesApplet" v-model="form.pics.introImagesApplet"
                :limit="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="内容图点单屏" prop="detailImages">
              <ImageUpload :arrType="true" :value="form.pics.detailImages" v-model="form.pics.detailImages"
                :limit="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内容图小程序" prop="detailImagesApplet">
              <ImageUpload :arrType="true" :value="form.pics.detailImagesApplet" v-model="form.pics.detailImagesApplet"
                :limit="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-form-item label="标签" >
            <div style="border: 1px solid #ccc;height: 70px">
              <el-tag
              :key="tag"
              v-for="tag in goodsTagList"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              />              
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+添加标签</el-button>
            </div>              
          </el-form-item>      
        </el-row>
        <el-row :gutter="10">    
          <el-col :span="12">
            <el-form-item label="描述" prop="desc">
              <el-input v-model="form.desc" type="textarea" placeholder="请输入内容" maxlength="17" show-word-limit/>
            </el-form-item>
          </el-col>
                <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPermi="['system:goods:edit']">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSpu, getSpu, updateSpu } from "@/api/system/goods";
import SelectCategory from "@/components/SelectCategory";
import SelectSpecs from "@/components/SelectSpecs";
import { setSpec } from "./href";
export default {
  props: {
    getList: {
      type: Function,
      default: null
    }
  },
  components: { SelectCategory, SelectSpecs },
  data() {
    var validateThumbnail = (rule, value, callback) => {
      let thumbnailValue=this.form.pics.thumbnail; 
      if (thumbnailValue == undefined || thumbnailValue === '') {        
        callback(new Error('请上传缩略图点单屏'));
      }else {
        callback();
      }
    };   
    var validateIntroImages = (rule, value, callback) => {
      let introImagesValue=this.form.pics.introImages; 
      if (introImagesValue == undefined || introImagesValue === '') {        
        callback(new Error('请上传介绍图点单屏'));
      }else {
        callback();
      }
    };
    var validateDetailImages = (rule, value, callback) => {
      let detailImagesValue=this.form.pics.detailImages; 
      if (detailImagesValue == undefined || detailImagesValue === '') {        
        callback(new Error('请上传内容图点单屏'));
      }else {
        callback();
      }
    };    
    var validateDiscount = (rule, value, callback) => {  
      var regular=/(^[+]{0,1}([0-9]+)$)|(^[+]{0,1}([0-9]+)[\.]{1}[0-9]{1}$)/;   //正数（保留2位小数)    
      if (value == undefined || value === '') {        
        callback(new Error('不能为空'));
      }else if(!regular.test(value)){     
        callback(new Error('请输入大于0的正数,最多保留1位小数'));     
      }else if(this.form.price){
        let discountValue=parseFloat(value);
        let priceValue=parseFloat(this.form.price);
        if(discountValue > priceValue){
          callback(new Error('折扣价不能大于原价'));
        }else {
          callback();
        }      
      }else {
        callback();
      }
    };
    var validatePrice = (rule, value, callback) => {  
      //let regular = /(^[+]{0,1}([1-9]+)$)|(^[+]{0,1}(\d+\.\d{1,2})$)/   //正数（保留2位小数)      
      var regular=/(^[+]{0,1}([0-9]+)$)|(^[+]{0,1}([0-9]+)[\.]{1}[0-9]{1}$)/; //正数 ,小数可有可无，最多2位
      if (value == undefined || value === '') {        
        callback(new Error('不能为空'));
      }else if(!regular.test(value)){    
        callback(new Error('请输入大于0的正数,最多保留1位小数'));     
      }else if(this.form.discount){        
        let discountValue=parseFloat(this.form.discount);
        let priceValue=parseFloat(value);
        if(priceValue<discountValue){
          callback(new Error('原价不能小于折扣价'));
        }else {
          callback();
        }
      }else {
        callback();
      }
    };

    return {
      title: "",
      specNames: "",
      // 表单参数
      form: {
        pics: {},
        spec: [],
        categoryIds:[],
      },
      open: false,
      // 表单校验
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        categoryIds: [{required: true, message: "不能为空", trigger: "blur" }],
        spec: [{required: true, message: "不能为空", trigger: "blur" }],
        takeTime: [{required: true, message: "不能为空", trigger: "blur" }],
        discount: [{required: true,validator: validateDiscount, trigger: "blur" }],
        price: [{required: true, validator: validatePrice, trigger: "blur" }],
        thumbnail:[{ required: true, validator: validateThumbnail, trigger: 'blur' }],
        introImages:[{required: true, validator: validateIntroImages,trigger: "blur" }],
        detailImages:[{required: true, validator: validateDetailImages, trigger: "blur" }],
        
      },
      tagValues:"",
      goodsTagList: [],
      inputVisible: false,
      inputValue: '',
      multiple:true,
      collapseTags:true
    };
  },
  methods: {
    handleClose(tag) {
        this.tagValues=this.tagValues.replace(tag,"");
        this.goodsTagList.splice(this.goodsTagList.indexOf(tag), 1);
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValues = this.inputValue;
        if (inputValues) {
          if(this.goodsTagList.indexOf(inputValues)==-1){            
            if(this.goodsTagList.length >= 3){
              this.$message('标签个数最多添加三个!');
            }else{ 
              this.tagValues=this.tagValues+inputValues;
              if(this.tagValues.length>13){
                this.$message('标签总字符数量最大13!');                
                this.tagValues=this.tagValues.replace(inputValues,"");
              }else{
                this.goodsTagList.push(inputValues);
              }
            }
          }else{
            this.$message('请重新添加标签，该标签已存在!');
          }          
        }
        this.inputVisible = false;
        this.inputValue = '';
      },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      getSpu(id).then((response) => {
        const { data } = response;
        data.pics = JSON.parse(data.pics);
        if(data.spec!=""){
          data.spec = JSON.parse(data.spec);
        }       
        this.goodsTagList=data.goodsTagList;
        if(this.goodsTagList.length>0){
          for(let i=0;i<this.goodsTagList.length;i++){
            this.tagValues=this.tagValues+this.goodsTagList[i];
          }
        }
        this.form = data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    // 表单重置
    reset() {
      this.tagValues="";
      this.goodsTagList=[];
      this.form = {
        pics: {},
        id: null,
        label: null,
        desc: null,
        remark: null
      };  
      //this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const sendForm = JSON.parse(JSON.stringify(this.form));
          sendForm.spec = JSON.stringify(setSpec(sendForm.spec));
          sendForm.pics = JSON.stringify(sendForm.pics);
          sendForm.goodsTagList = this.goodsTagList;
          if (sendForm.id != null) {
            if(sendForm.state == "3"){
              this.$message.error("下架商品之后才可以修改!");
              return;
            }
            updateSpu(sendForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpu(sendForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
       }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
