<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Admin\Model;
use Think\Model;

/**
 * 文档基础模型
 */
class PromoteModel extends Model{

    const LEVEL_PRESIDENT = 1;
    const LEVEL_DEPARMENT = 2;
    const LEVEL_GROUP_LEADER = 3;
    const LEVEL_TEAM_MEMBER = 4;

    public static $levelArr = [
        self::LEVEL_PRESIDENT => '会长',
        self::LEVEL_DEPARMENT => '部门长',
        self::LEVEL_GROUP_LEADER => '组长',
        self::LEVEL_TEAM_MEMBER => '组员'
    ];

    /* 自动验证规则 */
    protected $_validate = array(

        array("account", "require", "请输入推广员账号!"),
        array('account', '6,15', '账号长度为6-15个字符', self::EXISTS_VALIDATE, 'length'),
        array('account','','渠道账号已存在',0,'unique',1),
        /* 验证密码 */
        array("password", "require", "请输入登录密码!"),
        array('password','6,16', "密码长度为6-16位字符", self::EXISTS_VALIDATE, 'length'),//密码长度不合法
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('password', 'think_ucenter_md5', self::MODEL_BOTH, 'function', UC_AUTH_KEY),
        array('create_time', 'getCreateTime', self::MODEL_INSERT,'callback'),
        array('total_money',  0, self::MODEL_INSERT),
        array('balance_coin', 0, self::MODEL_INSERT),
        array('promote_type', 1, self::MODEL_BOTH),
        array('referee_id', 0, self::MODEL_BOTH),
    );

    /**
     * 构造函数
     * @param string $name 模型名称
     * @param string $tablePrefix 表前缀
     * @param mixed $connection 数据库连接信息
     */
    public function __construct($name = '', $tablePrefix = '', $connection = '') {
        /* 设置默认的表前缀 */
        $this->tablePrefix ='tab_';
        /* 执行构造方法 */
        parent::__construct($name, $tablePrefix, $connection);
    }

    public function login($account,$password){
        $map['account'] = $account;
        /* 获取用户数据 */
        $user = $this->where($map)->find();

        $status = $this->checkStatus($user);
        if ($status != 1) {
            return $status;
        }

        /* 验证用户密码 */
        if(think_ucenter_md5($password, UC_AUTH_KEY) === $user['password']){
            $this->autoLogin($user); //更新用户登录信息
            return $user['id']; //登录成功,返回用户ID
        } else {
            return -2; //密码错误
        }
    }

    public function login_phone($user) {
        $status = $this->checkStatus($user);
        if ($status != 1) {
            return $status;
        }
        $this->autoLogin($user);
        return $user['id'];
    }

    public function checkStatus($user)
    {
        if (!is_array($user)) {
            return -1;
        }
        if ($user['status'] == 1) {
            return 1;
        } elseif ($user['status'] == 2) {
            return -3;
        } elseif ($user['status'] == 0) {
            return -4;
        }
        return -1;
    }
    
    public function register($reg_data){
        $data = array(
            'account'       => $reg_data['account'],
            'password'      => $reg_data['password'],
            'nickname'      => $reg_data['account'],
            'real_name'     => $reg_data['real_name'],
            'email'         => $reg_data['email'],
            'mobile_phone'  => $reg_data['mobile_phone'],
            'status'        => $reg_data['status'],
            'invite_code'   => $reg_data['invite_code']
        );
        if(C('PROMOTE_AUTO_AUDIT') == 1){$data['status'] = 1;}
        /* 添加用户 */
        if($this->create($data)){
            $uid = $this->add();
            return $uid ? $uid : 0; //0-未知错误,大于0-注册成功
        } else {
            return $this->getError(); //错误详情见自动验证注释
        }
    }
    public function promote_add($add_data=array()){
         if(empty($add_data['nickname'])){
            $add_data['nickname']=$add_data['account'];
         }

        $data = array(
            'account'       => $add_data['account'],
            'password'      => $add_data['password'],
            'nickname'      => $add_data['nickname'],
            'second_pwd'    => $add_data['second_pwd'],
            'real_name'     => $add_data['real_name'],
            'email'         => $add_data['email'],
            'idcard'        => isset($add_data['idcard']) ? $add_data['idcard'] : '',
            'status'        => $add_data['status'],
            'mobile_phone'  => $add_data['mobile_phone'],
            'bank_name'     => $add_data['bank_name'],
            'bank_card'     => $add_data['bank_card'],
            'status'        => 1,
            'parent_id'     => isset($add_data['parent_id']) ? $add_data['parent_id'] : 0,
            'parent_name'   => get_promote_name($add_data['parent_id']),
            'admin_id'      =>  isset($add_data['admin_id']) ? $add_data['admin_id'] : 0,
            'invite_code'   => $add_data['invite_code'],   
            'create_time'   => NOW_TIME,
            'ba_id'         => $add_data['ba_id'],
        );
        /* 添加用户 */
        if($this->create($data)){
            $uid = $this->add();
            return $uid ? $uid : 0; //0-未知错误,大于0-注册成功
        } else {
            return $this->getError(); //错误详情见自动验证注释
        }
    }


    /**
    *编辑子推广员
    */
    public function edit($data){

        $data_c = $this->create($data);
        if(empty($data['password'])){ 
            unset($data_c['password']);
        }
        elseif(!empty($data["old_password"])){
            if(!$this->verifyUser($data_c['id'],$data["old_password"])){
                return false;
            }
        }
        return $this->where("id=".$data_c['id'])->save($data_c);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'pid'             => $user['id'],
            'account'         => $user['account'],
            'nickname'        => $user['nickname'],
        );
        session('promote_auth', $auth);
        session('promote_auth_sign', data_auth_sign($auth));
        session_regenerate_id();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session('promote_auth', null);
        session('promote_auth_sign', null);
        session('game_divide_second_pwd', null);
        session_regenerate_id();
    }
    
    /**
     * 验证用户密码
     * @param int $uid 用户id
     * @param string $password_in 密码
     * @return true 验证成功,false 验证失败
     * @author huajie <banhuajie@163.com>
     */
    public function verifyUser($uid, $password_in){
        $password = $this->getFieldById($uid, 'password');

        if(think_ucenter_md5($password_in, UC_AUTH_KEY) === $password){
            return true;
        }
        return false;
    }
        /**
     * 验证用户二级密码
     * @param int $uid 用户id
     * @param string $password_in 密码
     * @return true 验证成功,false 验证失败
     * @author huajie <banhuajie@163.com>
     */
    public function verify_er_User($uid, $password_in){
        $password = $this->getFieldById($uid, 'second_pwd');

        if(think_ucenter_md5($password_in, UC_AUTH_KEY) === $password){
            return true;
        }
        return false;
    }
    

    /**
     * 创建时间不写则取当前时间
     * @return int 时间戳
     * @author huajie <banhuajie@163.com>
     */
    protected function getCreateTime(){
        $create_time    =   I('post.create_time');
        return $create_time?strtotime($create_time):NOW_TIME;
    }

    //检查账号是否存在
    public function checkAccount($account){
        $c_acc = $this->where(array('account'=>$account))->find();
        if(empty($c_acc)){return ture;}else{ return false;}
    }

    /**
     * 检测用户名是不是被禁止注册
     * @param  string $username 用户名
     * @return boolean          ture - 未禁用,false - 禁止注册
     */
    protected function checkDenyMember($username){
        return true; //TODO: 暂不限制,下一个版本完善
    }

    /**
     * 检测邮箱是不是被禁止注册
     * @param  string $email 邮箱
     * @return boolean       ture - 未禁用,false - 禁止注册
     */
    protected function checkDenyEmail($email){
        return true; //TODO: 暂不限制,下一个版本完善
    }

    /**
     * 检测手机是不是被禁止注册
     * @param  string $mobile 手机
     * @return boolean        ture - 未禁用,false - 禁止注册
     */
    protected function checkDenyMobile($mobile){
        return true; //TODO: 暂不限制,下一个版本完善
    }

    /**
     * 获取渠道等级
     * @param $account
     * @return int|string
     */
    public function get_level($promote_id){
        $map['id'] = $promote_id;
        $data = $this->where($map)->find();
        if(empty($data)){
            return '';
        }
        if($data['parent_id'] == 0) {
            return '1';
        }else{
            return 2;
        }
    }

    /**
     * 渠道平台币修改
     * @param $promote_account 渠道帐号
     * @param $num  平台币数量
     * @param $type 1:增加 2:收回
     */
    public function edit_promote_balance_coin($promote_id,$num,$type,$sid=0){
        //开启事务
        $this->startTrans();
        $map['id'] = $promote_id;
        $data = $this->where($map)->find();
        if($type == 1){
            $data['balance_coin'] += (int)$num;
            $res = $this->where($map)->save($data);
        }
        if($type == 2){
            $data['balance_coin'] -= (int)$num;
            if($data['balance_coin'] < 0){
                $this->error = "该用户平台币小于所要扣除的平台币!";
                $this->rollback();
                return false;
            }
            $res = $this->where($map)->save($data);
        }
        $rec = D('PromoteCoin')->record($promote_id,$sid,$num,$type);
        if($res && $rec){
            //事务提交
            $this->commit();
            return true;
        }else{
            //事务回滚
            $this->rollback();
            return false;
        }
    }
		
		
	/*
	 * 未审核推广员列表
	 * @return array    检查结果集
	 * @author 鹿文学
	 */
	public function checkPromote() {
		
		$list = $this->field('id,account')->where(array('status'=>0))->select();
		$type=300;
		if ($list[0]) {
			
			$list = D('check')->dealWithCheckList($type,$list);
			
			if (empty($list[0])) {return '';}
			
			foreach ($list as $k => $v) {
				$data[$k]['info'] = '推广员账号:'.$v['account'].',账号状态:未审核';
				$data[$k]['type'] = $type;
				$data[$k]['url'] = U('Promote/lists',array('promote_id'=>$v['id']));
				$data[$k]['create_time'] = time();
				$data[$k]['status']=0;
				$data[$k]['position'] = $v['id'];
			}
			return $data;
		}else {
			D('check')->dealWithCheckListOnNull($type);
			return '';
		}
		
	}
	
	/*
	 * 渠道总数
	 * @param  array    $map      条件数组
	 * @author 鹿文学
	 */
	public function total($map=array()) {
		
		$map['status'] = 1;
		
		return $this->where($map)->count();
		
	}
	
	
	/*
	 * 新渠道 按时间分组
	 * @param  array    $map      条件数组
	 * @param  string   $field	  字段别名
	 * @param  string   $group    分组字段名
	 * @author 鹿文学
	 */
	public function newsAdd($map=array(),$field='news',$group='time',$flag=1,$order='time')	{
		
		switch($flag) {
			case 2:{$dateform = '%Y-%m';};break;
			case 3:{$dateform = '%Y-%u';};break;
			case 4:{$dateform = '%Y';};break;
			case 5:{$dateform = '%Y-%m-%d %H';};break;
			default:$dateform = '%Y-%m-%d';
		}
		
		$map['status'] = 1;
		
		$user = $this->field('FROM_UNIXTIME(create_time, "'.$dateform.'") as '.$group.',group_concat(id) as id ,COUNT(id) AS '.$field)
					->where($map)
					->group($group)
					->order($order)
					->select();
		
		return $user;
		
    }

    public function getPromotersByLevel($level=1)
    {
        $result = [];
        $result = $this->field("*")->where("level={$level}")->select();
        foreach ($result as &$item) {
            $item['nickname'] = $item['account'] . ($item['nickname'] ? "({$item['nickname']})" : "");
        }
        return $result;
    }

    public function getPromotersByLevelOther($level=1)
    {

        $where['level'] =  $level;
        $userAuth = session('user_auth');
        // setPowerPromoteIds($where,'id');

        $offcialData = [0=>['id'=>0,'nickname'=>C('OFFICIEL_CHANNEL')]];

        $result = $this->field("*")->where($where)->select();
        foreach ($result as &$item) {
            $item['nickname'] = $item['account'] . ($item['nickname'] ? "({$item['nickname']})" : "");
        }

        if (in_array('0',explode(',',$where['id'][1]))||$userAuth['data_empower_type']==1) {
            $result = array_merge($offcialData,$result);
//            dump($result);die();
        }

        return $result;
    }

    public function parseListData($result)
    {
        //获取是否要隐藏重要信息
        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $parseData = array();
        foreach ($result as $key => $value) {
            $parseData[$key] = $value;
            $parseData[$key]['company_belong_str'] = getCompanyBlong($value['company_belong']);
            $parseData[$key]['company_relation_str'] = getCompanyRelation($value['company_relation']);
            $parseData[$key]['create_time'] = set_show_time($value['create_time']);
            $parseData[$key]['last_login_time'] = set_show_time($value['last_login_time']);
            $parseData[$key]['level_name'] = getPromoteLeverName($value['level']);
            $parseData[$key]['status_str'] = get_info_status($value['status'],3) ?:"待审核";
            $parseData[$key]['ver_status'] = get_info_status($value['ver_status'],42) ?:"未认证";
            $parseData[$key]['oa_associated_str'] = $value['oa_associated'] == 1 ? "已关联" : "未关联";
            $parseData[$key]['pay_amount'] = sum_promote_total_money($value['id']);
            
            
            if(!$show_data_power){
//                $parseData[$key]['account'] = encryptStr($parseData[$key]['account']);
                $parseData[$key]['mobile_phone'] = encryptStr($parseData[$key]['mobile_phone']);
//                $parseData[$key]['top_account'] = encryptStr($parseData[$key]['top_account']);
                
            }
            

        }
        return $parseData;
        
    }

    public function getPromotersByLevelResource($level)
    {

        if ($level) {
            $where['level'] =  $level;
        }

        $userAuth = session('user_auth');
        setPowerPromoteIds($where,'id');

        $offcialData = [0=>['id'=>0,'nickname'=>'江息网络']];

        $result = $this->field("*")->where($where)->select();
        foreach ($result as &$item) {
            $item['nickname'] = $item['account'] . ($item['nickname'] ? "({$item['nickname']})" : "");
        }

        if ((in_array('0',explode(',',$where['id'][1]))||$userAuth['data_empower_type']==1)) {
            $result = array_merge($offcialData,$result);
//            dump($result);die();
        }

        return $result;
    }


}