<?php
namespace app\admin\controller;
use app\admin\controller\AuthBase;
use app\common\model\Admin as AdminModel;
use app\admin\controller\Upload;

class Banner extends AuthBase{
  public function _initialize(){
      parent::_initialize();
  }
  public function index(){
    $status = input('get.status');
    $condition = [];
    if($status){
        $condition['status'] = $status;
    }
    $banner_model = model('banner');
    $banner_list = $banner_model->where($condition)->order('created_at','desc')->paginate(10,false,['query'=>['status'=>$status]]);
    $this->assign('banner_list',$banner_list);
    return $this -> fetch();
  }
  public function create(){
    if(request()->isPost()){
      $data = input('post.');
      $banner_model = model('banner');
      $upload = new Upload();

      $result = $upload->sava(input('file.image'));
      if(!$result['error']){
        $image = $result['result']['url'];
        $data['image'] = $image;
      }
      $res = $banner_model->data($data)->save();
      if($res){
        $this->success('添加成功',url('admin/banner/index'),'',1);
      }else{
        $this->error('添加失败','','',1);
      }
    }else{
      return $this->fetch();
    }
  }
  public function update($id){
    $banner_model = model('banner');
    $resource_model = model('resource');
    if(request()->isPost()){
      $data = input('post.');
      if(input('file.image')){
        $banner_info = ($banner_model->find('id'));
        $old_image = $banner_info['image'];
        $upload = new Upload();
        $result = $upload->sava(input('file.image'));
        if(!$result['error']){
          $resource_model -> where('address',$old_image)->delete();
          $image = $result['result']['url'];
          $data['image'] = $image;
        }
      }
      $res = $banner_model->save($data,['id'=>$id]);
      if($res){
        $this->success('修改成功',url('admin/banner/index'),'',1);
      }else{
        $this->error('修改失败','','',1);
      }
    }else{
      $banner_info = $banner_model->find($id);
      $this->assign('banner_info',$banner_info);
      return $this->fetch();
    }
  }
  public function delete(){
    $id = input('post.id');
    $res = model('banner')->destroy($id);
    $banner_info = model('banner')->find($id);
    $old_image = $banner_info['image'];
    model('resource') -> where('address',$old_image)->delete();
    if($res){
      $this->success('删除成功','','',1);
    }else{
      $this->error('删除失败','','',1);
    }
  }
}
