<?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_ver")
 */
class Ver extends AdminController
{

    use \app\admin\traits\Curd;

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

    protected $ver_status = [0=>'未上线',1=>'已上线'];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\AppVer();
        $this->assign('ver_status', $this->ver_status);
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add(){
        if ($this->request->isPost()) {
            $ver_class = $this->request->post('ver_class', '');
            $ver_name = $this->request->post('ver_name', '');
            $exist = $this->model->where(['ver_class'=>$ver_class])->find();
            if($exist){
                $this->error("保存失败，渠道{$ver_class}已存在");
            }
            try {
                $save = $this->model->save(['ver_name'=>$ver_name,'ver_class'=>$ver_class,'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($ver_id)
    {
        $model = $this->model;
        $row = $model->find($ver_id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $model->where(['ver_id'=>$ver_id])->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

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