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

/**
 * 订单相关
 */
class Payment extends MY_Controller
{
    public $retdata = array('referer' => '', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
    protected $page = 25;//分页
    protected $pageConfig = array(
        'first_tag_open' => '<li>',
        'first_tag_close' => '</li>',
        'last_tag_open' => '<li>',
        'last_tag_close' => '</li>',
        'next_tag_open' => '<li>',
        'next_tag_close' => '</li>',
        'prev_tag_open' => '<li>',
        'prev_tag_close' => '</li>',
        'cur_tag_open' => "<li class='active'><a hef='#'>",
        'cur_tag_close' => "</a></li>",
        'num_tag_open' => "<li>",
        'num_tag_close' => "</li>",
    );
    protected $gchannelName = [
        1 => 'Google',
        2 => 'IOS',
//            2 => 'SMS',
        3 => 'VIVO',
//            4 => 'Bluecoins',
//            5 => 'Truemoney',
//            6 => '12call',
//            7 => 'dtac',
//            8 => 'Line',
//            9 => 'vinaphone',
//            10 => 'mobifone',
//            11 =>'viettel',
//            12 => 'huawei',
//            13 => 'blueSMS',
//            14 => 'blueVinafone',
//            15 => 'blueMobifone',
//            16 => 'blueViettel',
//            17 => 'blueVtc',
//            18 => 'kaopu',
//            19 => 'hwos',
    ];
    protected $deviceName = [1 => 'Android', 2 => 'IOS', 3 => 'Android'];
    protected $orderStatus = [
        999 => '全部(除已创建待支付)',
        0 => '已创建待支付',
        -2 => '已失效',
        -1 => '已取消',
        1 => '已支付待验证',
        2 => '已验证待发货',
        3 => '已退款',
        4 => '已发货',
    ];

    public $summarylistTable = '';
    public $goods = '';
    public $orderTable = '';

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->library('pagination');
        $this->load->database();
        $this->summarylistTable = otable::summarylist();
        $this->goods = otable::goodsCrazy();
        $this->orderTable = otable::order();

        $this->_payBlackList['uid'] = oo::commonOprModel("payment")->payWhiteList();
        $this->env = get_cookie($this->_wenenv);
    }


    /**
     *    订单列表
     */
    public function index()
    {
        $data['stime'] = date('Y-m-d');
        $data['etime'] = date('Y-m-d');
        $data['uid'] = $this->input->get('uid') ? $this->input->get('uid') : $this->input->post('uid');
        $data['channelList'] = $this->gchannelName;
        $data['payment_type'] = -1;
//        if(!empty($data['uid'])){
//            $data['payment_type'] = -1;
//        }
        $data['statusMap'] = [
            -1 => '全部',
            0 => '未验单',
            1 => '已验单',
            2 => '已发货',
            3 => '已退款',
        ];
        $this->load->view('payment/index', $data);
    }

    public function orders()
    {
        $data['stime'] = date("Y-m-d 00:00:00");
        $data['etime'] = date('Y-m-d 23:59:59');
        $data['uid'] = $this->input->get('uid') ? $this->input->get('uid') : $this->input->post('uid');
        $data['channelList'] = $this->gchannelName;
        $data['payment_type'] = 999;
        $data['statusMap'] = $this->orderStatus;
        $this->load->view('payment/order', $data);
    }

    /**
     *    订单列表
     */
    public function indexData($page = 0)
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'payWhite';
        $retData = $this->curl->req($url, $this->postData);
        $retData = json_decode($retData, 1);
        $payWhite = explode(",", $retData['list']);

        $stime = !empty($this->input->post('payment_stime')) ? $this->input->post('payment_stime') : date('Y-m-d');
        $etime = !empty($this->input->post('payment_etime')) ? $this->input->post('payment_etime') : date('Y-m-d');
        $payment_type = !empty($this->input->post('payment_type')) ? $this->input->post('payment_type') : 0;//0 所有 2 支付成功
        $uid = $this->input->post('uid') ? $this->input->post('uid') : '';//用户ID
        $order_id = $this->input->post('order_id') ? $this->input->post('order_id') : '';//订单ID
        $sl_platform_serial_num = $this->input->post('sl_platform_serial_num') ? $this->input->post('sl_platform_serial_num') : '';//订单ID
        $channel = $this->input->post('channel') ? $this->input->post('channel') : 0;//支付渠道
        $start = (int)$this->input->post('start') ? $this->input->post('start') : 0;
        $length = (int)$this->input->post('length') ? $this->input->post('length') : 10;

        //时间查询
        $dateArr = array();
        $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        $dateArr['payment_type'] = $payment_type;
        $dateArr['userid'] = $uid;
        $dateArr['order_id'] = $order_id;
        $dateArr['sl_platform_serial_num'] = $sl_platform_serial_num;
        //$dateArr['channel'] = $channel;
        if (empty($channel)) {
            $sidList = [999];
        } else {
            $sidList = [$channel];
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'getList';
        $this->postData['limit'] = $length;
        $this->postData['page'] = $start;
        $postData = array_merge($dateArr, $this->postData);
        //$sidList = $this->_getSidList();

        $postData['sidList'] = json_encode($sidList);
//		$res = $this->curl->req($url, $postData);
//		$retData = json_decode($res, TRUE);
        $retData = $this->getList($postData);

        if (empty($retData) || !is_array($retData['list'])) {
            die(json_encode($this->withNodata()));
        }

        $anPackageList = $this->androidPackageList;
        $iosPackageList = $this->iosPackageList;

        //动态sku
        $moveSku = [710, 711, 712];

        foreach ($retData['list'] as $k => &$value) {
            $gchannel = $value['gchannel'];
            $gplatform = $value['gplatform'];
            //包名
            $sid = $value['sl_sid'];

            //$value['gchannel'] = $this->gchannelName[$gchannel];//原先是区分支付渠道的
            $value['gchannel'] = $this->gchannelName[$sid];
            //$value['gplatform'] = $this->deviceName[$gplatform];//
            $value['gplatform'] = $this->deviceName[$sid];
            $value['sl_order_time'] = empty($value['sl_order_time']) ? '' : date('Y-m-d H:i:s', $value['sl_order_time']);
            $value['sl_pay_time'] = empty($value['sl_pay_time']) ? '' : date('Y-m-d H:i:s', $value['sl_pay_time']);
            $value['index'] = $k + 1;

            if ($sid == '-1') {
                $value['packageName'] = "Window测试";
            } else if ($sid % 2 == 0) {
                $value['packageName'] = '苹果' . $iosPackageList[$sid];
            } else {
                $value['packageName'] = '安卓' . $anPackageList[$sid];
            }
            //是否显示补发和查看详情按钮
            if ($value['sl_status'] == 1 && in_array($gchannel, [1, 3, 12, 18])) {
                $value['flag'] = 1;
            } else if ($value['sl_status'] == 1) {
                $value['flag'] = 2;
            } else if (in_array($gchannel, [1, 3, 12, 18])) {
                $value['flag'] = 3;
            } else {
                $value['flag'] = 4;
            }
            if ($value['sl_status'] == 3 && in_array($value['sl_gid'], [801, 803])) {
                $value['sl_status'] = 5;
            }
            $value['sl_orderid'] = $value['sl_orderid'] . (in_array($value['sl_uid'], $payWhite) ? '[白名单]' : '');
            if (in_array($value['sl_gid'], $moveSku) || $value['gpid'] == 22) {
                $value['gsku'] = '动态sku';
            }

            $slContent = json_decode($value['sl_content'], true) ?? [];
            if (!empty($slContent)) {
                if (!empty($slContent['data'])) {
                    if (!empty($slContent['data']['propsReward'])) {
                        $slContent['data']['props'] = $slContent['data']['propsReward'];
                    }
                    $slContent = $slContent['data'];
                }
            }
            $value['sl_content'] = json_encode($slContent);
        }

        $data['recordsTotal'] = $retData['total'];
        $data['recordsFiltered'] = $retData['total'];
        $data['data'] = $retData['list'];
        die(json_encode($data));
    }

    public function orderData($page = 0)
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'payWhite';
        $retData = $this->httpPost($this->postData, $url);
        $payWhite = explode(",", $retData['list']);

        $params = $this->input->post();

        $uid = $params['uid'] ?? '';   //用户ID
        $stime = $params['payment_stime'] ?? date("Y-m-d 00:00:00");
        $etime = $params['payment_etime'] ?? date('Y-m-d 23:59:59');
        $payment_type = $params['payment_type'] ?? 999; // 999:所有
        $order_id = $params['order_id'] ?? ''; // 订单ID
        $sl_platform_serial_num = $params['sl_platform_serial_num'] ?? ''; // 订单ID
        $sku = $params['sku'] ?? ''; // 商品SKU
        $channel = $params['channel'] ?? 0; // 支付渠道
        $start = intval($params['start'] ?? 0);
        $length = intval($params['length'] ?? 10);

        $this->page = $length;

        //时间查询
        $dateArr = [
            "stime" => $stime,
            "etime" => $etime,
            "payment_type" => $payment_type,
            "userid" => $uid,
            "order_id" => $order_id,
            "channel" => $channel,
            "sl_platform_serial_num" => $sl_platform_serial_num,
            "sku" => $sku,
        ];

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'getList';
        $this->postData['limit'] = $length;
        $this->postData['page'] = $start;
        $postData = array_merge($dateArr, $this->postData);

        $postData['sidList'] = json_encode(empty($channel) ? [999] : [$channel]);

        $retData = $this->getOrderList($postData);
        if (empty($retData) || !is_array($retData['list'])) {
            die(json_encode($this->withNodata()));
        }

        //动态sku
        $moveSku = [710, 711, 712];

        foreach ($retData['list'] as $k => &$value) {
            $sid = $value['sid'];

            //包名
            $value['gsku'] = $value['sku'];
            $value['gchannel'] = $this->gchannelName[$sid];
            $value['gplatform'] = $this->deviceName[$sid];
            $value['sl_order_time'] = $value['created_at'] ?: "";
            $value['sl_pay_time'] = $value['purchased_at'] ?: "";
            $value['index'] = $k + 1;
            $value['id'] = $value['inner_order_id'];
            $value['sl_orderid'] = $value['inner_order_id'];
            $value['sl_uid'] = $value['uid'];
            $value['sl_gid'] = $value['gid'];
            $value['sl_pusd'] = $value['price'];
            $value['sl_status'] = $this->orderStatus[$value['status']];
            $value['sl_levelId'] = $value['level'];
            $value['sl_platform_serial_num'] = $value['external_order_id'];
            $value['status'] = ($value['status'] == 3 && in_array($value['gid'], [801, 803])) ? 5 : $value['status'];
            $value['inner_order_id'] = $value['inner_order_id'] . (in_array($value['uid'], $payWhite) ? '[白名单]' : '');
            $value['gsku'] = (in_array($value['gid'], $moveSku) || $value['gpid'] == 22) ? '动态sku' : $value['gsku'];
            $value['sl_content'] = $this->buildSlContent($value['reward']);
        }

        $data['recordsTotal'] = $retData['total'];
        $data['recordsFiltered'] = $retData['total'];
        $data['data'] = $retData['list'];
        die(json_encode($data));
    }

    private function buildSlContent($reward): string
    {
        $slContent = json_decode($reward, true) ?? [];
        while (is_scalar($slContent)) {
            $slContent = json_decode($slContent, true) ?? [];
        }

        return $this->parseRewardHtml($slContent);
    }

    private function parseRewardHtml($rewards)
    {
        $html = '';
        $props = array_column(oo::commonOprModel('config')->getPropsConfigFromLocal(), null, 'id');
        foreach ($rewards as $reward) {
            $rewardProp = $props[$reward['propsId']] ?? ['name' => 'propsId:' . $reward['propsId']];
            if (!empty($rewardProp['skinList']) && is_array($rewardProp['skinList']) && !empty($reward['skin'])) {
                foreach ($rewardProp['skinList'] as $skinItem) {
                    if ($skinItem['id'] == $reward['skin']) {
                        $html .= "<span class='label label-success'>{$skinItem['name']}:{$reward['num']}</span>";
                        break;
                    }
                }
                continue;
            }

            $html .= "<span class='label label-success'>{$rewardProp['name']}:{$reward['num']}</span>";
        }
        return $html;
    }

    /**
     *    获取订单列表
     */
    public function getList($param)
    {
        $data = array('list' => array(), 'total' => 0);
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $paymentType = intval($param['payment_type']);
        $uid = oo::functions()->uint($param['userid']); // 用户ID
        $orderId = oo::functions()->escape($param['order_id']);//订单号
        $sl_platform_serial_num = $param['sl_platform_serial_num'];
        $channel = oo::functions()->uint($param['channel']);//渠道
        $sidList = json_decode($param['sidList'], 1);
        $page = oo::functions()->uint($param['page']);//起始页数
        $limit = oo::functions()->uint($param['limit']);//每页数量
        $uidSql = '';

        if (empty($sidList)) {
            return json_encode(['list' => [], 'total' => 0]);
        }
        if ($this->isAllSid($sidList)) {
            $where = " 1=1 ";
        } else {
            $where = "  sl_sid IN ( " . implode(',', $sidList) . " )";
        }

        if (empty($stime)) {
            $stime = strtotime('0:0:1');
        }//默认为当天
        if (empty($etime)) {
            $etime = time();
        }
//		if( empty($paymentType) ){ $paymentType = 2; }
        if (!empty($uid)) {
            $uidSql = ' AND sl_uid = ' . $uid;
        }
        if ($paymentType > 1) { //已发货,已退款,退款已处理等状态
            $where .= " AND sl_status = {$paymentType} AND sl_pay_time >= {$stime} AND sl_pay_time <= {$etime} ";
        } else {
            if ($paymentType != -1) {
                $where .= " AND sl_status = {$paymentType} AND sl_order_time >= {$stime} AND sl_order_time <= {$etime} ";
            } else {
                $where .= " AND sl_order_time >= {$stime} AND sl_order_time <= {$etime} ";
            }
        }
        if (!empty($orderId)) {
            $where .= " AND sl_orderid = '{$orderId}' ";
        }
        if (!empty($sl_platform_serial_num)) {
            $where .= " AND sl_platform_serial_num = '{$sl_platform_serial_num}' ";
        }
        if (!empty($channel)) {
            $where .= " AND g.gchannel = $channel ";
        }

        $slTable = $this->summarylistTable;
        $goodsTable = $this->goods;
        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if (!empty($blackUidArr) && empty($uid)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND sl_uid NOT IN ({$blackUidStr}) ";
        }

        $sql = " SELECT sl.*, g.* FROM {$slTable} AS sl LEFT JOIN {$goodsTable} AS g ON sl.sl_gid = g.gid WHERE {$where}  $blackUidSql $uidSql ORDER BY sl_order_time DESC LIMIT $page, $limit ";
        $list = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);

        //获取总数
        $totalSql = " SELECT count(1) as t FROM {$slTable} AS sl LEFT JOIN {$goodsTable} AS g ON sl.sl_gid = g.gid WHERE {$where} $blackUidSql $uidSql ";
        // oo::logs()->debug3(['tsql'=>$totalSql], 'Payment.php');

        $retTotal = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);
        $total = intval($retTotal['t']);

        $data['list'] = $list;
        $data['total'] = $total;
        return $data;
        return json_encode($data);
    }

    public function getOrderList($param)
    {
        $data = ['list' => [], 'total' => 0];

        $sidList = json_decode($param['sidList'], 1);
        if (empty($sidList)) {
            return json_encode($data);
        }

        $where = $this->buildOrderSqlWhere($param);

        $paymentType = intval($param['payment_type']);
        $channel = oo::functions()->uint($param['channel']);//渠道
        $page = oo::functions()->uint($param['page']);//起始页数

        $orderTbl = $paymentType != 0 ? otable::gameOrder() : otable::preorder();
        $sql = "SELECT * FROM {$orderTbl} WHERE {$where} ORDER BY created_at DESC limit {$page}, {$this->page}";
        $list = oo::commonOprDb('slavedb')->getAll($sql);

        $gidResults = $this->getGidInfoList($channel);
        foreach ($list as &$v) {
            $goods = [];
            foreach ($gidResults as $gidKey => $goodsValue) {
                if ($gidKey <= $v['gid']) {
                    $goods = $goodsValue;
                    $goods['gid'] = $v['gid'];
                    break;
                }
            }
            $v = array_merge($v, (array)$goods);
            $v['gname'] = $v['gname'] ?? '';
            $v['gdesc'] = $v['gdesc'] ?? '';
            $v['gsku'] = $v['gsku'] ?? '';

            // 预订单表 字段兼容
            if ($paymentType == 0) {
                $v['inner_order_id'] = $v['order_id'];
                $v['external_order_id'] = "-";
                $v['purchased_at'] = "-";
                $v['status'] = 0;
                $v['ext'] = $v['extend'];
                unset($v['order_id'], $v['extend']);
            }
        }

        // 获取总数
        $retTotal = oo::commonOprDb('slavedb')->getOne("SELECT count(1) as t FROM {$orderTbl} WHERE {$where}");

        $total = intval($retTotal['t']);
        $data['list'] = $list;
        $data['total'] = $total;
        return $data;
    }

    private function buildOrderSqlWhere($param): string
    {
        $sku = $param['sku'];
        $paymentType = intval($param['payment_type']);
        $uid = oo::functions()->uint($param['userid']); // 用户ID
        $orderId = oo::functions()->escape($param['order_id']);//订单号
        $sl_platform_serial_num = $param['sl_platform_serial_num'];
        $sidList = json_decode($param['sidList'], true);

        $sDateTime = date('Y-m-d H:i:s', strtotime($param['stime']));
        $eDateTime = date('Y-m-d H:i:s', strtotime($param['etime']));

        $uidSql = !empty($uid) ? ' AND uid = ' . $uid : "";

        if ($this->isAllSid($sidList)) {
            $where = "true";
        } else {
            $where = "sid IN ( " . implode(',', $sidList) . " )";
        }

        $where .= " AND created_at BETWEEN '{$sDateTime}' AND '{$eDateTime}'";
        if (!in_array($paymentType, [0, 999])) {
            $where .= " AND status = {$paymentType}";
        }

        if (!empty($orderId)) {
            $where .= " AND inner_order_id = '{$orderId}'";
        }

        if (!empty($sl_platform_serial_num)) {
            $where .= " AND external_order_id = '{$sl_platform_serial_num}'";
        }

        if (!empty($sku)) {
            $where .= " AND sku = '{$sku}'";
        }

        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if (!empty($blackUidArr) && empty($uid)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND uid NOT IN ({$blackUidStr})";
        }

        return "{$where} {$blackUidSql} {$uidSql}";
    }

    private function getGidInfoList($channel)
    {
        $channelArr = !empty($channel) ? [$channel] : [1, 2];
        $channelStr = implode(',', $channelArr);

        $goodsTable = $this->goods;
        $gidResults = oo::commonOprDb('slavedb')->getAll("select * from {$goodsTable} where `gchannel` in ({$channelStr})");
        $gidResults = array_column($gidResults, null, 'gid');
        krsort($gidResults);

        return $gidResults;
    }

    /**
     * 导出订单记录
     */
    public function exportRefundOrder()
    {
        $platformList = [1 => 'Android', 2 => 'IOS'];
        $data = [];
        $dateArr = array();
        $stime = $this->input->get('payment_stime');
        $etime = $this->input->get('payment_etime');
        $sl_platform_serial_num = $this->input->get('sl_platform_serial_num'); //订单id

        $userid = $this->input->get('userid');
        $orderid = $this->input->get('orderid');

        if ($stime) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $data['stime'] = date("Y-m-d", strtotime('-90 days 0:0:1'));
            $dateArr['stime'] = strtotime($stime . '-90 days 0:0:1');
        }

        if ($etime) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }

        $where = '1 = 1';
        if (!empty($dateArr['stime'])) {
            $where .= " AND sl_order_time >= {$dateArr['stime']}";
        }
        if (!empty($dateArr['etime'])) {
            $where .= " AND sl_order_time < {$dateArr['etime']}";
        }
        if ($sl_platform_serial_num) {
            $where .= " AND sl_platform_serial_num = '{$sl_platform_serial_num}'";
        }
        if ($orderid) {
            $where .= " AND sl_orderid = '{$orderid}'";
        }
        if ($userid) {
            $where .= " AND sl_uid = '{$userid}'";
        }
        $where .= " AND sl_status IN(3, 4)";

        $table = otable::summarylist();
        $sql = "SELECT * FROM {$table} WHERE {$where} ORDER BY sl_order_time DESC";
        $data['list'] = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);

        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $headerTable = ['ID', '用户ID', '游戏内商品ID', '平台商品ID', '商品价格', '下单时间', '支付时间', '支付渠道', '设备平台', '流水号'];
        $bodyKeys = ["id", "sl_uid", "sl_gid", "sl_orderid", "sl_pusd", "sl_order_time", "sl_pay_time", "channel", "platform", "sl_platform_serial_num"];

        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        $prefix = '';
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $v);
            if ($char == 'Z') {
                $char = 'AA';
                $prefix = 'A';
            } else {
                if (strlen($char) == 2) {
                    $char = $prefix . chr(ord(substr($char, 1, 1)) + 1);
                } else {
                    $char = $prefix . chr(ord($char) + 1);
                }
            }
        }

        //处理数据
        $i = 2;
        foreach ($data['list'] as $kb => $vb) {
            $charb = 'A';
            $prefix = '';
            foreach ($bodyKeys as $index => $value) {
                if ($value == 'channel') {
                    $sid = $vb['sl_sid'];
                    $valueBody = isset($this->gchannelName[$sid]) ? $this->gchannelName[$sid] : '-';
                } elseif ($value == 'platform') {
                    $sid = $vb['sl_sid'];
                    $valueBody = isset($platformList[$sid]) ? $platformList[$sid] : '-';
                } elseif (in_array($value, ['sl_order_time', 'sl_pay_time'])) {
                    $valueBody = $vb[$value];
                    $valueBody = date('Y-m-d H:i:s', $valueBody);
                } else {
                    $valueBody = $vb[$value];
                }
                if (in_array($value, ['sl_platform_serial_num', 'sl_orderid'])) {
                    $valueBody = "'" . $valueBody;
                }
                $objPHPExcel->getActiveSheet()->setCellValue($charb . $i, $valueBody);
                if ($charb == 'Z') {
                    $charb = 'AA';
                    $prefix = "A";
                } else {
                    if (strlen($charb) == 2) {
                        $charb = $prefix . chr(ord(substr($charb, 1, 1)) + 1);
                    } else {
                        $charb = $prefix . chr(ord($charb) + 1);
                    }
                }
            }
            $i++;
        }
        $outPutFileName = '退款订单_' . date('Y-m-d') . '_' . uniqid();

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $outPutFileName . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 失败订单记录
     */
    public function failOrder($page = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '', 'channelList' => $this->gchannelName, 'platformList' => [1 => 'Android', 2 => 'IOS']);
        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $data['stime'] = date("Y-m-d", strtotime('-7 days 0:0:1'));
            $dateArr['stime'] = strtotime($stime . '-7 days 0:0:1');
        }

        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }

        $data['sl_platform_serial_num'] = get_cookie('sl_platform_serial_num') ? get_cookie('sl_platform_serial_num') : '';//订单ID
        $where = '1 = 1';
        if (!empty($dateArr['stime'])) {
            $where .= " AND order_time >= {$dateArr['stime']}";
        }
        if (!empty($dateArr['etime'])) {
            $where .= " AND order_time < {$dateArr['etime']}";
        }
        if ($data['sl_platform_serial_num']) {
            $where .= " AND platform_serial_num = '{$data['sl_platform_serial_num']}'";
        }

        $table = otable::paymentFail();
        $data['page'] = $page;
        $limitStr = " limit $page, {$this->page}";
        $sql = "SELECT * FROM {$table} WHERE {$where} ORDER BY order_time DESC {$limitStr}";

        $data['list'] = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);

        //获取总数
        $totalSql = " SELECT COUNT(1) AS t FROM {$table} WHERE {$where}";
        $totalRet = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);
        $data['total'] = (int)$totalRet['t'];

        //分页
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#payment/failorder');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $this->page;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;

        $this->load->view('payment/failorder', $data);
    }

    /**
     * 导出失败订单记录
     */
    public function exportFailOrder()
    {
        $platformList = [1 => 'Android', 2 => 'IOS'];
        $data = [];
        $dateArr = array();
        $sl_platform_serial_num = get_cookie('sl_platform_serial_num') ? get_cookie('sl_platform_serial_num') : '';//订单ID
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $data['stime'] = date("Y-m-d", strtotime('-90 days 0:0:1'));
            $dateArr['stime'] = strtotime($stime . '-90 days 0:0:1');
        }

        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }
        $where = '1 = 1';
        if (!empty($dateArr['stime'])) {
            $where .= " AND order_time >= {$dateArr['stime']}";
        }
        if (!empty($dateArr['etime'])) {
            $where .= " AND order_time < {$dateArr['etime']}";
        }
        if ($sl_platform_serial_num) {
            $where .= " AND platform_serial_num = '{$sl_platform_serial_num}'";
        }

        $table = otable::paymentFail();
        $sql = "SELECT * FROM {$table} WHERE {$where} ORDER BY order_time DESC";
        $data['list'] = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);


        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $headerTable = ['ID', '用户ID', '游戏内商品ID', '平台商品ID', '下单时间', '支付渠道', '设备平台', '流水号', '商品sku'];
        $bodyKeys = ["pid", "uid", "gid", "order_id", "order_time", "channel", "platform", "platform_serial_num", "sku"];

        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        $prefix = '';
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $v);
            if ($char == 'Z') {
                $char = 'AA';
                $prefix = 'A';
            } else {
                if (strlen($char) == 2) {
                    $char = $prefix . chr(ord(substr($char, 1, 1)) + 1);
                } else {
                    $char = $prefix . chr(ord($char) + 1);
                }
            }
        }

        //处理数据
        $i = 2;
        foreach ($data['list'] as $kb => $vb) {
            $charb = 'A';
            $prefix = '';
            foreach ($bodyKeys as $index => $value) {
                if ($value == 'channel') {
                    $sid = $vb['sid'];
                    $valueBody = isset($this->gchannelName[$sid]) ? $this->gchannelName[$sid] : '-';
                } elseif ($value == 'platform') {
                    $sid = $vb['sid'];
                    $valueBody = isset($platformList[$sid]) ? $platformList[$sid] : '-';
                } elseif ($value == 'order_time') {
                    $valueBody = $vb[$value];
                    $valueBody = date('Y-m-d H:i:s', $valueBody);
                } else {
                    $valueBody = $vb[$value];
                }
                if (in_array($value, ['platform_serial_num', 'order_id'])) {
                    $valueBody = "'" . $valueBody;
                }
                $objPHPExcel->getActiveSheet()->setCellValue($charb . $i, $valueBody);
                if ($charb == 'Z') {
                    $charb = 'AA';
                    $prefix = "A";
                } else {
                    if (strlen($charb) == 2) {
                        $charb = $prefix . chr(ord(substr($charb, 1, 1)) + 1);
                    } else {
                        $charb = $prefix . chr(ord($charb) + 1);
                    }
                }
            }
            $i++;
        }
        $outPutFileName = '发货失败订单_' . date('Y-m-d') . '_' . uniqid();

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $outPutFileName . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     *    玩家订单信息
     */
    public function userindex($page = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        } else {
            $data['stime'] = date("Y-m-d");
        }

        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }

        if ($payment_type = get_cookie('payment_type')) {
            $data['payment_type'] = $payment_type;
            $dateArr['payment_type'] = $payment_type;
        } else {
            $data['payment_type'] = 2;
            $dateArr['payment_type'] = 2;
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'userList';
        $this->postData['limit'] = $this->page;
        $this->postData['page'] = $page;
        $postData = array_merge($dateArr, $this->postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if (!empty($retData)) {
            $data['list'] = $retData['list'];
            $data['total'] = (int)$retData['total'];
            $data['blackUidList'] = $retData['blackUidList'] ?? [];
            $data['page'] = $page;

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#payment/userindex');
            $pageConfig['total_rows'] = (int)$retData['total'];
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $this->load->view('payment/userindex', $data);
    }

    public function userindex1($page = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        } else {
            $data['stime'] = date("Y-m-d");
        }

        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }

        if ($payment_type = get_cookie('payment_type')) {
            $data['payment_type'] = $payment_type;
            $dateArr['payment_type'] = $payment_type;
        } else {
            $data['payment_type'] = 2;
            $dateArr['payment_type'] = 2;
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'userList';
        $this->postData['limit'] = $this->page;
        $this->postData['page'] = $page;
        $postData = array_merge($dateArr, $this->postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $res = $this->getUserIndexData($postData);
        $retData = json_decode($res, TRUE);
        if (!empty($retData)) {
            $data['list'] = $retData['list'];
            $data['total'] = (int)$retData['total'];
            $data['blackUidList'] = $retData['blackUidList'] ?? [];
            $data['page'] = $page;

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#payment/userindex');
            $pageConfig['total_rows'] = (int)$retData['total'];
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $this->load->view('payment/userindex', $data);
    }

    /**
     *    获取玩家订单信息
     */
    private function getUserIndexData($param)
    {
        $data = array('list' => array(), 'total' => 0);
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $paymentType = oo::functions()->uint($param['payment_type']);
        $length = oo::functions()->uint($param['length']);

        if (empty($stime)) {
            $stime = strtotime('0:0:1');
        }//默认为当天
        if (empty($etime)) {
            $etime = time();
        }
        $stime = date('Y-m-d H:i:s', $stime);
        $etime = date('Y-m-d H:i:s', $etime);
        if (empty($paymentType)) {
            $paymentType = 2;
        }
        $wherePaymentType = ' 1=1 ';
        if ($paymentType == 2) {
            $wherePaymentType = " status = 4 ";
        }

        $sidList = json_decode($param['sidList'], 1);
        if (empty($sidList)) {
            return json_encode([]);
        }
        $sidSqlStr = '';
        if (!$this->isAllSid($sidList)) {
            $sidSqlStr = " AND  sid IN ( " . implode(',', $sidList) . " ) ";
        }
        $where = $wherePaymentType . $sidSqlStr;

        $page = oo::functions()->uint($param['page']);//起始页数
        $limit = oo::functions()->uint($param['limit']);//每页页数

        $slTable = $this->orderTable;
        $blackUidArr = $this->_payBlackList['uid'];
        $limitStr = !empty($length) ? "  " : " limit $page, $limit";
//		$blackUidStr = implode(',', $blackUidArr);
        $sql = " SELECT  uid, count(1) as num, sum(price) as money FROM {$slTable} WHERE {$where} AND  created_at >= '{$stime}' AND created_at <= '{$etime}' GROUP BY uid ORDER BY money DESC {$limitStr} ";
//        oo::logs()->debug3(['sqlStr'=>$sql], 'Payment.php');
        $list = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);

        //获取总数
        $totalSql = " SELECT COUNT(1) AS t FROM (SELECT COUNT(1) AS num FROM {$slTable} WHERE {$where} AND created_at >= '{$stime}' AND created_at <= '{$etime}' GROUP BY uid ) as aa";
        $totalRet = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);

        $data['list'] = $list;
        $data['total'] = $totalRet['t'];
        $data['blackUidList'] = $blackUidArr;
        return json_encode($data);
    }


    /**
     * 报表导出
     */
    public function reportExport()
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
        }
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $stime = get_cookie('payment_stime');
        $etime = get_cookie('payment_etime');

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        } else {
            $data['stime'] = date("Y-m-d");
        }

        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }

        if ($payment_type = get_cookie('payment_type')) {
            $data['payment_type'] = $payment_type;
            $dateArr['payment_type'] = $payment_type;
        } else {
            $data['payment_type'] = 2;
            $dateArr['payment_type'] = 2;
        }

        $postData = array_merge($dateArr, $this->postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $postData['length'] = 1000;
        $postData['mod'] = 'Payment';
        $postData['act'] = 'userList';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);

        $retData = json_decode($res, TRUE);
        $headerTable = ['用户UID', '数量', '金额(美金)', '是否测试'];
        $bodyTable = $retData['list'];
        $blackUidList = $retData['blackUidList'] ?? [];
        $bodyKeys = ["uid", "num", "money", "istest"];

        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $v);
            if ($char == 'Z') {
                $char = 'AA';
            } else {
                $char = chr(ord($char) + 1);
            }
        }

        //处理数据
        $i = 2;
        foreach ($bodyTable as $kb => $vb) {
            $charb = 'A';
            foreach ($bodyKeys as $index => $value) {
                $valueBody = $vb[$value];
                if ($value == 'money') {
                    $valueBody = round($valueBody, 2);
                }

                if ($value == 'istest') {
                    $valueBody = in_array($vb['uid'], $blackUidList) ? '是' : '';
                }

                $objPHPExcel->getActiveSheet()->setCellValue($charb . $i, $valueBody);
                if ($charb == 'Z') {
                    $charb = 'AA';
                } else {
                    $charb = chr(ord($charb) + 1);
                }
            }
            $i++;
        }
        $outPutFileName = '支付玩家表_' . date('Y-m-d') . '_' . uniqid();

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $outPutFileName . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    public function vipuserList($type = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
//        if( $stime = get_cookie('payment_stime') ){
//            $data['stime'] = $stime;
//            $dateArr['stime'] = strtotime($stime.' 0:0:1');
//        }else{
//            $data['stime'] = date("Y-m-d");
//        }

        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'vipuserList';
//        $this->postData['limit'] = $perpage;
//        $this->postData['page'] = $page;
        $postData = array_merge($dateArr, $this->postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode($sidList);
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, 1);
        $data['list'] = $retData['list'] ?? [];
        $data['total'] = $retData['list'][$type]['total'] ?? 0;
        $data['type'] = $type;
        $this->load->view('payment/vipuserindex', $data);
    }

    /**
     *    BluePay对账
     */
    public function account()
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'channelList' => $this->gchannelName);
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('bluepay_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        } else {
            $data['stime'] = date("Y-m-01");
            $dateArr['stime'] = strtotime($data['stime'] . ' 0:0:1');
        }

        if ($etime = get_cookie('bluepay_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d");
            $dateArr['etime'] = strtotime($data['etime'] . ' 23:59:59');
        }

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'account';
        $postData = array_merge($dateArr, $this->postData);
        $sidList = $this->_getSidList();
        $postData['sidList'] = json_encode([1, 2]);

//        $res = $this->curl->req($url, $postData);
        $res = $this->getAccountData($postData);
        $retData = json_decode($res, TRUE);

        if (!empty($retData)) {
            $data['sucDeviceMoney'] = $retData['sucDeviceMoney'];
            $data['sucChannelMoney'] = $retData['sucChannelMoney'];
        }
        $this->load->view('payment/account', $data);
    }

    private function getAccountData($param)
    {
        $data = array();
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $sidList = json_decode($param['sidList'], 1);
        if (empty($sidList)) {
            return json_encode([]);
        }
        $stime = date('Y-m-d H:i:s', $stime);
        $etime = date('Y-m-d H:i:s', $etime);
        $sidSqlStr = '';
        if (!$this->isAllSid($sidList)) {
            $sidSqlStr = " AND  sid IN ( " . implode(',', $sidList) . " ) ";
        }

        $sTable = otable::summarylist();
        $gTable = otable::goodsCrazy();
//		$blackUidArr = $this->_payBlackList['uid'];
        $blackUidArr = [1, 2, 3];
        $blackUidStr = implode(',', $blackUidArr);
        $sql = " SELECT sid as sl_sid, price as sl_pusd FROM {$this->orderTable}   WHERE sid != -1 AND status = 4 AND purchased_at >= '{$stime}' AND purchased_at <= '{$etime}' AND uid NOT IN ({$blackUidStr}) $sidSqlStr";
        $sucList = oo::commonOprDb('slavedb')->getAll($sql, 1);
        $sucDeviceMoney = $sucChannelMoney = array();
        if ($sucList) {
            foreach ($sucList as $info) {
//				$gid = $info['sl_gid'];
//				$money = $info['sl_pusd'];
                $money = $info['sl_pusd'];
//				$moneyThb = $info['gpriceThb'];
//				$gchannel = $info['gchannel'];
                $gplatform = $info['sl_sid'];
                //汇总
                $sucDeviceMoney[$gplatform]['money'] += $money;//设备汇总
//				$sucDeviceMoney[$gplatform]['moneyThb'] += $moneyThb;//设备汇总
//				$sucChannelMoney[$gchannel][$gplatform]['money'] += ($money * 100);//渠道汇总
//                $sucChannelMoney[$gchannel][$gplatform]['moneyThb'] += ($moneyThb);//渠道汇总泰铢
            }
        }
        $data['sucDeviceMoney'] = $sucDeviceMoney;
        //$data['sucChannelMoney'] = $sucChannelMoney;
        return json_encode($data);
    }


    /**
     * 订单汇总查询
     */
    public function total()
    {
        $data = array('list' => '', 'userid' => '', 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '', 'payment_type' => '2');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        } else {
            $data['stime'] = date('Y-m-d', strtotime('-7 days'));
        }
        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        } else {
            $data['etime'] = date('Y-m-d', time());
        }

        //重新覆盖数据
        $data['userType'] = get_cookie('userType') ?? '';
        $data['groupId'] = get_cookie('groupId') ?? 0;
        $data['address'] = get_cookie('address') ?? '';

        if ($data['userType'] == '' && empty($data['groupId']) && empty($data['address'])) {
            //获取数据
            $postData = !empty($dateArr) ? array_merge($dateArr, $this->postData) : $this->postData;
            $sidList = $this->_getSidList();
            $postData['sidList'] = json_encode([1, 2]);
            $postData['mod'] = 'Payment';
            $postData['act'] = 'getTotal';
            ($this->env == 2) && $postData['demo'] = 1;
            $res = $this->curl->req($url, $postData);
//            $res = $this->getTotal($postData);
            $retData = json_decode($res, TRUE);

            $totalMoney = $totalMoneyAndroid = $totalMoneyIos = $totalRecord = $totalUid = $successPercentage = $channeperlList = $channelList = $totalOrder = $sidList = $sidPerlList = $vivoTotalMoney = [];
            $payClickAll = $payClickSuccess = $payClickCancel = $payClickError = $cancelPercent = $errorPercent = [];
            $dayList = $retData['dayList'] ?? [];
            $payEvent = [10009, 10010, 10011];

            foreach ($dayList as $_v) {
                $_v = date("Ymd", strtotime($_v));
                array_push($totalMoney, $retData['totalMoney'][$_v] ?? 0);//成功总金额
                array_push($totalMoneyAndroid, $retData['totalMoneyAndroid'][$_v] ?? 0);//成功总金额 安卓
                array_push($totalMoneyIos, $retData['totalMoneyIos'][$_v] ?? 0);//成功总金额 IOS
                array_push($totalUid, $retData['totalUid'][$_v] ?? 0);//成功总人数
                $totalRecordDay = $retData['totalRecord'][$_v] ?? 0;//成功总订单数
                array_push($totalRecord, $totalRecordDay);
                array_push($vivoTotalMoney, $retData['vivoTotalMoney'][$_v] ?? 0);//VIVO总收入

                $payClickAllTemp = ($retData['payReportTotal'][$_v]['1'] + $retData['payReportTotal'][$_v]['2']);
                array_push($payClickAll, $payClickAllTemp);//支付点击次数

                foreach ($payEvent as $eventId) {
                    $payClickTemp = intval($retData['payReportOtherTotal'][$eventId][$_v]['1'] + $retData['payReportOtherTotal'][$eventId][$_v]['2']);
                    switch ($eventId) {
                        case 10009:
                            array_push($payClickSuccess, $payClickTemp);//支付成功
                            $payClickSuccessTemp = $payClickTemp;
                            break;
                        case 10010:
                            array_push($payClickCancel, $payClickTemp);//支付取消
                            $payClickCancelTemp = $payClickTemp;
                            break;
                        case 10011:
                            array_push($payClickError, $payClickTemp);//支付失败
                            $payClickErrorTemp = $payClickTemp;
                            break;
                    }
                }

                $allRecordDay = $retData['allRecord'][$_v] ?? 0;//所有订单人数
                $successPer = empty($retData['allRecord'][$_v]) || empty($payClickAllTemp) ? 0 : round($totalRecordDay * 100 / $payClickAllTemp, 2);//成功率 成功订单 / 点击次数
                $cancelPer = empty($payClickAllTemp) || empty($payClickCancelTemp) ? 0 : round($payClickCancelTemp * 100 / $payClickAllTemp, 2);//取消率 取消点击次数 / 点击次数
                $errorPer = empty($payClickAllTemp) || empty($payClickErrorTemp) ? 0 : round($payClickErrorTemp * 100 / $payClickAllTemp, 2);//失败率
                array_push($successPercentage, $successPer);
                array_push($cancelPercent, $cancelPer);
                array_push($errorPercent, $errorPer);
                //按渠道计算成功订单率
                foreach ($this->gchannelName as $_gk => $_gchannel) {
                    $succChannel = $retData['succChannel'][$_v][$_gk] ?? 0;//渠道成功订单数
                    $totalChannel = $retData['totalChannel'][$_v][$_gk] ?? 0;//渠道总订单数
                    $payClick = $retData['payReportTotal'][$_v][$_gk] ?? 0;//支付点击次数
                    $succSid = $retData['succSid'][$_v][$_gk] ?? 0;//平台成功订单数
                    $totalSid = $retData['totalSid'][$_v][$_gk] ?? 0;//平台总订单数
                    $channelPer = empty($totalChannel) ? 0 : round($succChannel * 100 / $totalChannel, 2);//渠道成功率
                    $sidPer = empty($payClick) || empty($succSid) ? 0 : round($succSid * 100 / $payClick, 2);//平台订单成功率
                        $channeperlList[$_gk] ?? $channeperlList[$_gk] = [];
                        $channelList[$_gk] ?? $channelList[$_gk] = [];
                        $totalOrder[$_gk] ?? $totalOrder[$_gk] = [];
                        $sidList[$_gk] ?? $sidList[$_gk] = [];
                        $sidPerlList[$_gk] ?? $sidPerlList[$_gk] = [];
                        $payClickList[$_gk] ?? $payClickList[$_gk] = [];
                    array_push($channelList[$_gk], $succChannel);
                    array_push($channeperlList[$_gk], $channelPer);
                    array_push($totalOrder[$_gk], $totalSid);
                    array_push($sidList[$_gk], $succSid);
                    array_push($sidPerlList[$_gk], $sidPer);
                    array_push($payClickList[$_gk], $payClick);
                }
            }

            $data['dayList'] = $dayList;
//        //获取广告商数据
//        $infostime = strtotime($data['stime']);
//        $infoetime = strtotime($data['etime']);
//        $sql = "SELECT * FROM ad_inf  WHERE ad_time >= {$infostime} AND ad_time <= {$infoetime} ORDER BY ad_time DESC";
//        $query = $this->db->query($sql);
//        $adInfoList = $query->result_array();
//        $adInfoMoney = $adRoi = array();//每日广告花费
//        foreach ($adInfoList as $adKey => $adVal){
//            $t = date('Ymd', $adVal['ad_time']);
//            $adInfoMoney[$t] += $adVal['ad_money'];
//        }
//        foreach($dayList as $i => $day){
//            $adRoi[$i] = 0;
//            if (!$adInfoMoney[$day]){
//                continue;
//            }
//            $roi = round(($totalMoney[$i] - $adInfoMoney[$day])/$adInfoMoney[$day], 4);
//            $adRoi[$i] = $roi*100;
//        }
//        $data['adRoi'] = $adRoi;
        } else {
            $address = empty($data['address']) ? 'all' : $data['address'];
            //CMS查询数据
            $dateTemp = [];
            $stime = $data['stime'];
            for ($i = 0; $i <= $this->diffBetweenTwoDays($data['stime'], $data['etime']); $i++) {
                $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
            }
            $dateTemp = array_unique($dateTemp);
            $totalMoney = $payClickAll = $payClickSuccess = $payClickCancel = $payClickError = [];//array(8) { [0]=> int(0) [1]=> float(757.81) [2]=> float(206.96) [3]=> float(134.68) [4]=> float(80.85) [5]=> float(47.88) [6]=> int(0) [7]=> int(0) }
            $sidListTemp = [1, 2];
            foreach ($dateTemp as $k => $date) {
                $temp = oo::commonOprModel("statistics")->gamesIncome($date, $address, ['sum', 'count', 'orderCount'], 'all', [1, 2], $data['userType'], $data['groupId']);
                $totalMoney[$k] = $temp['sum'] ?? 0;//总金额
                $totalUid[$k] = $temp['count'] ?? 0;//人数
                $totalRecord[$k] = $temp['orderCount'] ?? 0;//成功订单数
                $temp = oo::commonOprModel("statistics")->gamesIncome($date, $address, ['sum', 'orderCount'], 'all', [1], $data['userType'], $data['groupId']);
                $sidList[1][$k] = $temp['orderCount'] ?? 0;
                $totalMoneyAndroid[$k] = $temp['sum'] ?? 0;
                $temp = oo::commonOprModel("statistics")->gamesIncome($date, $address, ['sum', 'orderCount'], 'all', [2], $data['userType'], $data['groupId']);
                $sidList[2][$k] = $temp['orderCount'] ?? 0;
                $totalMoneyIos[$k] = $temp['sum'] ?? 0;

                if ($date == date("Ymd")) {
                    foreach ($sidListTemp as $sid) {
                        $payClickTemp = oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid));
                        $payClickAll[$k] += array_sum($payClickTemp);
                        $payClickList[$sid][$k] = $payClickTemp[$sid] ?? 0;
                        $payClickSuccess[$k] += array_sum(oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, 10009)));
                        $payClickCancel[$k] += array_sum(oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, 10010)));
                        $payClickError[$k] += array_sum(oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, 10011)));
                    }
                } else {
                    $table = otable::staData();
                    $type = 'payReport';
                    $sql = "SELECT * FROM {$table} WHERE date = ({$date}) AND type = '{$type}'";
                    $payReportRet = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
                    $payReportRet['data'] = json_decode($payReportRet['data'], true);
                    foreach ($sidListTemp as $sid) {
                        $payClickAll[$k] += ($payReportRet['data']['total'][$sid] ?? 0);
                        $payClickList[$sid][$k] = ($payReportRet['data']['total'][$sid] ?? 0);
                        $payClickSuccess[$k] = (array_sum($payReportRet['data'][10009]['total']) ?? 0);
                        $payClickCancel[$k] = (array_sum($payReportRet['data'][10010]['total']) ?? 0);
                        $payClickError[$k] = (array_sum($payReportRet['data'][10011]['total']) ?? 0);
                    }
                }
                $successPercentage[$k] = empty($payClickAll[$k]) ? 0 : round($totalRecord[$k] * 100 / $payClickAll[$k], 2);
                $cancelPercent[$k] = empty($payClickAll[$k]) ? 0 : round($payClickCancel[$k] * 100 / $payClickAll[$k], 2);
                $errorPercent[$k] = empty($payClickAll[$k]) ? 0 : round($payClickError[$k] * 100 / $payClickAll[$k], 2);
                foreach ($sidListTemp as $sid) {
                    $sidPerlList[$sid][$k] = empty($payClickList[$sid][$k]) ? 0 : round($sidList[$sid][$k] * 100 / $payClickList[$sid][$k], 2);
                }
            }

            $data['dayList'] = $dateTemp;
        }

        $data['totalMoney'] = $totalMoney;
        $data['totalMoneyAndroid'] = $totalMoneyAndroid;
        $data['totalMoneyIos'] = $totalMoneyIos;
        $data['totalRecord'] = $totalRecord;
        $data['totalUid'] = $totalUid;
        $data['successPercentage'] = $successPercentage;//成功订单率
        $data['channelPerList'] = $channeperlList;//渠道订单成功率
        $data['channelList'] = $channelList;//渠道订单成功数
        $data['sidList'] = $sidList;//平台成功订单数
        $data['sidPerlList'] = $sidPerlList;//平台订单成功率
        $data['totalOrder'] = $totalOrder;//总订单数
        $data['payClickList'] = $payClickList;//支付点击次数列表
        $data['payClickAll'] = $payClickAll;//支付点击次数
        $data['payClickSuccess'] = $payClickSuccess;//支付点击次数
        $data['payClickCancel'] = $payClickCancel;//支付点击次数
        $data['payClickError'] = $payClickError;//支付点击次数
        $data['cancelPercent'] = $cancelPercent;//失败率
        $data['errorPercent'] = $errorPercent;//取消率
        $data['vivoTotalMoney'] = $vivoTotalMoney;

        //用户分组模型
        $groupList = oo::commonOprModel('config')->getUserGroupConfig2();
        array_multisort(array_column($groupList, 'sort'), SORT_DESC, $groupList);
        foreach ($groupList as $key => $row) {
            if (2 != $row['cid']) {
                unset($groupList[$key]);
                continue;
            }
        }
        $data['groupList'] = $groupList;

        $this->load->view('payment/total', $data);
    }

    public function total1()
    {
        $data = array('list' => '', 'userid' => '', 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '', 'payment_type' => '2');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        } else {
            $data['stime'] = date('Y-m-d', strtotime('-7 days'));
        }
        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        } else {
            $data['etime'] = date('Y-m-d', time());
        }
        if (($data['etime'] - $data['stime']) > 86400 * 15) $data['etime'] = $data['stime'] + 86400 * 15;
        if ($data['etime'] < $data['stime']) $data['etime'] = $data['stime'];


        //重新覆盖数据
        $data['userType'] = get_cookie('userType') ?? '';
        $data['groupId'] = get_cookie('groupId') ?? 0;
        $data['address'] = get_cookie('address') ?? '';

        if ($data['userType'] == '' && empty($data['groupId']) && empty($data['address'])) {
            //获取数据
            $postData = !empty($dateArr) ? array_merge($dateArr, $this->postData) : $this->postData;
            $sidList = $this->_getSidList();
            $postData['sidList'] = json_encode([1, 2, 3]);
            $postData['mod'] = 'Payment';
            $postData['act'] = 'getTotal';
            ($this->env == 2) && $postData['demo'] = 1;
//            $res = $this->curl->req($url, $postData);
            $res = $this->getTotal($postData);
            $retData = json_decode($res, TRUE);

            $totalMoney = $totalMoneyAndroid = $totalMoneyVivo = $totalMoneyIos = $totalRecord = $totalUid = $successPercentage = $channeperlList = $channelList = $totalOrder = $sidList = $sidPerlList = $vivoTotalMoney = [];
            $payClickAll = $payClickSuccess = $payClickCancel = $payClickError = $cancelPercent = $errorPercent = [];
            $dayList = $retData['dayList'] ?? [];
            $payEvent = [10009, 10010, 10011];

            foreach ($dayList as $_v) {
                $_v = date("Ymd", strtotime($_v));
                array_push($totalMoney, $retData['totalMoney'][$_v] ?? 0);//成功总金额
                array_push($totalMoneyAndroid, $retData['totalMoneyAndroid'][$_v] ?? 0);//成功总金额 安卓
                array_push($totalMoneyIos, $retData['totalMoneyIos'][$_v] ?? 0);//成功总金额 IOS
                array_push($totalMoneyVivo, $retData['totalMoneyVivo'][$_v] ?? 0);//成功总金额 VIVO
                array_push($totalUid, $retData['totalUid'][$_v] ?? 0);//成功总人数
                $totalRecordDay = $retData['totalRecord'][$_v] ?? 0;//成功总订单数
                array_push($totalRecord, $totalRecordDay);
                array_push($vivoTotalMoney, $retData['vivoTotalMoney'][$_v] ?? 0);//VIVO总收入

                $payClickAllTemp = ($retData['payReportTotal'][$_v]['1'] + $retData['payReportTotal'][$_v]['2']);
                array_push($payClickAll, $payClickAllTemp);//支付点击次数

                foreach ($payEvent as $eventId) {
                    $payClickTemp = intval($retData['payReportOtherTotal'][$eventId][$_v]['1'] + $retData['payReportOtherTotal'][$eventId][$_v]['2']);
                    switch ($eventId) {
                        case 10009:
                            array_push($payClickSuccess, $payClickTemp);//支付成功
                            $payClickSuccessTemp = $payClickTemp;
                            break;
                        case 10010:
                            array_push($payClickCancel, $payClickTemp);//支付取消
                            $payClickCancelTemp = $payClickTemp;
                            break;
                        case 10011:
                            array_push($payClickError, $payClickTemp);//支付失败
                            $payClickErrorTemp = $payClickTemp;
                            break;
                    }
                }

                $allRecordDay = $retData['allRecord'][$_v] ?? 0;//所有订单人数
                $successPer = empty($retData['allRecord'][$_v]) || empty($payClickAllTemp) ? 0 : round($totalRecordDay * 100 / $payClickAllTemp, 2);//成功率 成功订单 / 点击次数
                $cancelPer = empty($payClickAllTemp) || empty($payClickCancelTemp) ? 0 : round($payClickCancelTemp * 100 / $payClickAllTemp, 2);//取消率 取消点击次数 / 点击次数
                $errorPer = empty($payClickAllTemp) || empty($payClickErrorTemp) ? 0 : round($payClickErrorTemp * 100 / $payClickAllTemp, 2);//失败率
                array_push($successPercentage, $successPer);
                array_push($cancelPercent, $cancelPer);
                array_push($errorPercent, $errorPer);
                //按渠道计算成功订单率
                foreach ($this->gchannelName as $_gk => $_gchannel) {
                    $succChannel = $retData['succChannel'][$_v][$_gk] ?? 0;//渠道成功订单数
                    $totalChannel = $retData['totalChannel'][$_v][$_gk] ?? 0;//渠道总订单数
                    $payClick = $retData['payReportTotal'][$_v][$_gk] ?? 0;//支付点击次数
                    $succSid = $retData['succSid'][$_v][$_gk] ?? 0;//平台成功订单数
                    $totalSid = $retData['totalSid'][$_v][$_gk] ?? 0;//平台总订单数
                    $channelPer = empty($totalChannel) ? 0 : round($succChannel * 100 / $totalChannel, 2);//渠道成功率
                    $sidPer = empty($payClick) || empty($succSid) ? 0 : round($succSid * 100 / $payClick, 2);//平台订单成功率
                        $channeperlList[$_gk] ?? $channeperlList[$_gk] = [];
                        $channelList[$_gk] ?? $channelList[$_gk] = [];
                        $totalOrder[$_gk] ?? $totalOrder[$_gk] = [];
                        $sidList[$_gk] ?? $sidList[$_gk] = [];
                        $sidPerlList[$_gk] ?? $sidPerlList[$_gk] = [];
                        $payClickList[$_gk] ?? $payClickList[$_gk] = [];
                    array_push($channelList[$_gk], $succChannel);
                    array_push($channeperlList[$_gk], $channelPer);
                    array_push($totalOrder[$_gk], $totalSid);
                    array_push($sidList[$_gk], $succSid);
                    array_push($sidPerlList[$_gk], $sidPer);
                    array_push($payClickList[$_gk], $payClick);
                }
            }

            $data['dayList'] = $dayList;
//        //获取广告商数据
//        $infostime = strtotime($data['stime']);
//        $infoetime = strtotime($data['etime']);
//        $sql = "SELECT * FROM ad_inf  WHERE ad_time >= {$infostime} AND ad_time <= {$infoetime} ORDER BY ad_time DESC";
//        $query = $this->db->query($sql);
//        $adInfoList = $query->result_array();
//        $adInfoMoney = $adRoi = array();//每日广告花费
//        foreach ($adInfoList as $adKey => $adVal){
//            $t = date('Ymd', $adVal['ad_time']);
//            $adInfoMoney[$t] += $adVal['ad_money'];
//        }
//        foreach($dayList as $i => $day){
//            $adRoi[$i] = 0;
//            if (!$adInfoMoney[$day]){
//                continue;
//            }
//            $roi = round(($totalMoney[$i] - $adInfoMoney[$day])/$adInfoMoney[$day], 4);
//            $adRoi[$i] = $roi*100;
//        }
//        $data['adRoi'] = $adRoi;
        } else {
            $address = empty($data['address']) ? 'all' : $data['address'];
            //CMS查询数据
            $dateTemp = [];
            $stime = $data['stime'];
            for ($i = 0; $i <= $this->diffBetweenTwoDays($data['stime'], $data['etime']); $i++) {
                $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
            }
            $dateTemp = array_unique($dateTemp);
            $totalMoney = $payClickAll = $payClickSuccess = $payClickCancel = $payClickError = [];//array(8) { [0]=> int(0) [1]=> float(757.81) [2]=> float(206.96) [3]=> float(134.68) [4]=> float(80.85) [5]=> float(47.88) [6]=> int(0) [7]=> int(0) }
            $sidListTemp = [1, 2];
            foreach ($dateTemp as $k => $date) {
                $temp = oo::commonOprModel("statistics")->gamesIncome($date, $address, ['sum', 'count', 'orderCount'], 'all', [1, 2], $data['userType'], $data['groupId']);
                $totalMoney[$k] = $temp['sum'] ?? 0;//总金额
                $totalUid[$k] = $temp['count'] ?? 0;//人数
                $totalRecord[$k] = $temp['orderCount'] ?? 0;//成功订单数
                $temp = oo::commonOprModel("statistics")->gamesIncome($date, $address, ['sum', 'orderCount'], 'all', [1], $data['userType'], $data['groupId']);
                $sidList[1][$k] = $temp['orderCount'] ?? 0;
                $totalMoneyAndroid[$k] = $temp['sum'] ?? 0;
                $temp = oo::commonOprModel("statistics")->gamesIncome($date, $address, ['sum', 'orderCount'], 'all', [2], $data['userType'], $data['groupId']);
                $sidList[2][$k] = $temp['orderCount'] ?? 0;
                $totalMoneyIos[$k] = $temp['sum'] ?? 0;

                if ($date == date("Ymd")) {
                    foreach ($sidListTemp as $sid) {
                        $payClickTemp = oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid));
                        $payClickAll[$k] += array_sum($payClickTemp);
                        $payClickList[$sid][$k] = $payClickTemp[$sid] ?? 0;
                        $payClickSuccess[$k] += array_sum(oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, 10009)));
                        $payClickCancel[$k] += array_sum(oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, 10010)));
                        $payClickError[$k] += array_sum(oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, 10011)));
                    }
                } else {
                    $table = otable::staData();
                    $type = 'payReport';
                    $sql = "SELECT * FROM {$table} WHERE date = ({$date}) AND type = '{$type}'";
                    $payReportRet = oo::commonOprDb('statistics')->getOne($sql, MYSQLI_ASSOC);
                    $payReportRet['data'] = json_decode($payReportRet['data'], true);
                    foreach ($sidListTemp as $sid) {
                        $payClickAll[$k] += ($payReportRet['data']['total'][$sid] ?? 0);
                        $payClickList[$sid][$k] = ($payReportRet['data']['total'][$sid] ?? 0);
                        $payClickSuccess[$k] = (array_sum($payReportRet['data'][10009]['total']) ?? 0);
                        $payClickCancel[$k] = (array_sum($payReportRet['data'][10010]['total']) ?? 0);
                        $payClickError[$k] = (array_sum($payReportRet['data'][10011]['total']) ?? 0);
                    }
                }
                $successPercentage[$k] = empty($payClickAll[$k]) ? 0 : round($totalRecord[$k] * 100 / $payClickAll[$k], 2);
                $cancelPercent[$k] = empty($payClickAll[$k]) ? 0 : round($payClickCancel[$k] * 100 / $payClickAll[$k], 2);
                $errorPercent[$k] = empty($payClickAll[$k]) ? 0 : round($payClickError[$k] * 100 / $payClickAll[$k], 2);
                foreach ($sidListTemp as $sid) {
                    $sidPerlList[$sid][$k] = empty($payClickList[$sid][$k]) ? 0 : round($sidList[$sid][$k] * 100 / $payClickList[$sid][$k], 2);
                }
            }

            $data['dayList'] = $dateTemp;
        }

        $data['totalMoney'] = $totalMoney;
        $data['totalMoneyAndroid'] = $totalMoneyAndroid;
        $data['totalMoneyIos'] = $totalMoneyIos;
        $data['totalMoneyVivo'] = $totalMoneyVivo;
        $data['totalRecord'] = $totalRecord;
        $data['totalUid'] = $totalUid;
        $data['successPercentage'] = $successPercentage;//成功订单率
        $data['channelPerList'] = $channeperlList;//渠道订单成功率
        $data['channelList'] = $channelList;//渠道订单成功数
        $data['sidList'] = $sidList;//平台成功订单数
        $data['sidPerlList'] = $sidPerlList;//平台订单成功率
        $data['totalOrder'] = $totalOrder;//总订单数
        $data['payClickList'] = $payClickList;//支付点击次数列表
        $data['payClickAll'] = $payClickAll;//支付点击次数
        $data['payClickSuccess'] = $payClickSuccess;//支付点击次数
        $data['payClickCancel'] = $payClickCancel;//支付点击次数
        $data['payClickError'] = $payClickError;//支付点击次数
        $data['cancelPercent'] = $cancelPercent;//失败率
        $data['errorPercent'] = $errorPercent;//取消率
        $data['vivoTotalMoney'] = $vivoTotalMoney;

        //用户分组模型
        $groupList = oo::commonOprModel('config')->getUserGroupConfig2();
        array_multisort(array_column($groupList, 'sort'), SORT_DESC, $groupList);
        foreach ($groupList as $key => $row) {
            if (2 != $row['cid']) {
                unset($groupList[$key]);
                continue;
            }
        }
        $data['groupList'] = $groupList;

        $this->load->view('payment/total', $data);
    }

    private function getTotal($param)
    {
        set_time_limit(0);
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);

        if (empty($stime)) {
            $stime = strtotime('-7 days');
        }//默认为8天前
        if (empty($etime)) {
            $etime = time();
        }

        $stime = date('Y-m-d 00:00:01', $stime);
        $etime = date('Y-m-d 23:59:59', $etime);

        $sidList = json_decode($param['sidList'], 1);
        if (empty($sidList)) {
            return json_encode([]);
        }
        $sidSqlStr = '';
        if (!$this->isAllSid($sidList)) {
            $sidSqlStr = " AND  sid IN ( " . implode(',', $sidList) . " ) ";
        }

        $slTable = $this->summarylistTable;
        $goodsTable = $this->goods;
        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if (!empty($blackUidArr)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND uid NOT IN ({$blackUidStr}) ";
        }
        $goods = oo::commonOprDb('slavedb')->getAll("select * from {$goodsTable}", MYSQLI_ASSOC);
        $goods = array_column($goods, null, 'gid');
        //查询时间范围内的成功订单

        $sql = " SELECT price as sl_pusd, uid as sl_uid, purchased_at as sl_pay_time, gid, sid as sl_sid
              FROM {$this->orderTable}
              WHERE status = 4 AND  purchased_at >= '{$stime}' AND purchased_at <= '{$etime}' $blackUidSql $sidSqlStr ";
        //        oo::logs()->debug3(['sql'=>$sql], 'Payment.php');
        $list = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);

        //总订单数
        $sql2 = " SELECT  created_at as sl_order_time, gid, sid  as sl_sid
              FROM {$this->orderTable} 
              WHERE  created_at >= '{$stime}' AND created_at <= '{$etime}' $blackUidSql $sidSqlStr";
//        echo $sql2;die;
        $list2 = oo::commonOprDb('slavedb')->getAll($sql2, MYSQLI_ASSOC);

        $dayList = $this->getDays($stime, $etime, 2);
        $totalMoney = $totalMoneyAndroid = $totalMoneyIos = $totalRecord = $totalUid = $allRecord = $totalChannel = $succChannel = $totalSid = $succSid = $vivoTotalMoney = [];
        $totalMoneyVivo = [];
        $uid = [];
        //        oo::logs()->debug3(['succ'=>json_encode($list)], 'Payment.php');
        //        oo::logs()->debug3(['total'=>json_encode($list2)], 'Payment.php');
        //成功的订单
        foreach ($list as $_v) {
            $_v['gchannel'] = $goods[$_v['gid']]['gchannel'] ?? 1;
            $_v['sl_pay_time'] = strtotime($_v['sl_pay_time']);
            $date = date('Ymd', $_v['sl_pay_time']);
            $totalMoney[$date] += number_format($_v['sl_pusd'], 2, ".", "");
            if ($_v['sl_sid'] == 1) {
                $totalMoneyAndroid[$date] += number_format($_v['sl_pusd'], 2, ".", "");
            } else if ($_v['sl_sid'] == 3) {
                $totalMoneyVivo[$date] += number_format($_v['sl_pusd'], 2, ".", "");
            } else {
                $totalMoneyIos[$date] += number_format($_v['sl_pusd'], 2, ".", "");
            }
            $totalRecord[$date] += 1;
            //处理当天重复下单的用户统计
                $uid[$date] ?? $uid[$date] = [];
            if (!in_array($_v['sl_uid'], $uid[$date])) {
                $totalUid[$date] += 1;
                array_push($uid[$date], $_v['sl_uid']);
            }

            //统计当天的渠道的订单数
            if (isset($succChannel[$date][$_v['gchannel']])) {
                $succChannel[$date][$_v['gchannel']] += 1;
            } else {
                $succChannel[$date][$_v['gchannel']] = 1;
            }

            //统计平台 当天成功
            if (isset($succSid[$date][$_v['sl_sid']])) {
                $succSid[$date][$_v['sl_sid']] += 1;
            } else {
                $succSid[$date][$_v['sl_sid']] = 1;
            }

            //VIVO收入
//            $temp = oo::commonOprModel('member')->getUserInfo($_v['sl_uid']);
//            if($temp['channel'] == 1){
//                $vivoTotalMoney[$date] += number_format($_v['sl_pusd'],2,".","");
//                $succSid[$date][3] += 1;
//            }
        }
        //所有订单
        foreach ($list2 as $_v2) {
            $_v2['sl_order_time'] = strtotime($_v2['sl_order_time']);
            $_v2['gchannel'] = $goods[$_v2['gid']]['gchannel'] ?? 1;
            $date = date('Ymd', $_v2['sl_order_time']);
            $allRecord[$date] += 1;

            //统计当天的渠道的订单数
            if (isset($totalChannel[$date][$_v2['gchannel']])) {
                $totalChannel[$date][$_v2['gchannel']] += 1;
            } else {
                $totalChannel[$date][$_v2['gchannel']] = 1;
            }

            //统计平台
            if (isset($totalSid[$date][$_v2['sl_sid']])) {
                $totalSid[$date][$_v2['sl_sid']] += 1;
            } else {
                $totalSid[$date][$_v2['sl_sid']] = 1;
            }
        }

        $dayList = $this->getDays(strtotime($stime), strtotime($etime));
        $dayArr = [];
        foreach ($dayList as $day) {
            $dayArr[] = date('Ymd', strtotime($day));
        }

        //点击支付次数统计
        $payReportTotal = $payReportOtherTotal = [];
        if (!empty($dayArr)) {
            $dateStr = implode(",", $dayArr);
            $table = otable::staData();
            $type = 'payReport';
            $sql = "SELECT * FROM {$table} WHERE date IN ({$dateStr}) AND type = '{$type}'";
            $payReportRet = oo::commonOprDb('statistics')->getAll($sql, MYSQLI_ASSOC);
            $sidList = [1, 2, 3];
            //10009支付成功 10010支付取消 10011支付失败
            $tempArr = [10009, 10010, 10011];
            foreach ($payReportRet as $k => $v) {
                if ($v['date'] == date('Ymd')) {
                    $dataTemp = $dataTotalTemp = [];
                    foreach ($tempArr as $eventId) {
                        foreach ($sidList as $sid) {
                            $ret = oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, $eventId));
                            $dataTemp[$eventId]["total"][$sid] = array_sum($ret);
                        }
                    }
                    foreach ($sidList as $sid) {
                        $ret = oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid));
                        $dataTotalTemp['sid'][$sid] = $ret;
                        $dataTotalTemp['total'][$sid] = array_sum($ret);
                    }

                    foreach ($dataTotalTemp['total'] as $sid => $val) {
                        $payReportTotal[$v['date']][$sid] += $val;
                    }

                    foreach ($tempArr as $eventId) {
                        if (isset($dataTemp[$eventId]['total'])) {
                            foreach ($dataTemp[$eventId]['total'] as $sid => $val) {
                                $payReportOtherTotal[$eventId][$v['date']][$sid] += $val;
                            }
                        }
                    }
                } else {
                    $v['data'] = json_decode($v['data'], true);
                    if (isset($v['data']['total'])) {
                        foreach ($v['data']['total'] as $sid => $val) {
                            $payReportTotal[$v['date']][$sid] += $val;
                        }
                    }

                    foreach ($tempArr as $eventId) {
                        if (isset($v['data'][$eventId]['total'])) {
                            foreach ($v['data'][$eventId]['total'] as $sid => $val) {
                                $payReportOtherTotal[$eventId][$v['date']][$sid] += $val;
                            }
                        }
                    }
                }

            }

            if (!isset($payReportTotal[date('Ymd')])) {
                $dataTemp = $dataTotalTemp = [];
                foreach ($tempArr as $eventId) {
                    foreach ($sidList as $sid) {
                        $ret = oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid, $eventId));
                        $dataTemp[$eventId]["total"][$sid] = array_sum($ret);
                    }
                }
                foreach ($sidList as $sid) {
                    $ret = oo::commonOprRedis("Statistics")->hGetAll(okeys::payReport($sid));
                    $dataTotalTemp['sid'][$sid] = $ret;
                    $dataTotalTemp['total'][$sid] = array_sum($ret);
                }
                foreach ($dataTotalTemp['total'] as $sid => $val) {
                    $payReportTotal[date('Ymd')][$sid] += $val;
                }

                foreach ($tempArr as $eventId) {
                    if (isset($dataTemp[$eventId]['total'])) {
                        foreach ($dataTemp[$eventId]['total'] as $sid => $val) {
                            $payReportOtherTotal[$eventId][date('Ymd')][$sid] += $val;
                        }
                    }
                }
            }
        }

        $data = [
            'totalMoney' => $totalMoney,
            'totalMoneyAndroid' => $totalMoneyAndroid,
            'totalMoneyIos' => $totalMoneyIos,
            'totalMoneyVivo' => $totalMoneyVivo,
            'totalRecord' => $totalRecord,
            'totalUid' => $totalUid,
            'allRecord' => $allRecord,
            'dayList' => $dayList,
            'totalChannel' => $totalChannel,
            'succChannel' => $succChannel,
            'totalSid' => $totalSid,
            'succSid' => $succSid,
            'payReportTotal' => $payReportTotal,
            'payReportOtherTotal' => $payReportOtherTotal,
            'vivoTotalMoney' => $vivoTotalMoney,
        ];

        return json_encode($data);
    }


    public function totalData()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');

        $stime = $this->input->post('payment_stime');
        $etime = $this->input->post('payment_etime');
        $sort = $this->input->post('sort');
//        $start =  (int)$this->input->post('start');
//        $length =  (int)$this->input->post('length');

        //时间查询
        $dateArr = array();
        if ($stime) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        } else {
            $stime = date("Y-m-d", time());
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        }
        if ($etime) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        } else {
            $etime = date("Y-m-d", time());
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'hotGoodsList';
        $postData['limit'] = 100;
        $postData['page'] = 0;
        ($this->env == 2) && $postData['demo'] = 1;
//        $res = $this->curl->req($url, $postData);
        $res = $this->hotGoodsList($postData);
        $retData = json_decode($res, TRUE);
        //$channelList = array(1=> 'GooglePlay',2 => 'sms', 3=> 'IOS',  4 => 'Bluecoins', 5 => 'Truemoney', 6 => '12call');
        $channelList = array(1 => 'GooglePlay', 2 => 'IOS', -1 => 'PC');
        //获取后的处理
        if (!empty($retData)) {
            //处理actionIdType
            $total = 0;
            foreach ($retData as $k => &$v) {
                $v['channel'] = $channelList[$v['gchannel']];
                $total = $k + 1;
                $v['index'] = $total;
                $v['money'] = round($v['gprice'] * $v['num'], 2);
            }

            if ($sort == 'money') {
                $last_names = array_column($retData, 'money');
                array_multisort($last_names, SORT_DESC, $retData);
            }

            $data['recordsTotal'] = $total;
            $data['recordsFiltered'] = $total;
            $data['data'] = $retData;
        } else {
            $data = $this->withNodata();
        }

        echo json_encode($data);
    }

    private function hotGoodsList($param)
    {
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $page = oo::functions()->uint($param['page']);//起始页数
        $limit = oo::functions()->uint($param['limit']);//每页数量

        if (empty($stime)) {
            $stime = strtotime('-7 days');
        }//默认为七天前天
        if (empty($etime)) {
            $etime = time();
        }

        $stime = date('Y-m-d 00:00:01', $stime);
        $etime = date('Y-m-d 23:59:59', $etime);
        $slTable = $this->orderTable;
        $goodsTable = $this->goods;
        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if (!empty($blackUidArr)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND uid NOT IN ({$blackUidStr}) ";
        }

        $sql = " SELECT  gid, gname, sl_sid as gchannel, gimg, sl_pusd AS gprice, count(sl_gid) as num
                FROM {$slTable} AS sl 
                JOIN {$goodsTable} AS goods ON  sl.sl_gid = goods.gid  
                WHERE sl.sl_sid <> -1 AND sl.sl_pusd > 0 AND sl.sl_status = 2 {$blackUidSql} AND  sl_order_time >= {$stime} AND sl_order_time <= {$etime}
                GROUP BY sl_gid,sl_pusd,sl_sid
                ORDER BY count(sl_gid) DESC 
                LIMIT $page, $limit";
//        oo::logs()->debug3(['sql'=>$sql], 'Payment.php');

        $goods = oo::commonOprDb('slavedb')->getAll("select * from {$goodsTable}", MYSQLI_ASSOC);
        $goods = array_column($goods, null, 'gid');
        $sql = " SELECT  gid, sid ,  price as gprice , count(gid) as num
                FROM {$slTable}  
                WHERE sid <> -1 AND  price > 0 AND status = 4 {$blackUidSql} AND  created_at >= '{$stime}' AND created_at <= '{$etime}'
                GROUP BY gid,price,sid
                ORDER BY count(gid) DESC 
                LIMIT $page, $limit";
        $list = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);
        empty($list) && $list = [];
        foreach ($list as &$item) {
            $item['gname'] = $goods[$item['gid']]['gname'] ?? '';
            $item['gimg'] = $goods[$item['gid']]['gimg'] ?? '';
            $item['gchannel'] = $item['sid'];
        }
        return json_encode($list);
    }

    /**
     * 付费玩家统计
     */
    public function getPayUserStatistics()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $account = ['visitor' => '游客', 'FB' => 'FB'];
        $device = ['android' => '安卓', 'ios' => '苹果'];

        $playtimes = [0 => '0-100', 101 => '101-500', 501 => '501-2000', 2001 => '2001-5000', 5001 => '5001-10000', 10000 => '10000以上'];
        $accountKey = array_keys($account);
        $deviceKey = array_keys($device);
        $playtimesKey = array_keys($playtimes);
        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();

        if ($stime = get_cookie('payuserindex_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('payuserindex_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'getPayUserStatistics';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if (empty($retData)) {
            $this->load->view('payment/payuserstatistics', $data);
        }

        //获取等级
        $levelKeyList = $this->getLevel();
        $keyLevel = array_keys($levelKeyList);

        $dayList = $retData['dayList'];
        $levelValue = $accountValue = $deviceValue = $timesValue = $playTimesValue = [];

        //获取报表的数据
        foreach ($dayList as $day) {
            $day = date('Ymd', strtotime($day));
            $list = $retData['list'][$day];
            $list = empty($list) ? [] : unserialize($list);
            if (empty($list)) {
                $this->getValue($keyLevel, [], $levelValue);
                $this->getValue($accountKey, [], $accountValue);//账号是游客还是FB
                $this->getValue($deviceKey, [], $deviceValue);//平台
                $this->getValue($playtimesKey, [], $playTimesValue);//局数
            } else {
                $this->getValue($keyLevel, $list['level'], $levelValue);//玩家等级
                $this->getValue($accountKey, $list['account'], $accountValue);//账号是游客还是FB
                $this->getValue($deviceKey, $list['device'], $deviceValue);//平台
                $this->getValue($playtimesKey, $list['times'], $playTimesValue);//局数
            }
        }
        $levelStr = '';
        $accountStr = '';
        $deviceStr = '';
        $playtimesStr = '';
        //等级
        foreach ($levelKeyList as $k => $v) {
            $k > 10 ? $levelStr .= "{name:'" . $v . "' ,visible:false ,data: [" . implode(',', $levelValue[$k]) . ']},' : $levelStr .= "{name:'" . $v . "',data: [" . implode(',', $levelValue[$k]) . ']},';
        }
        //账号
        foreach ($account as $ka => $_va) {
            $accountStr .= "{name:'" . $_va . "',data: [" . implode(',', $accountValue[$ka]) . ']},';
        }
        //平台
        foreach ($device as $kd => $_vd) {
            $deviceStr .= "{name:'" . $_vd . "',data: [" . implode(',', $deviceValue[$kd]) . ']},';
        }
        //筹码
        foreach ($playtimes as $km => $_vm) {
            $playtimesStr .= "{name:'局数【" . $_vm . "】',data: [" . implode(',', $playTimesValue[$km]) . ']},';
        }
        $levelStr = rtrim($levelStr, ',');
        $playtimesStr = rtrim($playtimesStr, ',');

        $data['levelStr'] = $levelStr;
        $deviceStr = rtrim($deviceStr, ',');
        $data['displayStr'] = $accountStr . $deviceStr;
        $data['playtimesStr'] = $playtimesStr;
        $data['dayList'] = $dayList;
        $this->load->view('payment/payuserstatistics', $data);
    }

    /**
     * 获取数据
     * @param $levelKey
     * @param $loseLevel
     * @param $loseLevelValue
     * @return mixed
     */
    private function getValue($levelKey, $loseLevel, &$loseLevelValue)
    {
        foreach ($levelKey as $kl) {
            $loseLevelValue[$kl] = isset($loseLevelValue[$kl]) ? $loseLevelValue[$kl] : [];
            array_push($loseLevelValue[$kl], $loseLevel[$kl] ?? 0);
        }
        return $loseLevelValue;
    }

    /**
     * 获取等级
     * @return array
     */
    public function getLevel()
    {
        $data = [];
        for ($i = 1; $i <= 30; $i++) {
            $data[$i] = '等级' . $i;
        }
        return $data;
    }

    /**
     * 进行补发
     */
    public function reissue()
    {
        $params = $this->input->post();

        $postData = [
            "game" => "cc",
            "uid" => $params['uid'],
            "inner_order_id" => $params['orderId'],
            "product_id" => $params['sku'],
            "external_order_id" => $params['payId'],
        ];

        if (empty($postData['uid']) || empty($postData['inner_order_id']) || empty($postData['product_id']) || empty($postData['external_order_id'])) {
            $this->response(1, '参数错误');
        }

        $username = get_cookie('username');
        $chineseName = get_cookie('chinesename');
        $postData['operator'] = "$chineseName($username)";

        $curEnv = $this->config->item('CUR_ENV') ?: "";

        if ($curEnv == "prod") {
            $url = "http://platform.superant.cc/common/order/retry";
        } else {
            $url = "http://test.platform.superant.cc/common/order/retry";
        }

        $ret = Curl::json_post($url, json_encode($postData, JSON_NUMERIC_CHECK));
        $ret = json_decode($ret, true);

        if ($ret['code'] == 1) {
            $this->response(0, '补发成功');
        } else {
            $this->response(1, $ret['msg']);
        }
    }

    /**
     * 查询订单流水号
     */
    public function detail()
    {
        $uid = $this->input->post('uid');
        $orderId = $this->input->post('orderId');
        if (empty($uid) || empty($orderId)) {
            $this->response(1, '参数错误');
        }
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postData;
        $postData['orderId'] = $orderId;
        $postData['uid'] = $uid;
        $postData['mod'] = 'Payment';
        $postData['act'] = 'detail';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        die($res);
    }

    /**
     *   新版对账    2018-1-23
     */
    public function checking($channletype = 1)
    {
        $data = array('channelList' => array(1 => 'GooglePlay', 2 => 'IOS'), 'list' => [], 'channeltype' => $channletype, 'currencyname' => array(1 => '美元', 2 => '港币', 3 => '美元'));

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'checking';
        $this->postData['channletype'] = $channletype;
        $res = $this->curl->req($url, $this->postData);
        $retData = json_decode($res, 1);
        $data['list'] = $retData['list'];
        $data['channelname'] = $data['channelList'][$channletype];
        $dateList = $localList = $otherList = array();
        if ($data['list']) {
            foreach ($data['list'] as $value) {
                $dateList[] = date('Y-m', $value['check_time']);
                $local_totalmoney[] = $value['local_totalmoney'] * $value['exchange_rate'];
                $other_totalmoney[] = $value['other_totalmoney'];
            }
        }
        $dateList = array_reverse($dateList);
        $local_totalmoney = array_reverse($local_totalmoney);
        $other_totalmoney = array_reverse($other_totalmoney);
        $data['dateList'] = $dateList;
        $data['local_totalmoney'] = $local_totalmoney;
        $data['other_totalmoney'] = $other_totalmoney;
        $this->load->view('payment/checking', $data);
    }

    /**
     *   新版对账，添加支付渠道金额处理入库
     */
    public function actionChecking()
    {
        $pay_channel = $this->input->post('pay_channel');
        $pay_money = $this->input->post('pay_money');
        $pay_ordernum = $this->input->post('pay_ordernum');
        $pay_currency = $this->input->post('pay_currency');
        $pay_time = $this->input->post('pay_time');
        $other_income = $this->input->post('other_income');
        $exchange_rate = $this->input->post('exchange_rate');//新加货币汇率

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        //新加货币汇率
        if (empty($exchange_rate)) {
            $this->retdata['message'] = '添加失败';
            die(json_encode($this->retdata));
        }

        $this->postData['pay_channel'] = $pay_channel;//支付渠道
        $this->postData['pay_money'] = $pay_money;//收入
        $this->postData['pay_ordernum'] = $pay_ordernum;//订单数量
        $this->postData['pay_currency'] = $pay_currency;//货币
        $this->postData['pay_time'] = $pay_time;//日期
        $this->postData['other_income'] = $other_income;//财务收入
        $this->postData['exchange_rate'] = $exchange_rate;//新加货币汇率

        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'actionChecking';
        $res = $this->curl->req($url, $this->postData);

        $resData = json_decode($res, 1);

        $retCode = $resData['code'];
        if ($retCode == 1) {
            $this->retdata['state'] = 'success';
            $this->retdata['message'] = '添加成功';
            $this->retdata['refresh'] = TRUE;
        } else {
            $this->retdata['message'] = '添加失败';
        }
        die(json_encode($this->retdata));
    }


    /**
     * ajax编辑财务收入
     */
    public function ajaxEditIncome()
    {
        $id = $this->input->post('id');
        $field = $this->input->post('field');
        $val = $this->input->post('val');

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'ajaxEditIncome';
        $postData = array_merge(array('id' => $id, 'field' => $field, 'val' => $val), $this->postData);
        $res = $this->curl->req($url, $postData);
    }

    /**
     * 支付渠道屏蔽管理
     */
    public function switch()
    {
//        if(!$this->isAdmin()) {//如果不是管理员没有权限查看用户列表
//            redirect('permission/forbidpage');
//            exit;
//        }
        $data = array('v' => '', 's' => '');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'switch';
        $res = $this->curl->req($url, $this->postData);
        if ($res) {
            $info = json_decode($res, 1);
            $data['v'] = $info['v'];
            $data['s'] = $info['s'];
            $data['sidlist'] = $info['sidlist'];
        }
        $this->load->view('payment/switch', $data);
    }

    /**
     * 更新支付管理
     */
    public function actionSwitch()
    {
        $name = $this->input->post('name');
        $val = $this->input->post('val');

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'actionSwitch';
        $postData = array_merge(array('keyname' => $name, 'keyval' => $val), $this->postData);
        $res = $this->curl->req($url, $postData);
    }


    public function firstbuy()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();

        if ($stime = get_cookie('payuserindex_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('payuserindex_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'getFirstBuy';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        $dayList = $retData['dayList'];
        $firstBuyList = $payList = $loginList = $firstPayList = [];
        if (!empty($dayList)) {
            $loginListData = $retData['loginList'];
            $slListData = $retData['slList'];
            foreach ($dayList as $day) {
                $firstTemp = 0;
                $payTemp = $slListData[$day]['payNum'] ?? 0;//付费用户
                $firstPayTemp = $slListData[$day]['firstPayNum'] ?? 0;//首次付费用户
                $loginTemp = $loginListData[$day] ?? 0;
                foreach ($slListData[$day]['firstBuy'] as $v) {
                    $firstTemp += $v;
                }
                $payPercent = empty($payTemp) ? 0 : round($firstTemp * 100 / $payTemp, 2);
                $firstPayPercent = empty($payTemp) ? 0 : round($firstTemp * 100 / $firstPayTemp, 2);
                $loginPercent = empty($loginTemp) ? 0 : round($firstTemp * 100 / $loginTemp, 2);
                array_push($firstBuyList, $firstTemp);
                array_push($payList, $payPercent);
                array_push($firstPayList, $firstPayPercent);
                array_push($loginList, $loginPercent);
            }
        }
        $displayStr = $this->getSerialStr('首冲商品', $firstBuyList);
        $displayStr .= ',' . $this->getSerialStrPer('首冲商品/支付人数', $payList);
        $displayStr .= ',' . $this->getSerialStrPer('首冲商品/首次支付人数', $firstPayList);
        $displayStr .= ',' . $this->getSerialStrPer('首冲商品/DAU', $loginList);
        $data['displayStr'] = $displayStr;
        $data['dayList'] = $dayList;
        $this->load->view('payment/firstbuy', $data);
    }

    /**
     * 单日购买商品排行榜
     */
    public function todayBugGoodsRank($sort = 'number')
    {
        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('payment_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        } else {
            $data['stime'] = date('Y-m-d', strtotime('-7 days'));
        }
        if ($etime = get_cookie('payment_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        } else {
            $data['etime'] = date('Y-m-d', time());
        }
        $data['sort'] = $sort;
        $this->load->view('payment/todayBugGoodsRank', $data);
    }

    /**
     * 商品购买成功率曲线
     */
    public function goodsPaySuccess()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();

        if ($stime = get_cookie('stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        $sid = get_cookie('sid');
        if (empty($sid)) {
            $sid = 999;
        }

        $gname = get_cookie('gname');

        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'goodsPaySuccess';
        $postData['sidList'] = json_encode([$sid]);
        $postData['gname'] = $gname;
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        $dayList = $retData['dayList'];

        $goodsAll = $goods = $retSuccess = $retAll = [];
        if (!empty($dayList)) {
            foreach ($dayList as $k => $v) {
                foreach ($retData['retAll'][$k] as $a_k => $a_v) {
                    $retAll[$k][$a_v['sl_gid']] = $a_v['count'];
                }
                foreach ($retData['retSuccess'][$k] as $a_k => $a_v) {
                    $retSuccess[$k][$a_v['sl_gid']] = $a_v['count'];
                }
            }

            foreach ($retData['goods'] as $k => $v) {
                $goods[$v['gid']] = $v['gname'];
                $goodsAll[] = $v['gid'];
            }
        }

        $data['dayList'] = $dayList;
        $data['goodsAll'] = $goodsAll;
        $data['goods'] = $goods;
        $data['retSuccess'] = $retSuccess;
        $data['retAll'] = $retAll;
        $data['gname'] = $gname;
        $data['retDau'] = $retData['retDau'];
        $data['sid'] = $sid;

        $this->load->view('payment/goodsPaySuccess', $data);
    }

    //支付白名单
    public function payWhite()
    {
        $url = $this->config->item('officialUrl');
        $this->postData['mod'] = 'Payment';
        $this->postData['act'] = 'payWhite';
        $retData = $this->curl->req($url, $this->postData);
        if (!empty($retData)) {
            $retData = json_decode($retData, 1);
            $data['content'] = $retData['list'];
        }

        $this->load->view('payment/payWhite', $data);
    }

    //设置支付白名单
    public function setPayWhite()
    {
        $url = $this->config->item('officialUrl');
        $postData = $this->input->post('content');
        $postData = str_replace("，", ",", $postData);
        $postData = str_replace(" ", "", $postData);
        $posts = $this->postData;
        $posts['mod'] = 'Payment';
        $posts['act'] = 'setPayWhite';
        $posts['content'] = $postData;
        $this->curl->req($url, $posts);
        $return['state'] = 'success';
        $return['message'] = '成功';
        $return['refresh'] = true;
        die(json_encode($return));
    }

    /**
     * 首充分析
     */
    public function firstPunch()
    {
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $data = array('stime' => '', 'etime' => '');

        //时间查询
        $dateArr = array();

        if ($stime = get_cookie('payuserindex_stime')) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . '0:0:1');
        } else {
            $dateArr['stime'] = strtotime('- 7 days 0:0:1');//默认开始时间
            $data['stime'] = date('Y-m-d', $dateArr['stime']);
        }

        if ($etime = get_cookie('payuserindex_etime')) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . '23:59:59');
        } else {
            $dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
            $data['etime'] = date('Y-m-d', $dateArr['etime']);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postData);
        $postData['mod'] = 'Payment';
        $postData['act'] = 'firstPunch';
        $postData['sidList'] = json_encode([1, 2]);
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        $firstPayPercent = $firstPunchPercent = [];
        foreach ($retData['firstPayPlayerNumList'] as $fk => $fv) {
            $firstPayPercent[] = round($fv / $retData['firstPayPlayerOrderNumList'][$fk] * 100, 2);
        }
        foreach ($retData['firstPunchNumList'] as $fk => $fv) {
            $firstPunchPercent[] = round($fv / $retData['firstPunchOrderNumList'][$fk] * 100, 2);
        }
        $retData['firstPayPercent'] = $firstPayPercent;
        $retData['firstPunchPercent'] = $firstPunchPercent;

        $data['data'] = $retData;
        $this->load->view('payment/firstPunch', $data);
    }

    public function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    public function orderStatusSummary()
    {
        $statusMap = [
            '-2' => '已失效订单数',
            '-1' => '已取消订单数',
            '0' => '已创建订单数',
            '1' => '已支付订单数',
            '2' => '验证成功订单数',
            '3' => '已退款订单数',
            '4' => '已发货订单数',
        ];
        $time = time();
        $stime = $time - 7 * 86400;
        $etime = $time;
        if ($inputstime = get_cookie('stime')) {
            $stime = strtotime($inputstime);
        }
        if ($inputetime = get_cookie('etime')) {
            $etime = strtotime($inputetime);
        }
        if (($etime - $stime) > 86400 * 15) $etime = $stime + 86400 * 15;
        if ($etime < $stime) $etime = $stime;
        $stime = date('Y-m-d', $stime);
        $etime = date('Y-m-d 23:59:59', $etime);
        $tbl = otable::order(date("Y", strtotime($stime)));
        $sql = "select * from {$tbl} where created_at >= '{$stime}' and  created_at <= '{$etime}' ";
        $orders = oo::commonOprDb('slavedb')->getAll($sql);
        $formatOrders = [];
        $dayList = [];
        $defaultData = [];
        $date = $stime;
        while ($date <= $etime) {
            $dayList[] = $date;
            $defaultData[$date] = 0;
            $date = date('Y-m-d', strtotime($date) + 86400);
        }
        foreach ($statusMap as $status => $text) {
            $formatOrders[$status] = $defaultData;
        }
        foreach ($orders as $order) {
            if (empty($formatOrders[$order['status']])) continue;
            $date = date('Y-m-d', strtotime($order['created_at']));
            $formatOrders[$order['status']][$date]++;
        }
        $data = [
            'stime' => $stime,
            'etime' => date('Y-m-d', strtotime($etime)),
            'statusMap' => $statusMap,
            'formatOrders' => $formatOrders,
            'dayList' => $dayList,
        ];
        $this->load->view('payment/orderStatusSummary', $data);
    }
}
