<template>
  <el-dialog
    :title="title"
    center
    append-to-body
    :visible.sync="show"
    width="800px">
    <div v-loading="loading">
      <el-form ref="form" :model="form">
        <el-row>
          <el-col :span="4"><label>单品名称</label></el-col>
          <el-col :span="8">
            <el-form-item>
              <el-input v-model="form.name" placeholder="规则：主题名＋单品名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <label>库存数量</label>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-input-number v-model="form.num"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <label>标签</label>
          </el-col>
          <el-col :span="20">
            <el-form-item>
              <el-tag
                :key="tagIndex"
                v-for="(tag,tagIndex) in form.category_name"
                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-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        <el-col :span="4">
          <label>封面图片</label>
        </el-col>
        <el-col :span="20">
          <div class="upload-block">
            <el-upload
              action="/api/public/upload/zone"
              :http-request="uploadFile"
              :class="{disabled:!uploadShow}"
              :before-upload="beforeAvatarUpload"
              list-type="picture-card"
              :file-list="imageList"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-col>
      </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </div>
  </el-dialog>
</template>

<script>
  import {getSingleDetailApi,addSingleApi,editSingleApi,uploadFileApi} from "../../service/api";
  export default {
    name: "dialogObj",
    props:[
      'dialogObj'
    ],
    data(){
      return{
        show: false,
        id: '',
        loading: true,
        uploadShow: true,
        type: 0,
        title: '',
        form:{ name: '', num: 0, cover: ''},
        imageList: [],
        rules: {

        },
        inputVisible: false,
        inputValue: '',
        teacherDetail: {}
      }
    },
    methods:{
      handleClose(tag) {
        this.form.category_name.splice(this.form.category_name.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.form.category_name.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      sub(){
        switch(this.dialogObj.type){
          case 0:
            this.$refs['form'].validate((valid) => {
              if(valid){
                if(this.imageList.length >0){
                  this.form.cover = this.imageList[0].name;
                }
                let json = this.form;
                json.category_name = json.category_name.join(',')
                addSingleApi(json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  this.$emit("reflash");
                  this.show = false;
                })
              }
            });
            break;
          case 1:
            this.$refs['form'].validate((valid) => {
              if(valid){
                if(this.imageList.length >0){
                  this.form.cover = this.imageList[0].name;
                }
                let json = this.form;
                json.category_name = json.category_name.join(',')
                editSingleApi(this.id,json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  this.$emit("reflash");
                  this.show = false;
                })
              }
            });
            break
        }
      },
      handleAvatarSuccess(res) {
        this.imageList = [{name:res.data.url,url:process.env.IMAGE_URL_HEAD + res.data.url}]
      },
      beforeAvatarUpload(){
        this.uploadShow = false
      },
      uploadFile(a) {
        this.loading = true;
        this.$store.dispatch('setProgress',{type:'new',id:a.file.uid});
        this.fileUid = a.file.uid;
        uploadFileApi({file:a.file,type:'local'}).then(res=>{
          this.imageList = [{name:res.url,url:process.env.IMAGE_URL_HEAD + res.url}]
          this.loading = false;
          this.$message({
            type: 'success',
            message: '上传成功!'
          });
        }).catch(()=>{
          this.loading = false;
        })
      },
      handleRemove(){
        this.uploadShow = true
      },
      initDialog(){
        switch(this.dialogObj.type){
          case 0:
            this.title = '新增单品';
            this.show = this.dialogObj.show;
            this.type = 0;
            this.imageList = [];
            this.form = {
              name: '',
              num: 0,
              cover: '',
              category_name: []
            };
            this.uploadShow = true;
            this.loading = false;
            break;
          case 1:
            this.title = '编辑';
            this.show = this.dialogObj.show;
            this.id = this.dialogObj.id;
            this.type = 1;
            getSingleDetailApi(this.dialogObj.id).then(res=>{
              this.loading = false;
              this.form = {
                name:res.name,
                num:res.num,
                cover:res.cover,
                category_name: res.category_name ? res.category_name.split(',') : []
              };
              if(this.form.cover && this.form.cover !== ''){
                this.imageList = [{name:res.cover,url:process.env.IMAGE_URL_HEAD + res.cover}];
                this.uploadShow = false
              }else{
                this.imageList = [];
                this.uploadShow = true
              }
            });
            break;
        }
      }
    },
    watch:{
      dialogObj:{
        handler: function () {
          this.loading = true;
          this.initDialog()
        },
        deep: true
      },
      show(value){
        this.$emit("changeShow",value);
      }
    }
  }
</script>

<style scoped lang="less">
  .el-col{
    margin-bottom: 20px;
    line-height: 40px;
    .el-select{
      width: 100%;
    }
    .upload-block{
      height: 150px;
    }
    label{
      color: #5982e6;
      text-align: center;
      display: block;
    }
  }
  .dialog-footer{
    display: block;
    text-align: center;
  }
</style>
<style>
  .disabled .el-upload--picture-card {
    display: none !important;
  }
  .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>

