<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
/**
 * 后台积分兑换码控制器
 */
class ScoreCode extends Home{
     /* 积分兑换码查询首页 */
	public function index(){     
      if($_POST){
			foreach ($_POST as $key=>$value){
				if($value){
					$map[]  = [$key,'like', '%'.$value.'%'];
				 }
			}
        }
        $map=isset($map)?$map:'';
        $res=getLists('ScoreCode',$map,10,'id desc',"");
	    $this->assign('res', $res);
		$this->meta_title="积分兑换码管理";
		$this->assign('meta_title', $this->meta_title);
	    return $this->fetch("scorecode/index"); 
	}


    /* 编辑积分兑换码 */
	public function edit($id){   
	    if($_POST){
		   $ScoreCode = new \app\admin\model\ScoreCode;
           $res=$ScoreCode->allowField(true)->validate(true)->save($_POST,['id' => $_POST['id']]);
	       if($res){
			   addUserLog("edit_scorecode",session_uid());
		      $this->success("更新成功！",cookie("__forward__"));
		   }else{
			  $error=$ScoreCode->getError()?$ScoreCode->getError():"更新失败！";
			  $this->error($error);
		   } 
	   }
	   else{
		 $map['id']=$id;
		 $info=db("ScoreCode")->where($map)->find();
	     $this->assign('info', $info);
		 unset($map);
		 $map['status']=1;
		 $list =db('score_type')->where($map)->order("id desc")->select(); 
	     $this->assign('list', $list);
		   cookie("__forward__",input('server.HTTP_REFERER'));
		 $this->meta_title="编辑积分兑换码";
		 $this->assign('meta_title', $this->meta_title);
	     return $this->fetch("scorecode/edit");
	   }
	}
	 /* 增加积分兑换码 */
	public function add($id=""){  
	   if($_POST){
		  $ScoreCode = new \app\admin\model\ScoreCode;
            // 过滤post数组中的非数据表字段数据
          $res=$ScoreCode->validate(true)->allowField(true)->save($_POST);
	      if($res){
			  addUserLog("add_scorecode",session_uid());
		      $this->success("新增成功！",cookie("__forward__"));
		  }else{
			  $error=$ScoreCode->getError()?$ScoreCode->getError():"新增失败！";
			  $this->error($error);
		  } 
	 }
	  else{
		if(input("type_id")){
			$info["type_id"]=input("type_id");
			 $this->assign('info', $info);
		}
		 unset($map);
		 $map['status']=1;
		 $list =db('score_type')->where($map)->order("id desc")->select(); 
	     $this->assign('list', $list);
		  $this->meta_title="新增积分兑换码";
		    cookie("__forward__",input('server.HTTP_REFERER'));
		  $this->assign('meta_title', $this->meta_title);
	      return $this->fetch("scorecode/edit");
	  }
	}
	 /* 删除积分兑换码*/
	public function del(){   
	    $id=input("id");
	    $map['id']=["in",$id];
		if(!$map["id"]){
			 $this->error("未选择数据！");
		}
		
		$res=db("scorecode")->where($map)->delete();
		
		if($res){
		   addUserLog("del_scorecode",session_uid());
		   $this->success("删除成功！");
		}else{
	           $this->error("删除失败！");
		}
	}
	
}
