<?php
// 游戏默认分成比例模板
namespace Admin\Controller;

class CompanySystemRatioController extends AdminController
{

    private $api = "http://admin.wmtxkj.cn/index.php?g=Api&m=CpJuheCompany&a=ratioIndex";

    public function _initialize()
    {
        $this->admininfo = $_SESSION['onethink_admin']['user_auth'];
        parent::_initialize();
    }

    //比例类型 0-内团 1-外团 2-分发联盟 3上游游戏 4聚合比例
    private $checkRatio = [0,1,2,3,4];

    public function index()
    {
        $params = I('get.');
        $page = $params['p'] ? intval($params['p']) : 1;
        $row = $params['row'] ? intval($params['row']) : 10;
        //权限分配
        if(!IS_ROOT){
            $this->OpAuthList= getModuleControllerAuth();
        }

        $map = [];



        $data = M("game_ratio_mould","tab_")->where($map)->select();

        $handleData=[];
        $handleData = $this->getAggregateData();

        foreach ($data as $key => $value) {
            $handleData[$value['relation_game_id']][$value['company_belong']][] = ['turnover'=>"0.00",'ratio'=>$value['ratio'],'instanceof'=>1];

            $handleData[$value['relation_game_id']][$value['company_belong']]=array_merge($handleData[$value['relation_game_id']][$value['company_belong']],json_decode($value['turnover_ratio'],true)??[]);
        }

        $handleData = $this->getCpGameRatio($handleData);
        $data = $this->handleRatio($handleData);

        $checkData = $handleData;

//        dump($data);die();

        $gameData = M("game","tab_")->field("original_package_name,relation_game_name game_name,game_type_name,relation_game_id game_id")
            ->where($map)
            ->group("original_package_name")
            ->select();
        $gameOriginData = M("game","tab_")->field("original_package_name,relation_game_name game_name,relation_game_id")->where($map)->group("relation_game_id")->select();
        //类型区分
        $handleGameData = [];
        foreach ($gameData as $key => $value) {
            if ($value['game_type_name']) {
                $handleGameData[$value['game_type_name']][] = $value;
            }
        }
        //游戏原包名区分
        $handleOriginData = [];
        foreach ($gameOriginData as $key => $value) {
            if ($value['original_package_name']) {
                $handleOriginData[$value['original_package_name']][] = $value;
            }
        }

        //将比例打进游戏中
        foreach ($handleOriginData as $key => $value) {
            foreach ($value as $k => $v) {
                $handleOriginData[$key][$k]['ratio_data'] =  $data[$v['relation_game_id']];

            }
        }

        //处理数据
        $data = [];
        foreach ($handleGameData as $key => $value) {

            $handleData = [];

            foreach ($value as $k => $v) {
//                unset($handleGameData[$key][$k]['original_package_name']);
                $handleGameData[$key][$k]['game_data'] =  $handleOriginData[$v['original_package_name']];

            }
            $handleData['game_type'] = $key;
            $handleData['data'] = $handleGameData[$key];
            $data[] = $handleData;

        }
//        dump($data);die();
        foreach ($data as $key => $value) {

            foreach ($value['data'] as $k => $v) {

                if (!$v['game_data']) {
                    $data[$key]['data'][$k]['row'] = 1;
                    $data[$key]['row'] += 1;
                }

                foreach ($v['game_data'] as $vk => $vv) {
                    $data[$key]['data'][$k]['game_data'][$vk]['row'] = $vv['ratio_data']?count($vv['ratio_data']):1;
                    $data[$key]['data'][$k]['row'] += $vv['ratio_data']?count($vv['ratio_data']):1;
                    $data[$key]['row'] += $vv['ratio_data']?count($vv['ratio_data']):1;

//                    if (!$vv['ratio_data']) {
//                        $data[$key]['data'][$k]['game_data'][$vk]['row']=1;
//                    }

                    foreach($vv['ratio_data'] as $vvk=>$vvv) {
                        if (count($data[$key]['data'][$k]['game_data'][$vk]['ratio_data']) == 1) {
                            $data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk]['turnover'] = '无阶梯';
                            break;
                        } else {

                            if ($vvv['is_equal'] != 1) {

                                if (($data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+1]['turnover'] == $vvv['turnover'] && !$data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+2]['turnover'])
                                ||!($data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+1]['turnover'])) {
                                    $end = '∞';
                                } elseif($data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+1]['turnover'] == $vvv['turnover'] && $data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+2]['turnover']) {
                                    $end = floatval($data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+2]['turnover']);
                                } else {
                                    $end = floatval($data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk+1]['turnover']);
                                }

                                $data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk]['turnover']
                                    = floatval($vvv['turnover']).($vvv['instanceof']==1?'<=':'<').'月流水'.
                                    ('<').
                                    ($end);
                            } else {

                                if ($vvv['instanceof'] != 1) {
                                    foreach ($this->checkRatio as $ck => $cv) {
//                                        if($v['game_id'] == 187) {
//
//                                            dump($checkData[$v['game_id']][$cv]);
//                                            dump($vvv);
//                                        }
                                        foreach ($checkData[$v['game_id']][$cv] as $gk=> $gv){
//                                            if($cv == 2){
//                                                dump($gv);
//                                                dump($vvv['turnover']);
//                                                die();
                                                if($gv['turnover'] < $vvv['turnover']) {
                                                    $checkInstanceof = array_column($checkData[$v['game_id']][$cv],'instanceof');
//                                                    if($v['game_id'] == 187 && $cv == 2) {
//                                                        dump($checkData[$v['game_id']][$cv]);
//                                                        dump($vvv['turnover']);
//                                                        dump(in_array(3,$checkInstanceof));
//                                                    }
//                                                    in_array($checkInstanceof,2);

//                                                    die();
                                                    if (in_array(2,$checkInstanceof)) {
                                                        $data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk][$cv] = $gv['ratio'];
                                                    }
                                                } else {
                                                    break;
                                                }
//                                            }

                                        }
                                    }
                                }

                                $data[$key]['data'][$k]['game_data'][$vk]['ratio_data'][$vvk]['turnover']=
                                    '月流水='.$vvv['turnover'];
                            }

                        }

                    }

                }
            }
        }
//        die();

        if ($_REQUEST['export']) {
            $this->assign("is_export",true);
            $this->assign("data",$data);

            $time = date("Y-m-d",time());

            $this->assign('title',"海南万盟天下产品分成比例体系[{$time}]");
            $this->display("export");die();
        }

        $count = count($data);
        $page = set_pagination($count, $row,$params);
        if($page) {
            $this->assign('_page', $page);
        }

        $size = $row;//每页显示的记录数

        $data = array_slice($data, (($params['p']??1) - 1) * $size, $size);

//        dump($data);die();

        $this->assign("data",$data);
        $this->display();

    }


    //获取上游游戏比例
    function getCpGameRatio($handleData = []) {
        $cpGameData = M('cp_game_ratio', 'tab_')->where(['is_del'=>"0"])->order('id asc')->select();

        foreach ($cpGameData as $key => $value) {

            $cpRatio['turnover'] = $value['begin_total_amount'];
            $cpRatio['instanceof'] = $value['instanceof'];
            $cpRatio['ratio'] = $value['ratio'];

            $handleData[$value['game_id']][3][] =$cpRatio;

        }

        return $handleData;
    }

    //将比例整合
    function handleRatio($handleData = []) {
        $finalData = [];
//        dump($handleData);die();
        foreach ($handleData as $key => $value) {
            foreach ($value as $vk => $vv) {
                foreach ($vv as $k => $v) {

                    if ($finalData[$key][$v['turnover']]) {
                        $finalData[$key][$v['turnover']][$vk] = $v["ratio"];
//                        if($v["instanceof"] != 0 && ($vk==0||$vk==1||$vk==2) && $handleData[$key][$vk][$k-1]["ratio"]) {
//                            $finalData[$key][$v['turnover']][$vk] = $handleData[$key][$vk][$k-1]["ratio"];
//                        }
                        //判断是否有相同值且一个是>=另一个是>的情况
                        if ($finalData[$key][$v['turnover']]["instanceof"] != $v["instanceof"]) {
                            $finalData[$key][$v['turnover']]["instanceof"] = 0;

                            $finalData[$key][$v['turnover']."ed"] = $finalData[$key][$v['turnover']];
                            $finalData[$key][$v['turnover']."ed"]['is_equal'] = 1;
                        }

                        continue;
                    }
                    $v['is_equal'] = 0;
                    $v[$vk] = $v["ratio"];
                    unset($v["ratio"]);
                    $finalData[$key][$v['turnover']] = $v;

                }
            }
        }

        foreach ($finalData as $key => $value) {

            $last_names = array_column($finalData[$key],'turnover');
            array_multisort($last_names,SORT_ASC,$finalData[$key]);

        }

//        dump($finalData);die();
        $data = [];
        foreach ($finalData as $key => $value) {

            foreach ($value as $k => $v) {

                foreach ($this->checkRatio as $ck=>$cv) {
                    if ($k == "0.00" && !$finalData[$key][$k][$cv]) {
                        $finalData[$key][$k][$cv] = "0.00";
                    }

                    if ($k != "0.00" && !$finalData[$key][$k][$cv]) {
                        //查找上一个比例
                        $finalData[$key][$k][$cv] = $data[$key][count($data[$key])-1][$cv];
                    }
                }
//                dump($finalData[$key]);

                $data[$key][] = $finalData[$key][$k];

            }

        }
//        dump($data);die();

//        foreach ($data as $key => $value) {
//
//            $last_names = array_column($data[$key],'turnover');
//            array_multisort($last_names,SORT_ASC,$data[$key]);
//
//        }
//        dump($data);


        return $data;
    }

    function getAggregateData() {
        $request = [];
        $request['remote'] = 1;

        $aggregateData = json_decode(curl_post($this->api,$request),true);

//        dump($aggregateData);

        $gameData = M("game","tab_")
            ->field("unique_code,relation_game_id game_id")
            ->where('unique_code is not null or unique_code!=""')
            ->group("unique_code")
            ->select();

//        dump($gameData);

        $gameUniqueData = [];
        foreach ($gameData as $key => $value ) {

            $gameUniqueData[$value['unique_code']] = $value['game_id'];

        }

        $handleAggregateData = [];
        foreach ($aggregateData as $key => $value) {

            if ($value['unique_code']) {

                $explodeData = explode('|',$value['exploitation_rate']);
                $explodeDefauleData = explode('|',$value['default_exploitation_rate']);

                $temporaryNum = 100;
                $temporaryData = [];

                foreach ($explodeDefauleData as $k => $v) {
//                    dump($v);
                    if ($v<$temporaryNum && $v>0) {
                        $temporaryData = [];
                        $temporaryNum = $v;

                        $temporaryData[] = ['turnover'=>'0.00','instanceof'=>1,'ratio'=>number_format(100.00-$v,2,'.','')];

                        $defauleData = json_decode($explodeData[$k],true);

                        foreach ($defauleData as $ek => $ev) {
                            $temporaryData[] = ['turnover'=>number_format($ev['money'],2,'.',''),'instanceof'=>$ev['symbol'],'ratio'=>number_format(100.00-$ev['rate'],2,'.','')];
                        }
//                        dump($temporaryData);

                    }

                }

                if($temporaryData) {
                    $handleAggregateData[$gameUniqueData[$value['unique_code']]][4] = $temporaryData;
                }

            }
        }

        return $handleAggregateData;
    }

    
}