<?php
/**
 * Created by PhpStorm.
 * User: 30868
 * Date: 2018/9/13
 * Time: 20:59
 */
namespace app\admin\controller;
use app\admin\controller\AuthBase;
use app\common\model\Admin as AdminModel;
use app\admin\controller\Upload;

class Project extends AuthBase
{
    protected $tag_model;
    protected $city_model;
    protected $catalog_model;
    protected $project_model;
    public function _initialize()
    {
        $this->project_model = model("project");
        $this->tag_model = model("Tags");
        $this->city_model = model("Citys");
        $this->catalog_model = model("Catalogs");
        parent::_initialize();
    }
    //活动列表
    public function index(){
      // $title = input('get.title','');
      // $city = input('get.city','');
      // $tags = input('get.tags','');
      // $catalogs = input('get.catalogs','');
      // $this->project_mode->where('title','like',"%".$title."%")
      //                   ->where(function($query,$tags){
      //                     $tag_arr = explode(',',$tags);
      //
      //                   });

      $title = input('get.title');
      $type = input('get.type');
      $catalog_id = input('get.catalog_id');
      $condition = [];
      if($title){
          $condition['title'] = ['like',"%".$title."%"];
      }
      if($type){
          $condition['type'] = $type;
      }
      if($catalog_id){
          $condition['catalog_id'] = $catalog_id;
      }
      $catalog_list = $this->catalog_model->order('sort','asc')->select();
      $this -> assign('catalog_list', $catalog_list);
      $project_list =
          $this->project_model
          ->where($condition)->order('created_at desc')
          ->paginate(10,false,['query'=>['title'=>$title,'type'=>$type,'catalog_id'=>$catalog_id]]);
      $this->assign('project_list',$project_list);
      return $this->fetch('');
    }
    // 添加项目
    public function create(){

      if (request()->isPost()) {
        // 引入上传类
        $upload = new Upload();
        $file = input('file.');
        $data = input('post.');
        $poster = '';
        $kf_qrcode = '';
        $banners = [];
        if($data['type']==2){
          $result = $upload->sava($file['kf_qrcode']);
          if(!$result['error']){
            $kf_qrcode = $result['result']['url'];
            $data['kf_qrcode'] = $kf_qrcode;
          }
        }
        $result = $upload->sava($file['poster']);
        if(!$result['error']){
          $poster = $result['result']['url'];
          $data['poster'] = $poster;
        }
        foreach ($file['banners'] as $name => $f) {
          $result = $upload->sava($f);
          if(!$result['error']){
            $banners[] = $result['result']['url'];
            $data['banners'] =  json_encode($banners);
          }
        }
        // $result =  $upload -> sava(input('file.banners'));
        //写入数据库
        // $data['description'] = htmlspecialchars($data['description']);
        $res = $this->project_model->data($data)->save();
        if($res){
          $this->success('添加成功','','',1);
        }else{
          $this->error('添加到数据库失败','','',1);
        }
      }else{
        $tag_list = $this->tag_model -> order('sort','asc') -> select();
        $this -> assign('tag_list', $tag_list);
        $catalog_list = $this->catalog_model->order('sort','asc')->select();
        $this -> assign('catalog_list', $catalog_list);
        $city_list = $this->city_model->order('sort','asc')->select();
        $this -> assign('city_list', $city_list);
        return $this->fetch();
      }

    }
    public function delete(){
      $id = input('post.id');
      $used = model('Orders')->where('pid',$id)->count();
      if($used>0){
        $this->error('该项目已有用户下单,不可删除！','','',1);
      }

      $res = model('project')->destroy($id);
      if($res){
        $this->success('删除成功','','',1);
      }else{
        $this->error('删除失败','','',1);
      }
    }
    // 修改项目
    public function updateProject($id){

      if (request()->isPost()) {
        // 引入上传类
        $id = input('post.id');
        $upload = new Upload();
        $file = input('file.');
        $data = input('post.');
        $data = array_merge(array_diff($data, array('id'=>$id)));
        $poster = '';
        $kf_qrcode = '';
        $banners = [];
        $project_info = $this->project_model -> find($id);

        $old_banners = json_decode($project_info['banners_native']);
        $old_poster = $project_info['poster'];
        $old_kf_qrcode = $project_info['kf_qrcode'];

//        $resource_model = model('resource');

        if($data['type']==2){
          if(input('file.kf_qrcode')){
            $result = $upload->sava(input('file.kf_qrcode'));
            if(!$result['error']){
//              $resource_model -> where('address',$old_kf_qrcode)->delete();
              $kf_qrcode = $result['result']['url'];
              $data['kf_qrcode'] = $kf_qrcode;
            }
          }
        }
        if(input('file.poster')){
          $result = $upload->sava(input('file.poster'));
          if(!$result['error']){
//            $resource_model -> where('address',$old_poster)->delete();
            $poster = $result['result']['url'];
            $data['poster'] = $poster;
          }
        }
        if(input('file.banners')){
          $file_banners = input('file.banners');
          foreach ($file_banners as $name => $f) {
            $result = $upload->sava($f);
            if(!$result['error']){
              $banners[] = $result['result']['url'];
            }
          }
          $data['banners'] =  json_encode(array_merge($banners,$old_banners));
        }

        // $result =  $upload -> sava(input('file.banners'));
        //写入数据库
        // $data['description'] = htmlspecialchars($data['description']);
        $res = $this->project_model->save($data,['id'=>$id]);
        if($res){
          $this->success('修改成功','','',1);
        }else{
          $this->error('修改失败','','',1);
        }
      }else{
        $project_info = $this->project_model->find($id);
        // return;
        $this->assign('project_info',$project_info);
        $value = $project_info->tags_id_str;
        $value = trim($value,'|');
        $tags = explode('|', $value);
        $this->assign('tags',$tags);
        $tag_list = $this->tag_model -> order('sort','asc') -> select();
        $this -> assign('tag_list', $tag_list);
        $catalog_list = $this->catalog_model->order('sort','asc')->select();
        $this -> assign('catalog_list', $catalog_list);
        $city_list = $this->city_model->order('sort','asc')->select();
        $this -> assign('city_list', $city_list);
        return $this->fetch();
      }
    }
    // 标签管理
    public function tags(){
        $title = input('get.name','');
        $tag_list = $this->tag_model->where('name','like',"%".$title."%") -> order('sort','asc')->paginate(15,false,['query'=>['name'=>$title]]);
        $this->assign("tag_list",$tag_list);
        return $this->fetch('');
    }
    public function addTag(){
        $data = array(
            'name' => trim(input('post.name')),
            'sort' => input('post.sort',0),
        );
        $validate = validate('Project');
        if(!$validate->scene('addTag')->check($data)){
            $this->error($validate->getError(),$_SERVER["HTTP_REFERER"],'',1);
        }else{
            $res = $this->tag_model->data($data)->save();
            if(!$res){
                $this->error('添加失败',$_SERVER["HTTP_REFERER"],'',1);
            }else{
                $this->redirect($_SERVER["HTTP_REFERER"]);
            }
        }
    }
    public function editTag($id){
        $this->assign('id',$id);
        $tag_info = $this->tag_model->where('id',$id)->find();
        $this->assign('tag_info',$tag_info);
        return $this->fetch();
    }
    public function updateTag(){
        $id = input('post.id');
        $data = array(
            'id' => $id,
            'name' => trim(input('post.name')),
            'sort' => input('post.sort',0)
        );
        $validate = validate('Project');
        if(!$validate->scene('updateTag')->check($data)){
            $this->error($validate->getError(),$_SERVER["HTTP_REFERER"],'',1);
        }else{
            $res = $this->tag_model->save($data,['id'=>$id]);
            if(!$res){
                $this->error('修改失败',$_SERVER["HTTP_REFERER"],'',1);
            }else{
                $this->redirect(url('admin/project/tags'));
            }
        }
    }
    public function deleteTag(){
      $id = input('post.id');
      $used = $this->project_model->where('tags','like',"%".'|'.$id.'|'."%")->count();
      if($used>0){
        $this->error('该标签已在项目中引用,不可删除！','','',1);
      }
      $res = model('tags')->destroy($id);
      if($res){
        $this->success('删除成功','','',1);
      }else{
        $this->error('删除失败','','',1);
      }
    }
//    城市管理
    public function citys(){
        $title = input('get.name','');
        $tag_list = $this->city_model->where('name','like',"%".$title."%") -> order('sort','asc')->paginate(15,false,['query'=>['name'=>$title]]);
        $this->assign("tag_list",$tag_list);
        return $this->fetch('');
    }
    public function addCity(){
        $data = array(
            'name' => trim(input('post.name')),
            'sort' => input('post.sort',0),
        );
        $validate = validate('Project');
        if(!$validate->scene('addTag')->check($data)){
            $this->error($validate->getError(),$_SERVER["HTTP_REFERER"],'',1);
        }else{
            $res = $this->city_model->data($data)->save();
            if(!$res){
                $this->error('添加失败',$_SERVER["HTTP_REFERER"],'',1);
            }else{
                $this->redirect($_SERVER["HTTP_REFERER"]);
            }
        }
    }
    public function editCity($id){
        $this->assign('id',$id);
        $tag_info = $this->city_model->where('id',$id)->find();
        $this->assign('tag_info',$tag_info);
        return $this->fetch();
    }
    public function updateCity(){
        $id = input('post.id');
        $data = array(
            'id' => $id,
            'name' => trim(input('post.name')),
            'sort' => input('post.sort',0)
        );
        $validate = validate('Project');
        if(!$validate->scene('updateTag')->check($data)){
            $this->error($validate->getError(),$_SERVER["HTTP_REFERER"],'',1);
        }else{
            $res = $this->city_model->save($data,['id'=>$id]);
            if(!$res){
                $this->error('修改失败',$_SERVER["HTTP_REFERER"],'',1);
            }else{
                $this->redirect(url('admin/project/citys'));
            }
        }
    }
    public function deleteCity(){
      $id = input('post.id');
      $used = $this->project_model->where('city',$id)->count();
      if($used>0){
        $this->error('该城市已在项目中引用,不可删除！','','',1);
      }

      $res = model('citys')->destroy($id);
      if($res){
        $this->success('删除成功','','',1);
      }else{
        $this->error('删除失败','','',1);
      }
    }
    // 分类管理
    public function catalogs(){
        $title = input('get.name','');
        $tag_list = $this->catalog_model->where('name','like',"%".$title."%") -> order('sort','asc')->paginate(15,false,['query'=>['name'=>$title]]);
        $this->assign("tag_list",$tag_list);
        return $this->fetch('');
    }
    public function addCatalogs(){
      if (request()->isPost()) {
        $data = array(
            'name' => trim(input('post.name')),
            'sort' => input('post.sort',0),
            'poster' => input('file.poster')
        );
        $validate = validate('Project');
        if(!$validate->scene('addCatalogs')->check($data)){
            $this->error($validate->getError(),$_SERVER["HTTP_REFERER"],'',1);
        }else{
            $upload = new Upload();
            $result =  $upload -> sava(input('file.poster'));
            if($result['error']){
                $this->assign('msg', $result['error']);
                return view();
            }
            $data['poster'] = $result['result']['url'];
            $res = $this->catalog_model->data($data)->save();
            if(!$res){
                $this->error('添加失败',$_SERVER["HTTP_REFERER"],'',1);
            }else{
                $this->success('添加成功',$_SERVER["HTTP_REFERER"],'',1);
            }
        }
      }else{
        return $this->fetch();
      }
    }
    public function editCatalogs($id){
        $this->assign('id',$id);
        $tag_info = $this->catalog_model->where('id',$id)->find();
        $this->assign('tag_info',$tag_info);
        return $this->fetch();
    }
    public function updateCatalogs(){
        $id = input('post.id');
        $data = array(
            'id' => $id,
            'name' => trim(input('post.name')),
            'sort' => input('post.sort',0)
        );
        $validate = validate('Project');
        if(!$validate->scene('updateTag')->check($data)){
            $this->error($validate->getError(),$_SERVER["HTTP_REFERER"],'',1);
        }else{
            if(input('file.poster')){
              //            上传封面到七牛云
              $upload = new Upload();
              $result =  $upload -> sava(input('file.poster'));
              if($result['error']){
                  $this->assign('msg', $result['error']);
                  return view();
              }
              // 将资源目录该图的引用设为0
//              $resource_model = model('Resource');
//              $res = $resource_model->where('address',input('post.old_poster'))->setDec("use_num");
              $data['poster'] = $result['result']['url'];
            }
            $res = $this->catalog_model->save($data,['id'=>$id]);
            if(!$res){
                $this->error('修改失败',$_SERVER["HTTP_REFERER"],'',1);
            }else{
                $this->redirect(url('admin/project/catalogs'));
            }
        }
    }
    public function deleteCatalog(){
      $id = input('post.id');
      $used = $this->project_model->where('catalog_id',$id)->count();
      if($used>0){
        $this->error('该分类下有项目,不可删除！','','',1);
      }
//      $catalog_info = model('catalogs')->find($id);
//      $old_image = $catalog_info['poster'];
//      model('resource') -> where('address',$old_image)->delete();
      $res = model('catalogs')->destroy($id);
      if($res){
        $this->success('删除成功','','',1);
      }else{
        $this->error('删除失败','','',1);
      }
    }



    // 处理删除某一张bannner图
    public function deleteBanners(){
      $id = input('post.id');
      $address = input('post.address');

//      $resource_model = model('resource');
//      $del_res = $resource_model -> where('address',$address)->delete();

      $project_info = $this->project_model -> find($id);
      $banners = json_decode($project_info['banners_native']);
      $new_banners = array_merge(array_diff($banners, array($address)));
      $up_res = 0;
      if($new_banners!=$banners){
      $up_res = $this->project_model -> save([
          'banners'  => json_encode($new_banners)
      ],['id' => $id]);
      }
      if($up_res){
        return array(
          'success' => '成功删除该图',
          'data' => input('post.'),
          'old_banners' => $banners,
          'new_banner' => $new_banners,
//          'del_res' => $del_res
        );
      }else{
        return array(
          'error' => '删除失败，该图片不可能已经被删除',
          'data' => input('post.'),
          'old_banners' => $banners,
          'new_banner' => $new_banners,
//          'del_res' => $del_res
        );
      }


    }
}
