<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增商品</el-button>
    <el-table :data="products" style="margin-top: 12px;">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="商品名" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="openDialog(scope.row)">编辑</el-button>
          <el-button type="text" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="商品" :visible.sync="showDialog">
      <el-form :model="form">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="form.stock" />
        </el-form-item>
        <el-form-item label="封面">
          <el-input v-model="form.coverUrl" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.description" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="上架" value="ON" />
            <el-option label="下架" value="OFF" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { adminProducts } from '../../api/admin';

export default {
  data() {
    return {
      products: [],
      showDialog: false,
      form: {}
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      adminProducts.list().then((res) => {
        this.products = res.data.data || [];
      });
    },
    openDialog(row) {
      this.form = row ? { ...row } : { status: 'ON', stock: 0 };
      this.showDialog = true;
    },
    save() {
      const action = this.form.id
        ? adminProducts.update(this.form.id, this.form)
        : adminProducts.create(this.form);
      action.then(() => {
        this.$message.success('保存成功');
        this.showDialog = false;
        this.load();
      });
    },
    remove(id) {
      adminProducts.remove(id).then(() => {
        this.$message.success('删除成功');
        this.load();
      });
    }
  }
};
</script>
