<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
class Index extends controller
{


    /**
     * 通配符转换
     * @param $str
     * @return string
     */
    public function wildcard($str)
    {
        $_str = '';
        for($i=0; $i<strlen($str); $i++){
            if($str{$i} == '*'){
                $str{$i} = '%';
            }elseif ($str{$i} == "?"){
                $str{$i} = '_';
            }
            $_str .=    $str{$i};           //后面一个字符的选择
        }

        return $_str;
    }

    /**
     * \斜线转义便于MySQL like查询
     * @param $str
     * @return string
     */
    public function slashEscap($str)
    {
        $_str = "";
        for ($i = 0; $i < strlen($str); $i++)
        {
            if($str{$i} == "\\"){
                $_str .= "\\\\";
            }else {
                $_str .= $str{$i};
            }
        }

        return $_str;
    }
    //获取用户的函数   (根据条件筛选出来)
    public function getuser(Request $request){
        if ($request->isPost()){
            $data = input();
            $group = isset($data['group']) ? $data['group']:'';          //组
            $user  = isset($data['user']) ? $data['user']:'';            //用户
            $order  = isset($data['order']) ? $data['order']:'';         //用户

            $groupArr = explode(",", $group);                             //使用字符串切割
            $user  = explode(",", $user);                              //使用字符串切割
            $where1=[];              //通配查询
            $whereuser['Login']=['in',$user];      //精准选择(用户成员)
            $str = "";
            $likeData = [];
           foreach ($groupArr as $key=>$value){
               if(strpos($value,'*') !== false || strpos($value,'?') !== false){//判断是否存在通配查询
                   $wildcardStr = $this->wildcard($value);
                   $str = $this->slashEscap($wildcardStr);
                   $likeData[] = ["like",$str];
                   $where1['group'] = $likeData;
                   unset($groupArr[$key]);
               }
           }
            if(count($likeData) == 1){
                $where1['group'] = ["like",$str];
            }

            $where['Group'] = ['in',$groupArr];       //精准选择(组的成员);
            $result = Db::connect("db_con2")->name('mt5_users')->where($where)->whereOr($where1)->whereOr($whereuser)->distinct(true)->select();

            $result1 = Db::name('order_progress')->where(['orig_order'=>$order])->select();  //筛选函数(当前跟踪的订单)

            //外层筛选出来之前做过的订单
            foreach ($result as $key => $value) {
                //自己选择的用户
                $result[$key]['LOGIN'] = $value["Login"];
                $result[$key]['NAME'] = $value['Name'];
                $result[$key]['GROUP'] = $value['Group'];
                $result[$key]['BALANCE'] = $value['Balance'];
                foreach ($result1 as $k => $v) {
                    if($value['Login']==$v['dest_login']){
                        unset($result[$key]);
                    }
                }

            }

            $result = array_values($result);          //重新组织数组的键值对


            if($result){
                
                return json(['code'=>'00','user'=>$result,'msg'=>'获得数据成功']);

            }else{

                return json(['code'=>'01','msg'=>'没有对应的数据']);
            }               

        }else{

            return json(['code'=>'01','msg'=>'请使用post方式访问']);

        }


    }


    //点击订单后获取到的信息
    public function getorder(Request $request){

        if ($request->isPost()){

            $data = input(); //获取订单的信息

            //获取deals表中的信息 判断订单是否平仓 entry为0是正  entry为1时是负
            $deals = Db::connect("db_con2")->query("select count(*) as 'num' from mt5_deals  WHERE PositionID = {$data['orderid']} group by entry ");

            $deal = array_column($deals,'num');
            if(!$deals || $deal['0'] != $deal['1']){
                return json(['code'=>'01','msg'=>'没有找到匹配的订单']);
            }

            //查询开仓信息
            $openResult = Db::connect("db_con2")->query("SELECT Price,Time FROM mt5_deals WHERE PositionID={$data['orderid']} and Time = (SELECT MIN(Time) FROM mt5_deals WHERE PositionID={$data['orderid']})")[0];

            //通过deals表查询盈利
            $earnings = Db::connect("db_con2")->query("SELECT SUM(Commission) as commission,SUM(Profit) as profit FROM mt5_deals WHERE PositionID={$data['orderid']}")[0];

            //查询关仓信息
            $closeResult = Db::connect("db_con2")->query("SELECT Price,Time,Login,PositionID,Symbol,Volume,PriceTP,PriceSL FROM mt5_deals WHERE PositionID={$data['orderid']} and Time = (SELECT MAX(Time) FROM mt5_deals WHERE PositionID={$data['orderid']})")[0];

            //获取订单的所有deal,orders
            $result =  Db::connect("db_con2")->query("select Deal as 'deal',`Order` from mt5_deals  WHERE PositionID = {$data['orderid']}");



            $getDeals = array_column($result,'deal');
            $order = array_column($result,'Order');

            if($closeResult && $result && $openResult){

                //发送set_current_postion 数据
                $send = ['orders'=>$order,'from'=>strtotime($openResult['Time'])-1,'to'=>strtotime($closeResult['Time'])+1,'login'=>$closeResult['Login'],'deals'=>$getDeals];

                $data = [
                    'OPEN_PRICE' => $openResult["Price"],
                    'OPEN_TIME' => $openResult["Time"],
                    'CLOSE_TIME' => $closeResult['Time'],
                    'CLOSE_PRICE' => $closeResult['Price'],
                    'LOGIN' => $closeResult['Login'],
                    'TICKET' => $closeResult['PositionID'],
                    'SYMBOL' => $closeResult['Symbol'],
                    'VOLUME' => $closeResult['Volume'],
                    'TP' => $closeResult['PriceTP'],
                    'SL' =>  $closeResult['PriceSL'],
                    'PROFIT' => $earnings['profit'],
                    'COMMISSION' => $earnings['commission'],
                    'send' => $send
                ];

                return json(['code'=>'00','data'=>$data,'msg'=>'获得数据成功']);

            }else{

                return json(['code'=>'01','msg'=>'没有找到匹配的订单']);
            }
        }else{

            return json(['code'=>'01','msg'=>'请使用post方式访问']);

        }

    }

    // 点击订单后查询函数(rollback)
    public function rollback_order(Request $request){
        if ($request->isPost()){

            $data = input(); //获取订单的信息

            $result = Db::name('order_progress')->where(['type'=>"insert","orig_order"=>$data['orderid'],'error_code'=>0])->select();                        //insert成功后插入的订单
            $result1 = Db::name('order_progress')->where(['type'=>"rollback","orig_order"=>$data['orderid']])->where('error_code','neq',0)->select();        //rollback失败后的订单
            $result2 = Db::name('order_progress')->where(['type'=>"retry","orig_order"=>$data['orderid']])->where('error_code','eq',0)->select();            //retry成功的订单
            $result = array_merge($result,$result1,$result2);               //对数据进行合并
            if($result){
                
                return json(['code'=>'00','data'=>$result,'msg'=>'获得数据成功']);

            }else{

                return json(['code'=>'01','msg'=>'暂无数据']);
            }
        }else{

            return json(['code'=>'01','msg'=>'请使用post方式访问']);

        }
    }



    // 点击订单后查询函数(retry)
    public function retry_order(Request $request){
        if ($request->isPost()){

            $data = input(); //获取订单的信息


           $result = Db::name('order_progress')->where(['type'=>"insert","orig_order"=>$data['orderid']])->where('error_code','neq',0)->select();              //insert失败的订单

            $result1 = Db::name('order_progress')->where(['type'=>"retry","orig_order"=>$data['orderid']])->where('error_code','neq',0)->select();               //retry失败的订单
            $result2 = Db::name('order_progress')->where(['type'=>"except_rollback","orig_order"=>$data['orderid']])->where('error_code','neq',0)->select();     //except_rollback失败的订单
            $result = array_merge($result,$result1,$result2);               //对数据进行合并
            if($result){

                return json(['code'=>'00','data'=>$result,'msg'=>'获得数据成功']);

            }else{

                return json(['code'=>'01','msg'=>'暂无数据']);
            }
        }else{

            return json(['code'=>'01','msg'=>'请使用post方式访问']);

        }
    }

    


    //确认密码函数(批量操作的时候需要)
    public function  querypassword(Request $request){
        if ($request->isPost()){


            $data = input();                                              //获取传递的信息
            $password = md5($data['password']);                           //获取加密后的密码

            //根据用户来选择数据
            if($data['nickname']=="普通管理员"){
                $result = Db::name('admin')->where(['id'=>1])->find();        //找到用户(获取原始的密码)
            }else{
                $result = Db::name('admin')->where(['id'=>2])->find();        //找到用户(获取原始的密码)
            }


            // 筛选出来的数据进行密码的匹配
            if($password==$result['password']){
                return json(['code'=>'00','msg'=>'请求数据成功']);
            }else{
                return json(['code'=>'01','msg'=>'密码填写有误']); 
            }
        }else{

            return json(['code'=>'01','msg'=>'请使用post方式访问']);

        }
    }



    //更新梯度函数(retry的时候进行查询)

    public function update_percentage(Request $request){
        if ($request->isPost()){

            $data = input();                                              //获取传递的信息
            $update_array =[];
            foreach ($data as $key => $value) {
                $result =  Db::connect("db_con2")->name('mt5_users')->where(['Login'=>$value])->find();
                $update_array[$value]= $result['Balance'];
            }
            if($update_array){
                return json(['code'=>'00','data'=>$update_array,'msg'=>'请求数据成功']);
            }else{
                return json(['code'=>'01','data'=>$update_array,'msg'=>'请求数据有误']);
            }
        }else{

            return json(['code'=>'01','msg'=>'请使用post方式访问']);
        }
    }


}
