<?php
/**
 * Copy Right IJH.CC
 * Each engineer has a duty to keep the code elegant
 * $Id$
 */

if(!defined('__CORE_DIR')){
    exit("Access Denied");
}

class Mdl_Staff_Staff extends Mdl_Table
{   
  
    protected $_table = 'staff';
    protected $_pk = 'staff_id';
    protected $_cols = 'staff_id,from,cate_id,name,mobile,passwd,face,orders,money,credits,comments,score1,score1.score3,haoping,chaping,zhongping,audit,loginip,lastlogin,clientip,dateline';

    public function staff($u, $l = 'staff_id') {
        $l = strtolower($l);
        switch ($l) {
            case 'staff_id':
                $field = 'staff_id';
                break;
            case 'mobile':
                $field = 'mobile';
                break;
            default:
                return false;
        }
        $sql = "SELECT * FROM " . $this->table($this->_table) . " WHERE " . $this->field($field, $u);

        if ($row = $this->db->GetRow($sql)) {
            $row = $this->_format_row($row);
        }
        return $row;
    }

    public function detail_by_mobile($mobile)
    {
        if(!$mobile = K::M('verify/check')->mobile($mobile)){
            return false;
        }
        $sql = "SELECT * FROM ".$this->table($this->_table)." WHERE ".$this->field('mobile', $mobile);
        if ($row = $this->db->GetRow($sql)) {
            $row = $this->_format_row($row);
        }
        return $row;        
    }

    public function update_mobile($staff_id, $mobile)
    {
        if(!$mobile = K::M('verify/check')->mobile($mobile)){
            $this->msgbox->add('手机号码不正确', 511);
            return false;
        }else if($a = $this->detail_by_mobile($mobile)){
            if($a['staff_id'] != $staff_id){
                $this->msgbox->add('手机号码已经存在', 512);
                return false;
            }
        }
        return $this->update($staff_id, array('mobile'=>$mobile), true);
    }

    protected function _format_row($row)
    {
        static $staff_from = null;
        if($staff_from === null){
            $staff_from = K::M('data/data')->staff_from();
        }
        $row['from_title'] = $staff_from[$row['from']];
        if($cate = K::M('staff/cate')->cate($row['cate_id'])){
            $row['cate_title'] = $row['title'];
        }
        return $row;
    }

    protected function _check($row, $staff_id=null)
    {
        if($row['passwd'] && !preg_grep('/[0-9a-f]{32}/', $row['passwd'])){
            if($staff_id && $row['passwd'] == '******'){
                unset($row['passwd']);
            }else{
                $row['passwd'] = md5($row['passwd']);
            }
        }
        if(isset($row['mobile'])){
            if($a = $this->detail_by_mobile($mobile)){
                if(empty($staff_id) || ($a['staff_id'] != $staff_id)){
                    $this->msgbox->add('手机号码已经存在', 511);
                }
            } 
        }
        return $row;
    }
    
    public function check_login(){        
        
        $a = explode('-',$_COOKIE['KT-STAFF_TOKEN']);
        
        $return = 0;
        
        
        if(!$id = intval($a[0])){
            $return = 1;
        }
        $m = $this->detail($id);

        if(!$m){
            $return = 1;
        }else if($this->create_token($m['staff_id'],$m['passwd']) != $_COOKIE['KT-STAFF_TOKEN']){
            $return = 1;
        }
        
        $r = array(
            '0' => $return,
            '1' => $m
        );
        return $r;
        
        
    }
    
    
    //生成TOKEN
    public function create_token($uid, $pwd)
    {
        $staff = strtoupper(md5($_SERVER['HTTP_USER_AGENT'].$uid.md5(__CFG::SECRET_KEY.$pwd.__IP,true)));
        $token = "{$uid}-KT{$staff}";
        return $token;
    }
    
    
     public function loginout(){

        $this->cookie->delete('STAFF_TOKEN');
        $this->tmpl = 'xiche/mcenter/login.html';

    }
    
    
    /**
     * 用户登录
     * @param   $u  staff_id/手机号
     * @param   $p  密码{明文密码}
     */
    public function login($u, $p, $l=null, $ismd5=false, $keep=false)
    {
        $passwd =$ismd5 ? $p : md5($p);

        if($l === null){
            if(K::M('verify/check')->mobile($u)){
                $l = 'mobile';
            }else{
                $l = 'staff_id';
            }
        }


        if(!$staff = K::M('staff/staff')->staff($u, $l)){
            $this->msgbox->add('手机号不存在!!',111);
            $this->msgbox->response();
        }else if($staff['passwd'] != $passwd){
            $this->msgbox->add('登录密码不正确!!',112);
            $this->msgbox->response();
        }else{
            $this->staff_id = $staff['staff_id'];
            $this->staff = $staff;
            $expire = $keep ? 2592000 : 0;
            $token = $this->create_token($this->staff_id, $passwd);
            $this->cookie->delete('STAFF_TOKEN');
            $this->cookie->set('STAFF_TOKEN', $token);
            K::M('staff/staff')->update($staff['staff_id'], array('lastlogin'=>__CFG::TIME, 'loginip'=>__IP), true);
            return $staff;
        }
        return false;       
    }
    
    
    

    
    
    

    //计算经纬度距离
    function getdistance($lng1,$lat1,$lng2,$lat2){  
        //将角度转为狐度
        $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2=deg2rad($lat2);
        $radLng1=deg2rad($lng1);
        $radLng2=deg2rad($lng2);
        $a=$radLat1-$radLat2;
        $b=$radLng1-$radLng2;
        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;

        if($s < 1000){
            $s = $s.'m';
        }else{
            $s = intval($s/1000).'.'.($s%1000).'km';
        }
        return $s;
    }
    

    public function updates($staff_id,$data,$checked=false)
    {
        return $this->db->update($this->_table, $data, self::field($this->_pk, $staff_id));
    }
}