<template>
  <el-dialog :title="dialogObj.title"
             :visible.sync="dialogObj.show">
    <el-form label-width="80px">
      <el-form-item label="名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="封面">
        <el-upload
          class="upload-demo"
          action="/api/public/upload"
          :http-request="uploadFile"
          list-type="picture-card"
          multiple
          :limit="1"
          :file-list="imgList">
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogObj.show = false">取 消</el-button>
    <el-button type="primary" @click="onSave()">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
  import {getCategoryApi,addCategoryApi,updateMenuApi,uploadFileApi} from "../../service/api";

  export default {
    name: "menuDialog",
    data(){
      return {
        imgList:[],
        form:{
          name:'',
          pid:'',
          cover:'',
          type:0
        }
      }
    },
    methods:{
      initDialog(){
        switch (this.dialogObj.type) {
          case 0:
            this.form = {
              name:'',
              pid:this.dialogObj.pid,
              cover:'',
              type:0
            };
            this.imgList = [];
            break;
          case 1:
            this.form = {
              name:this.dialogObj.that.name,
              pid:this.dialogObj.that.pid,
              cover:this.dialogObj.that.cover,
              type:0
            };
            this.imgList[0]= {name:this.dialogObj.that.cover,url:this.dialogObj.that.cover,title:'',lable:''}
        }
      },
      onSave(){
        switch (this.dialogObj.type) {
          case 0:
            addCategoryApi(this.form).then(res=>{
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.dialogObj.show = false;
              this.$emit('reflash')
            });
            break;
          case 1:
            updateMenuApi(this.dialogObj.category_id,this.form).then(res=>{
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
              this.dialogObj.show = false;
              this.$emit('reflash')
            })
        }
      },
      uploadFile(a){
        this.$store.dispatch('setProgress',{type:'new',id:a.file.uid});
        uploadFileApi({file:a.file,type:'local'}).then(res=>{
          this.imgList[0]= {name:res.url,url:process.env.IMAGE_URL_HEAD + res.url,title:'',lable:''}
          this.form.cover = this.imgList[0].url
        })
      }
    },
    props:[
      'dialogObj'
    ],
    watch:{
      'dialogObj'(){
        this.initDialog()
      }
    }
  }
</script>

<style scoped>

</style>