<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 机器人相关
 */
class Robot extends MY_Controller{
    public $postBaseData = array('lid' => 1, 'sid' => 1);
    public $urlLogin = '';
    public $urlBase  = '';
    public $uid = 0;
    public $type = 0;
    public $levelId = 0;
    public $money = 0;
    public function __construct()
    {
        date_default_timezone_set("Asia/Shanghai");
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->database();
        $this->urlLogin = $this->config->item('officialBaseUrl').'/api/login.php';
        $this->urlBase = $this->config->item('officialUrl');
    }

    public function Main(){
        set_time_limit(0);
        $robot = $this->GetRobot();
        var_dump(date('Ymd-H:i:s'),$robot);
        if(empty($robot)){
            var_dump('false');
            return false;
        }
        foreach ($robot as $ro){
            $this->uid = $ro['uid'];
            $this->UpdateRobot($this->uid);
            $this->type = $ro['type'];
            // 登录
            $loginData = $this->Login($ro);
            $spins = intval($loginData['spins']);
            $this->levelId = intval($loginData['levelId']);
            /*// 追加体力
            if($this->type == 1){
                $addSpin = $this->AddSpin(20);
                $spins = intval($addSpin['spins']);
            }else if($this->type == 2){
                $addSpin = $this->AddSpin(30);
                $spins = intval($addSpin['spins']);
            }
            // 大转盘
            $turnData = $this->Turn();
            if($turnData['code'] == 1){
                $this->Turn(false);
            }
            */
            // 老虎机部分
            while ($spins>0){
                $slot = $this->Solt($this->levelId);
                if($slot['code'] == 1){
                    $slot = $slot['data'];
                    switch ($slot['type']){
                        case 3:
                            $rank = mt_rand(0,100);
                            if($rank <33){
                                break;
                            }
                            $toUid = $slot['stealInfo']['toUid'];
                            $this->Steal($toUid);
                            $this->OverSteal($toUid);
                            break;
                        case 4:
                            $rank = mt_rand(0,100);
                            if($rank <33){
                                break;
                            }
                            $toUid = $slot['attackInfo']['toUid'];
                            $attckObject = [];
                            foreach ($slot['attackInfo']['element'] as $a){
                                if($a['level'] > 0){
                                    $attckObject[] = $a['id'];
                                }
                            }
                            $optId = array_rand($attckObject,1);
                            $this->Attack($toUid,$attckObject[$optId]);
                            break;
                    }
                    $spins = intval($slot['curSpins']);
                }else{
                    $spins = $spins - 1;
                }
                sleep(3);
            }
            // 普通型先开矿
            if($this->type == 0){
                $this->Mining();
            }

            $while = true;
            while ($while){
                $while = false;
                // 建造部分
                $build = $this->GetLevelConfig();
                $build = $build['data']['buildConfig'];
                $upLevelObject = [];
                $element = $this->getLandDatas();
                if($element['code'] == 1){
                    $element = $element['data']['element'];
                    $leveId = $element['data']['levelId'];
                }else{
                    break;
                }
                $lNum = 0;
                foreach ($element as $row){
                    if($row['level'] < 5){
                        $do = 0;
                        if($row['status'] == 1){
                            $do = 1;
                        }
                        $upLevelObject[] = ['optId'=>$row['id'],'level'=>intval($row['level']),'levelNum'=>5-intval($row['level'])+$do];
                        $lNum += intval($row['level']);
                    }else if($row['status'] == 1){
                        $upLevelObject[] = ['optId'=>$row['id'],'level'=>intval($row['level']),'levelNum'=>5-intval($row['level'])+1];
                        $lNum += intval($row['level']);
                    }else{
                        $lNum += 5;
                    }
                }

                $maxLevel = $this->getLevelMax();
                if($leveId > $maxLevel || ($leveId == $maxLevel -1 && $lNum>=24)){
                    break;
                }

                // 获取最新钱的总值
                $userAssetsInfo = $this->GetMoney();
                $this->money = intval($userAssetsInfo['data']['money']);
                $flag = true;
                foreach ($upLevelObject as $key=>$row){
                    for ($i=0;$i<$row['levelNum'];$i++){
                        $price = $build[$row['optId']-1][$row['level']+$i];
                        if($this->money > $price){
                            $levelData = $this->UpLevel($row['optId']);
                            if($levelData['code'] != 1) {
                                $flag = false;
                                break;
                            }
                            $this->money = intval($levelData['data']['lastCoins']);
                        }else{
                            break;
                        }
                    }
                    if($key+1 == count($upLevelObject) && $flag){
                        $Reward = $this->LevelReward();
                        if($Reward['code'] == 1) {
                            $while = true;
                        }else{
                            $while = false;
                        }
                    }
                }
            }
            // 平衡型开矿
            if($this->type == 1){
                $this->Mining();
            }

            // 移除richesKing
            $this->deleteKing();
        }

        var_dump("robot run all");
    }

    /**
     * 等级奖励
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 17:37
     * Description:
     */
    public function LevelReward(){
        $post = ['uid'=>$this->uid,'act'=>'levelReward','mod'=>'Level'];
        return $this->MakeCurl($post);
    }

    /**
     * 追加体力
     * @param $spins
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 16:57
     * Description:
     */
    public function AddSpin($spins){
        $post = ['uid'=>$this->uid,'act'=>'actionUser','mod'=>'User','spins'=>$spins,'frombg'=>1];
        return $this->MakeCurl($post);
    }

    /**
     * 获取金币
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 16:48
     * Description:
     */
    public function GetMoney(){
        $post = ['uid'=>$this->uid,'act'=>'getMoney','mod'=>'User'];
        return $this->MakeCurl($post);
    }

    /**
     * 获取建造价格
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 14:53
     * Description:
     */
    public function GetLevelConfig(){
        $post = ['uid'=>$this->uid,'act'=>'getConfig','mod'=>'User'];
        return $this->MakeCurl($post);
    }

    /**
     * 开矿
     * Created by: Owen
     * Created on: 2019/6/19 14:05
     * Description:
     */
    public function Mining(){
        if($this->levelId < 2){
            return false;
        }
        $mining = $this->getMining();
        if($mining['code'] == 1)
            $mining = $mining['data'];
        $this->getMiningReward($mining['offline']);
        foreach ($mining['islandLevel'] as $k=>$a){
            $flag = true;
            $num = 5-$a;
            while ($flag && $num){
                $UpData = $this->UpMining($k);
                if($UpData['code'] != 1){
                    $flag = false;
                }
                $num--;
            }
        }
    }

    /**
     * 获取矿工信息
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 14:39
     * Description:
     */
    public function getMining(){
        $post = ['uid'=>$this->uid,'act'=>'getMiningInfo','mod'=>'Mining'];
        return $this->MakeCurl($post);
    }

    /**
     * 领取矿工收益
     * @param $coins
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 14:39
     * Description:
     */
    public function getMiningReward($coins){
        $post = ['uid'=>$this->uid,'act'=>'receiveUserIncome','mod'=>'Mining','coins'=>$coins];
        return $this->MakeCurl($post);
    }

    /**
     * 升级矿工
     * @param $levelId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 14:39
     * Description:
     */
    public function UpMining($levelId){
        $post = ['uid'=>$this->uid,'act'=>'UpdateMining','mod'=>'Mining','levelId'=>$levelId];
        return $this->MakeCurl($post);
    }

    /**
     * 老虎机
     * @param $leveId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 9:50
     * Description:
     */
    public function Solt($leveId){
        $post = ['uid'=>$this->uid,'act'=>'getShowSlot','mod'=>'Slot','levelId'=>$leveId,'multiple'=>1];
        return $this->MakeCurl($post);
    }

    /**
     * 偷取
     * @param $toUid
     * Created by: Owen
     * Created on: 2019/6/19 10:10
     * Description:
     */
    public function Steal($toUid){
        $optId = [0,1,2];
        foreach ($optId as $value){
            $post = ['uid'=>$this->uid,'act'=>'levelStealOperation','mod'=>'Level','toUid'=>$toUid,'optId'=>$value,'bet'=>1];
            $temp = $this->MakeCurl($post);
        }
    }

    /**
     * 结束偷取
     * @param $toUid
     * @return mixed
     * Created by: Owen
     * Created on: 2019/7/17 13:52
     * Description:
     */
    public function OverSteal($toUid){
        $post = ['uid'=>$this->uid,'act'=>'overStealOperation','mod'=>'Level','toUid'=>$toUid];
        return $this->MakeCurl($post);
    }

    /**
     * 攻击
     * @param $toUid
     * @param $optId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 10:42
     * Description:
     */
    public function Attack($toUid,$optId){
        $post = ['uid'=>$this->uid,'act'=>'levelAttackOperation','mod'=>'Level','toUid'=>$toUid,'bet'=>1,'optId'=>$optId];
        return $this->MakeCurl($post);
    }

    /**
     * 获取建造价格
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 12:26
     * Description:
     */
    public function LevelConfig(){
        $post = ['uid'=>$this->uid,'act'=>'getConfig','mod'=>'User'];
        return $this->MakeCurl($post);
    }

    /**
     * 升级建筑
     * @param $optId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 12:25
     * Description:
     */
    public function UpLevel($optId){
        $post = ['uid'=>$this->uid,'act'=>'levelOperation','mod'=>'Level','optId'=>$optId];
        return $this->MakeCurl($post);
    }

    /**
     * 大转盘
     * @param bool $type
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/19 16:08
     * Description:
     */
    public function Turn($type = true){
        if($type){
            $post = ['uid'=>$this->uid,'act'=>'slotTurntable','mod'=>'Slot','type'=>2];
        }else{
            $post = ['uid'=>$this->uid,'act'=>'confirmTurntable','mod'=>'Slot'];
        }
        return $this->MakeCurl($post);
    }

    /**
     * 登录获取最新数据
     * @param $param
     * @return int
     * Created by: Owen
     * Created on: 2019/6/18 20:23
     * Description:
     */
    public function Login($param){
        $sign = base64_encode($param['mac'].'_superant');
        $post = ['mobile_request'=>$sign,'device'=>'Android','isRobot'=>1];
        $returnData = $this->MakeCurl($post,$this->urlLogin);
        return $returnData;
    }

    /**
     * 建筑情况
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/29 16:35
     * Description:
     */
    public function getLandDatas(){
        $post = ['uid'=>$this->uid,'toUid'=>$this->uid,'act'=>'getLandDatas','mod'=>'Level'];
        return $this->MakeCurl($post);
    }

    /**
     * 最大等级
     * @return int
     * Created by: Owen
     * Created on: 2019/6/29 16:39
     * Description:
     */
    public function getLevelMax(){
        $post = ['uid'=>$this->uid,'act'=>'getLevelConfig','mod'=>'Config','frombg'=>1,'page'=>1,'page_size'=>1000];
        $retData = $this->MakeCurl($post);
        $list = $retData['data'];
        $maxLevel = 0;
        foreach ($list as $row){
            if($row['levelId'] >$maxLevel)
                $maxLevel = intval($row['levelId']);
        }
        return $maxLevel;
    }

    public function deleteKing(){
        $post = ['uid'=>$this->uid,'act'=>'deleteKing','mod'=>'User'];
        return $this->MakeCurl($post);
    }

    /**
     * 获取机器人
     * @param $param
     * @return array
     * Created by: Owen
     * Created on: 2019/6/18 20:14
     * Description:
     */
    public function GetRobot(){
        $time = date('H');
        $robot = [];
        if($time>=20 && $time<22){
            $robot = $this->GetRobotByPro(0,1);
        }
        if(($time>=11 && $time<13))  {
            $robot = $this->GetRobotByPro(1,1);
        }
        if($time>=15 && $time<17){
            $robot = $this->GetRobotByPro(1,2);
        }
        if($time>=9 && $time<11){
            $robot = $this->GetRobotByPro(2,1);
        }
        if($time>13 && $time<15){
            $robot = $this->GetRobotByPro(2,2);
        }
        if($time>=18 && $time<20){
            $robot = $this->GetRobotByPro(2,3);
        }
        return $robot;
    }

    public function GetRobotByPro($type,$times){
        $date = date('Y-m-d');
        $sql   = "SELECT * FROM t_robot WHERE is_run=1 AND type={$type} ORDER BY RAND()";
        $temp = $this->GetRobotBySql($sql);
        $count = count($temp);
        foreach ($temp as $key=>$row){
            if($row['lastTime'] == $date && $row['times'] == $times){
                unset($temp[$key]);
            }
        }
        $count = floor($count/20);
        $robot = [];
        $temp = array_filter($temp);
        sort($temp);
        shuffle($temp);
        for ($i=0;$i<$count;$i++){
            if(empty($temp[$i])){
                continue;
            }else{
                $robot[] = $temp[$i];
            }
        }
        return $robot;
    }

    public function GetRobotBySql($sql){
        $robot = [];
        $ret= $this->db->query($sql);
        foreach ($ret->result_array() as $value){
            $robot[] = $value;
        }
        return $robot;
    }

    public function UpdateRobot($uid){
        $date = date('Y-m-d');
        $sql   = "update t_robot set lastTime='{$date}',times=times+1 where uid={$uid} limit 1";
        $this->db->query($sql);
    }

    /**
     * 生成机器人
     * @param $post
     * @return int
     * Created by: Owen
     * Created on: 2019/6/18 18:51
     * Description:
     */
    public function MakeRobot($type = 0){
        $is_run = 1;
        $mac = 100000000000;
        // 查询最大值
        $tb  = otable::Robot();
        $sql = "SELECT MAX(id) as id FROM {$tb} LIMIT 1";
        $row = oo::commonOprDb('games')->getOne($sql,1);
        if(!empty($row)){
            $mac += intval($row['id']);
        }
        $mac = str_split($mac,2);
        $mac = implode(':',$mac);
        $sign = base64_encode($mac.'_superant');
        $post = ['mobile_request'=>$sign,'device'=>'Android'];
        $returnData = $this->MakeCurl($post,$this->urlLogin);
        $this->uid = $returnData['uid'];
        $time = time();
        $insertSql = "INSERT INTO {$tb} SET uid={$returnData['uid']},mac='{$mac}',type={$type},is_run={$is_run},created_at={$time}";
        $ret = oo::commonOprDb('games')->query($insertSql);
        $this->EditInfo();
        return $ret?$ret:0;
    }

    public function EditInfo(){
        $tb = otable::RobotInfo();
        $row = oo::commonOprDb('slavedb')->getOne("SELECT avatar FROM {$tb} WHERE avatar != \"\" OR avatar != NULL ORDER BY RAND() LIMIT 1",1);
        $s_picture = $this->config->item('base_url').'public/avatar/'.$row['avatar'];
        $row = oo::commonOprDb('slavedb')->getOne("SELECT name FROM {$tb} WHERE name != \"\" OR name != NULL ORDER BY RAND() LIMIT 1",1);
        $nick = $row['name'];
        $u_flag = mt_rand(1,10);
        $post = ['uid'=>$this->uid,'act'=>'modifyInfo','mod'=>'User','nick'=>$nick,'s_picture'=>$s_picture,'u_flag'=>$u_flag];
        return $this->MakeCurl($post);
    }

    public function MakeRobotRule(){
        $arr = [20,50,10];
        foreach ($arr as $key=>$row){
            for ($i=0;$i<$row;$i++){
                //$this->MakeRobot($key);
            }
        }
        $tb = otable::Robot();
        $sql   = "update {$tb} set times=0 where 1";
        oo::commonOprDb('games')->query($sql);
    }

    /**
     * 访问控件
     * @param $post
     * @return mixed
     * Created by: Owen
     * Created on: 2019/6/18 17:57
     * Description:
     */
    public function MakeCurl($post,$url = ""){
        $posts = $this->postBaseData;
        if($url === ""){
            $url = $this->urlBase;
        }
        foreach ($post as $key=>$value){
            $posts[$key] = $value;
        }
        $retData = $this->curl->req($url, $posts);
        $this->debug(['uid'=>$this->uid,'posts'=>$posts,'retData'=>$retData],$this->uid.'.log');
        return json_decode($retData,true);
    }

    /**
     * 写日志-无大小限制-适合大型日志
     * @param $params
     * @param string $filename
     * @return bool|int
     * Created by: Owen
     * Created on: 2019/6/18 11:54
     * Description:
     */
    public function debug($params, $filename='log.txt')
    {
        $ymd = date('Ymd');
        $dir = "./deBUG/robot/"."{$ymd}/";
        if (!is_dir($dir))
        {
            $old = umask(0);
            mkdir($dir,0775 , true);
            umask($old);
        }
        $filepath = "{$dir}{$filename}";
        $str = is_array($params) ? json_encode($params) : $params;
        return file_put_contents($filepath,"{$str} \n", FILE_APPEND);
    }


    //------------------------------------------------------------------------------------------------------------------

    public function showRobot($page = 0){
        $this->load->library('pagination');
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $posts['page'] = $page/10;
        $title = ['机器人ID','用户ID','设备ID','类型：0普通，1平衡，2激进','启动状态：0关闭，1启动','创建时间'];
//        $ret = $this->db->query('SELECT count(*) as count FROM t_robot');
//        $ret = $ret->result_array();
        $tb  = otable::Robot();
        $ret = oo::commonOprDb('slavedb')->getOne("SELECT count(*) as count FROM {$tb}",1);
        $data['total'] = $ret['count'];
        $start = ($page/10 -1)*10;
//        $ret= $this->db->query("SELECT * FROM t_robot LIMIT {$start},10");
//        $arr = $ret->result_array();
        $arr =  oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY id DESC LIMIT {$start},10",1);
        foreach ($arr as $value){
            $value['created_at'] = date('Y-m-d H:i:s',$value['created_at']);
            $robot[] = $value;
        }

        if(empty($robot)){
            $list = [];
        }else{
            $list = $robot;
        }

        $data['title'] = $title;
        $data['list'] = $list;
        $data['page'] = $posts['page'];

        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#robot/showRobot');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;

        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;

        $this->load->view('robot/showRobot', $data);
    }

    public function actionRobot(){
        $postData = $this->input->post();
        $data = json_decode($postData['data'],true);
        $tb = otable::Robot();
        foreach ($data as $row){
            $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET uid={$row['uid']},mac='{$row['mac']}',type={$row['type']},is_run={$row['is_run']} WHERE id={$row['id']}");
        }
        if(!$ret){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function actionAdd(){
        for ($i=10;$i--;){
            $ret = $this->MakeRobot();
        }
        if($ret == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }
}