<?php
namespace Admin\Model;
use Think\Model;
use Think\Storage;


class SliderModel extends Model{

    protected $_validate = array(
        array('title', 'require', '幻灯名称不能为空', self::MUST_VALIDATE , 'regex', self::MODEL_BOTH),
		array('cover_id', 'check_cover_id', '幻灯图片不能为空', self::MUST_VALIDATE , 'callback', self::MODEL_BOTH),
		array('link', 'require', '幻灯连接不能为空', self::MUST_VALIDATE , 'regex', self::MODEL_BOTH),
    );

    protected $_auto = array(
		array('title', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
		array('create_time', 'getCreateTime', self::MODEL_BOTH,'callback'),
        array('cover_id', 'get_cover_id', self::MODEL_BOTH,'callback'),
    );
	
    public function info($id, $field = true){
        $map = array();
        if(is_numeric($id)){
            $map['id'] = $id;
        }
		$info=$this->field($field)->where($map)->find();
		$info["picurl"]=get_cover($info["cover_id"],"path");
        return $info;
    }
	
    public function update(){
        $data = $this->create();
        if(!$data){
            return false;
        }
        if(empty($data['id'])){
            $res = $this->add();
        }else{
            $res = $this->save();
        }
        return $res;
    }
	
	public function remove($id = null){
		$map = array('id' => array('in', $id) );
		$list = $this->where($map)->field('pic')->select();
		foreach ($list as $key => $value) {
            Storage::unlink($value['pic']);
		}
		$res=$this->where($map)->delete();
		return $res;
	}

    protected function getCreateTime(){
        $create_time    =   I('post.create_time');
        return $create_time?strtotime($create_time):NOW_TIME;
    }

    protected function get_cover_id(){
        $cover_id    =   I('post.cover_id');
        $id = I('post.id');
        $picurl    =   str_replace((is_ssl()?'https://':'http://').$_SERVER['HTTP_HOST'].__ROOT__,'',I('post.picurl'));
        if(empty($cover_id) && empty($id)){
            return M('Picture')->data(array('url'=>$picurl,'status'=>1,'create_time'=>NOW_TIME))->add();
        }else{
            if(is_file(".".$picurl)){
                $data['path']=$picurl;
            }else{
                $data['url']=$picurl;
            }
            M('Picture')->where(array('id'=>$cover_id))->save($data);
            return $cover_id;
        }
    }

    protected function check_cover_id(){
        $cover_id    =   I('post.cover_id');
        $picurl    =   I('post.picurl');
        if(!empty($cover_id)){
            return true;
        }else{
            if(empty($picurl)){
                return false;
            }else{
                return true;
            }
        }
    }
}
