<template>
  <div class="add">
    <el-button type="primary" size="small" style="margin-bottom:16px" @click="dialogVisible=true" v-if="type=='add'">新增</el-button>
    <el-button type="text" size="small" @click="editBtn" v-else>编辑</el-button>
    <el-dialog
      :title="type == 'add' ? '新增计量单位' : '编辑计量单位'"
      :visible.sync="dialogVisible"
      width="30%"
      append-to-body
      :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="计量单位" prop="unitname">
          <el-input v-model="ruleForm.unitname" size="small" placeholder="比如：克/千克"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div>
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="submit" size="small">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
  
</template>

<script>
import { log } from '@antv/g2plot/lib/utils';
export default {
  name: '',
  data() {
    return {
      currentData:'',
      dialogVisible:false,
      ruleForm: {
        unitname:''
      },
      rules:{
        unitname: [
          { required: true, message: '请输入计量单位', trigger: 'blur' },
        ]
      }
    };
  },
  props:['type','unitData'],
  computed:{
  },
  watch:{
    currentData: {
      handler(val) {
        this.ruleForm.unitname = val.unitname
      }
    }
  },
  methods: {
    editBtn() {
      this.dialogVisible=true
      this.currentData = this.unitData
    },
    handleClose() {
      this.dialogVisible = false
    },
    submit() {
      this.$refs.ruleForm.validate(async val => {
        if(val) {
          let res = await this.$api.requested({
            "accesstoken": "bed2f4500c0e799a29ddbbe47a2a04b6",
            "id": "20220922084703",
            "version":1,
            "content": {
                "unitid":this.type == 'add' ? 0 : this.currentData.unitid,
                "unitname":this.ruleForm.unitname
            }
          })
          console.log(res);
          this.tool.showMessage(res,() => {
            this.$emit('unitAddSuccess')
            this.dialogVisible = false
            this.$refs.ruleForm.resetFields()
          })
        }
      })
    }
  },
};
</script>

<style scoped>
  .dialog-footer {
    display: flex;
    justify-content: space-evenly;
  }
  /deep/.el-dialog__body {
    padding-top: 10px !important;
    padding-bottom: 0 !important;
  }
  /deep/.dialog-footer {
    margin-top: 10px !important;
  }
</style>
