<?php

namespace app\admin\controller\app;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * @ControllerAnnotation(title="app_products")
 */
class Products extends AdminController
{

    use \app\admin\traits\Curd;

    /**
     * 字段排序
     * @var array
     */
    protected $sort = [
        'add_time' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\AppProducts();
        
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add(){
        if ($this->request->isPost()) {
            $product_name = $this->request->post('product_name', '');
            $exist = $this->model->where(['product_name'=>$product_name])->find();
            if($exist){
                $this->error("保存失败，产品{$product_name}已存在");
            }
            try {
                $save = $this->model->save(['product_name'=>$product_name,'add_user'=>session('admin.username'),'add_time'=>date('Y-m-d H:i:s')]);
            } catch (\Exception $e) {
                $save = false;
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($product_id)
    {
        $row = $this->model->find($product_id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($product_id)
    {
        $this->checkPostRequest();
        $row = $this->model->find($product_id);;
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }


    
}
