<?php

namespace Biz\SetAdapter\Result;
abstract class BaseAdapter {

    //$params=array('status'=>0,'data'=>'','msg'=>'');
    /**
     * 统一接口输出风格
     * @param string $path
     * @param array $params
     * @return array
     */
    public function update(string $path, array $params) {
        if ((int)$params['status'] > 0) {
            $params['status'] = 1;
        }
        $data = $params['data'];
        if ($data === null) {
            $data = new \stdClass();
        } else {
            $json = json_encode($data);
            $json = str_replace('\":null', '\\"\\"', $json);
            $json = str_replace('null', '""', $json);
            $data = json_decode($json, 1);
        }
        $params['data'] = $data;
        self::fix($path, $params);
        return $params;
    }

    /**
     * 特殊接口转换调用方法注册
     * @param $path
     * @param $data
     */
    protected function fix($path, &$data) {
        $path = strtolower($path);
        self::betDetailFix($path, $data);
        self::filterNoneSetting($path, $data);
        self::fixOddsArray($path, $data);
        if ($_GET['devicetype'] === 'ios') self::fixAccountSum($path, $data);
        else
            self:: zbAccountSumFix($path, $data);
        self::filterPrize($path, $data);
        self::fixLongPrizeCode($path, $data);
        self::filterDefInfo($path, $data);
        self:: filterNoneDataInHis($path, $data);
        self:: zbListFix($path, $data);
    }

    /**
     * 将玩法详情改为数组
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function betDetailFix($path, &$data) {

        $tpath = strtolower('Api/BetRecord/GetDetails');
        if ($data['status'] != 1) return $data;
        if ($path === $tpath) {
            $open_codes = is_array($data['data']['opencodes']) ? array_values($data['data']['opencodes']) : [];
            $back_water = 0;
            $details = $data['data']['details'];
            $details = str_replace('<br/>', '$', $details);
            $details = str_replace(['（￥', '）'], [',', ''], $details);
            $details = preg_replace('/\s+/u', ',', $details);
            $details = substr($details, 0, -1);
            $arr = explode('$', $details);
//            dd($arr, $details);
            $arr2 = [];//分组所选的玩法详情
            foreach ($arr as $k => $v) {
                $tmp = explode(',', $v);
                array_unshift($tmp, $data['data']['ptypename']);
                if (isset($arr2[$tmp[0]])) {
                    $arr2[$tmp[0]]['play_code'] .= ',' . $tmp[1];
                    $arr2[$tmp[0]]['money'] += $tmp[2];
                    $arr2[$tmp[0]]['prize_status'] = $arr2[$tmp[0]]['prize_status'] === '中奖' ? '中奖' : $tmp[3];
                } else {
                    $arr2[$tmp[0]]['cat'] = $tmp[0];
                    $arr2[$tmp[0]]['play_code'] = $tmp[1];
                    $arr2[$tmp[0]]['money'] = $tmp[2];
                    $arr2[$tmp[0]]['prize_status'] = $tmp[3];
                }
            }
            //投注玩法列表
//            dd($open_codes);
            $arr2 = array_values($arr2);
            foreach ($open_codes as $k => $v) {
                //$v=>当前玩法分组数组
                foreach ($v as $kk => $vv) {
                    $m = $vv['settings']['multiple'];
                    if (!isset($arr2[$k]['multiple'])) {
                        $arr2[$k]['multiple'] = $m;
                    } else {
                        if ($arr2[$k]['multiple'] !== $m) {
                            $arr2[$k]['multiple'] = '混合';
                        }
                    }
                    $f_rate = (float)$vv['settings']['back'] ?? 0;
                    $back_water += $arr2[$k]['money'] * $f_rate;
                }
            }
            $data['data']['details'] = $arr2;
            $data['data']['back_water'] = number_format($back_water, 2, '.', '');
        }
        return $data;
    }

    /**
     * 过滤空值属性
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function filterNoneSetting($path, &$data) {
        $t = strtolower('Api/Settings/Query');
        if ($path !== $t) return $data;
        foreach ($data['data']['data'] as $k => $v) {
            if (!$v['settings']) {
                unset($data['data']['data'][$k]);
            }
        }
        if (strpos($_GET['game'], 'sixlottery') !== false) {
            $data['data']['data']['twoface']=[
                'name'=>'twoface',
                'parent'=>'',
                'isback'=>0,
            ];
            $data['data']['data']['specialnum']=[
                'name'=>'specialnum',
                'parent'=>'',
                'isback'=>0,
            ];
            $data['data']['data']['generalnum']=[
                'name'=>'generalnum',
                'parent'=>'',
                'isback'=>0,
            ];
            $data['data']['data']['selfselect']=[
                'name'=>'selfselect',
                'parent'=>'',
                'isback'=>0,
            ];
            $data['data']['data']['series_bornend']=[
                'name'=>'series_bornend',
                'parent'=>'',
                'isback'=>0,
            ];
            $data['data']['data']['series']=[
                'name'=>'series',
                'parent'=>'',
                'isback'=>0,
            ];

        }
        return $data;
    }

    /**
     * 将odds属性列表转换为odds对象数组；back统一格式化为string
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function fixOddsArray($path, &$data) {
        $t = strtolower("Api/Long/getGameList");
        if ($path !== $t) {
            return $data;
        }
        foreach ($data['data'] as $k => $v) {
            $oddsArr = json_decode($v['odds'], 1);
            foreach ($oddsArr as $kkk => $vvv) {
                $vvv['settings']['back'] = (string)$vvv['settings']['back'];
                $hasBackWater = 0;
                if (gettype($vvv['settings']['multiple']) === 'string') {
                    $max = (string)$vvv['settings']['multiple'];
                    $min = '0';
                    $vvv['settings']['multiple'] = ['max' => $max, 'min' => $min];
                    $vvv['settings']['back'] = $vvv['settings']['back'] ?: '0';

                }
                if ($vvv['settings']['back'])
                    $hasBackWater = 1;
                $vvv['settings']['hasBackWater'] = $hasBackWater;
                $vvv['cn_name'] = $this->getChName($vvv['name']);
                ksort($vvv);
                $oddsArr[$kkk] = $vvv;

            }
            $oddsArr = array_values($oddsArr);
            $v['odds'] = $oddsArr;
            $data['data'][$k] = $v;
        }
        return array_values($data['data']);
    }

    /**
     * 将账户统计中的资金类型转换为对象数组
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function fixAccountSum($path, &$data) {
        $t = strtolower('Api/UserDetails/AccountSum');
        if ($path !== $t) return $data;
        $tmp = [];
        foreach ($data['data'] as $k => $v) {
            $tmp[] = ['key' => $k, 'value' => $v];
        }
        return $data['data'] = $tmp;

    }

    /**
     * 过滤历史开奖数据中无用数据和未开奖数据
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function filterPrize($path, &$data) {
        $t = strtolower('Api/UserDetails/TrendChart');
        if ($path !== $t) return $data;
        if ($data['data'] === null)
            return $data['data'] = [];
        $newData = [];
        $newData['status'] = $data['status'];
        $newData['msg'] = $data['msg'];
        $newData['data']['icon'] = $data['data']['icon'];
        $newData['data']['name'] = $data['data']['name'];
        $newData['data']['data'] = [];
        if (isset($data['data']['page']))
            $newData['data']['page'] = $data['data']['page'];
        foreach ($data['data']['data'] as $k => $v) {
            $v['codes'] = str_replace(' ', '', $v['codes']);
            if (!$v['codes'] || $v['codes'] === '-1') {
                unset($data['data'][$k]);
                continue;
            }
            $item = [
                'codes' => $v['codes'],
                'info_no' => $v['info_no']
            ];
            $cond = mb_strpos($_GET['name'], 'sixlottery');
            if ($cond >= 0) {
                $item['specialcodea'] = $v['specialcodea'];
                $item['specialborn'] = $v['specialborn'];
                $item['specialcolorwave'] = $v['specialcolorwave'];
                $item['specialendcode'] = $v['specialendcode'];
                $item['specialheadcode'] = $v['specialheadcode'];
            }
            if (strpos($data['data']['name'], '28')) {
                $item['other'] = json_decode($v['extra']);
            }
            $newData['data']['data'][] = $item;
        }
        return $data = $newData;

    }

    /**
     * 修改未开奖长龙玩法名称丢失数据
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function fixLongPrizeCode($path, &$data) {
        $t = strtolower('Api/long/getprizelist');
        if ($path !== $t) return $data;
        foreach ($data['data'] as $k => $v) {
            if (!isset($v['prize_code']))
                $v['prize_code'] = '';
            $data['data'][$k] = $v;
        }
        return $data;
    }

    /**
     * 过滤试玩接口多余数据
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function filterDefInfo($path, &$data) {
        $t = strtolower('Api/SystemInfo/DefaultInfo');
        if ($path !== $t) return $data;
        unset($data['data']['newdevice']);
        return $data;
    }

    /**
     * 过滤开奖历史中的号码空格、未开奖记录
     * @param $path
     * @param $data
     * @return mixed
     */
    protected function filterNoneDataInHis($path, &$data) {
        $t = strtolower('Api/GameCenter/Lotterytwo');
        if ($path !== $t)
            return $data;
        if (!isset($data['data']['tolist']))
            $data['data']['tolist'] = [];
        foreach ($data['data']['tolist'] as $k => $v) {
            $codes = $v['codes'] = str_replace(' ', '', $v['codes']);
            if (!$codes || $codes === '-1') {
                unset($data['data']['tolist'][$k]);
                continue;
            }
            unset($v['prizes']);
            $pos = strpos($_GET['game_name'], '28');
            if (!$pos) unset($v['other']);
            $data['data']['tolist'][$k] = $v;
            $data['data']['tolist'] = array_values($data['data']['tolist']);
        }
        return $data;
    }

    /**
     * 账变列表接口适配
     * @param $path
     * @param $data
     */
    protected function zbListFix($path, &$data) {
        $t = strtolower('Api/userDetails/Querry');
        if ($path !== $t)
            return;
        $data['status'] = 1;
        if (!$data['data']) $data['data'] = [];
    }

    /**
     * 账变详情适配
     * @param $path
     * @param $data
     */
    protected function zbAccountSumFix($path, &$data) {
        $dic = include(ROOT_PATH . '/Application/Api/Lang/TradeType.php');
        $t = strtolower('Api/userDetails/AccountSum');
        if ($path !== $t)
            return;
        $conv = [];
        foreach ($data['data'] as $k => $v) {
            $type = $dic[$k];
            $key = $type['key'];
            $title = $type['title'];
            if (!$title) continue;
            $conv[$key] = ['id' => $k, 'value' => $v, 'title' => $title];
        }

        $data['data'] = $conv;
    }

    /**
     *转换玩法为中文名
     * @param $name
     * @return string
     */
    private function getChName($name): string {
        $way = [
            'single' => '单',
            'double' => '双',
            'dobule' => '双',
            'lastsingle' => '尾单',
            'lastdouble' => '尾双',
            'lastbig' => '尾大',
            'lastsmall' => '尾小',
            'big' => '大',
            'small' => '小',
        ];
        $arr = explode('_', $name);
        if (count($arr) === 1) {
            $arr = explode('-', $name);
        }
        if (count($arr) === 1) {
            return '未知';
        }
        $count = count($arr);
        return $way[$arr[$count - 1]];
    }
}