<template>
  <div class="app-container">
    <!-- 添加或修改商品类型对话框 -->
    <el-dialog :title="form.id ? '编辑' : '新增'" :close-on-click-modal="false" :visible.sync="visible" @close="close" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <el-form-item label="类型名称" prop="name"><el-input v-model="form.name" placeholder="请输入类型名称" clearable /></el-form-item>
        <el-form-item label="状态 " prop="state">
          <el-radio-group v-model="form.state">
            <el-radio-button v-for="dict in stateOptions" :key="dict.dictValue" :label="parseInt(dict.dictValue)">{{ dict.dictLabel }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, exportType } from '@/api/system/shop/type';
import { getToken } from '@/utils/auth';
export default {
  components: {},
  data() {
    return {
      // 遮罩层
      loading: false,
      visible: false,
      // 状态字典
      stateOptions: [],
      // 表单参数
      form: {},
     // 表单校验
     rules: {
       name: [{ required: true, message: '类型名称', trigger: 'blur' }],
       state: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
     }
    };
  },
  created() {
    this.getDicts('common_state').then(response => {
      this.stateOptions = response.data;
    });
  },
  methods: {
    /** 查询商品类型列表 */
    init(id) {
      this.visible = true;
      if (id != '') {
        this.loading = true;
        getType(id).then(response => {
          this.form = response.data;
          this.loading = false;
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateType(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功');
                this.$emit('refresh'); //刷新父组件数据
                this.visible = false;
              }
            });
          } else {
            addType(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功');
                this.$emit('refresh'); //刷新父组件数据
                this.visible = false;
              }
            });
          }
        }
      });
    },
    // 关闭弹窗表单重置
    close() {
      this.resetForm('form');
      this.form = {};
    }
  }
};
</script>
