<?php
class zybAction extends baseAction
{
    /**
     * @method 资源包管理首页
     * @author zhengweihua 
     * @copyright 2022-08-02
     */
    public function index()
    {
        $Params = mvc::$URL_PARAMS;
       
        $MainBase = new MainBase();
        $statusArr = ['-2' => '退款', '-1' => '过期', '0' => '待付款', '1' => '正常'];
        $styleArr = ['vin' => 'vin解码','common' => '普通接口'];

        $field = ["SUM(az_count) as total,SUM(az_count_has) as countHas,az_type"];
        $recordRes = $MainBase->get('api_zyb', ['*'], sprintf(" and az_status=1 and az_etime >%d and az_uid = %d order by az_id desc", time() - 15*86400, $_SESSION['_userid']));
        $vinzybInfo = $MainBase->get('api_zyb', $field, sprintf(" and az_style='vin' and az_status=1  and az_etime >%d and az_uid = %d group by az_type order by az_etime asc", time(), $_SESSION['_userid']));
        $mycommonZybRes = $MainBase->get('api_zyb', $field, sprintf(" and az_style='common' and az_status=1 and az_count_has > 0 and az_etime >%d and az_uid = %d group by az_type order by az_etime asc", time(), $_SESSION['_userid']),true);
        //统计三十天内的查询数据
        $tjArr = [];
        $starttime = strtotime("-30 day",strtotime(date('Y-m-d')));
        $endtime = time();
        $field = ["FROM_UNIXTIME(azl_atime, '%Y-%m-%d') as search_date,SUM(azl_change) as total,azl_style"];
        $where = sprintf(" and azl_atime>%d and azl_atime<%d  and azl_uid=%d  and az_type = 'per' group by azl_style, FROM_UNIXTIME(azl_atime, '%s') ORDER BY FROM_UNIXTIME(azl_atime, '%s') desc",$starttime,$endtime,$_SESSION['_userid'],'%Y-%m-%d','%Y-%m-%d');
        $res = $MainBase->get('api_zyb_list left join api_zyb on azl_az_id = az_id',$field,$where);
        foreach ($res['data'] as $item) {
            $tjArr[$item['search_date']][$item['azl_style']] += abs($item['total']);
        }
        //vin解码资源包分类统计：每日次数 + 按次购买次数（仿控制台统计逻辑）
        $B2cBase = new B2cBase();
        $shopVin = $B2cBase->get('sh_shop',['shop_vin_count'],sprintf("and shop_uid=%d",$_SESSION['_userid']),true);
        $vinDayCount = intval($shopVin['data']['shop_vin_count']);
        $vinPerCount = 0;
        if(count($vinzybInfo['data'])>0){
            foreach ($vinzybInfo['data'] as $value) {
                if($value['az_type']=='per'){
                    $vinPerCount += intval($value['countHas']);
                }else{
                    $vinDayCount += intval($value['total']);
                }
            }
        }
        $vinCountText = $vinDayCount.'次/天'.($vinPerCount>0?' + '.$vinPerCount.'次':'');
        LibTpl::Set('tjArr', $tjArr);     
        LibTpl::Set('statusArr', $statusArr);
        LibTpl::Set('vinzyb', $vinzybInfo['data']);
        LibTpl::Set('vinCountText', $vinCountText);
        LibTpl::Set('commonZyb',$mycommonZybRes['data']);
        LibTpl::Set('zybRecordList', $recordRes['data']);
        LibTpl::Set('styleArr',$styleArr);
        LibTpl::Set('Params', $Params);
        LibTpl::Put();
    }

    /**
     * @method 购买资源包
     * @author zhengweihua 
     * @copyright 2022-08-02
     */
    public function buy()
    {
        $Params = mvc::$URL_PARAMS;
        $styleArr = [
            'vin' => 'vin解码',
            'common' => '普通'
        ];
        if (empty($Params['az_style'])) {
            $url  = mvc::$cfg['SELF_URI'] . 'zyb/index';
            LibTpl::Error('参数错误', $url, 2);
        }
        $LibYpApi =  new LibYpApi();
        $zybPriceRes   =  $LibYpApi->Get('zyb/getZybPrice');

        LibTpl::Set('zybList', $zybPriceRes['data']);
        LibTpl::Set('styleArr', $styleArr);
        LibTpl::Set('Params', $Params);
        // LibTpl::Set('currentZyb', $currentZyb);
        LibTpl::Put();
    }

    /**
     * @method 创建资源包订单
     * @author zhengweihua 
     * @copyright 2022-08-02
     */
    function buildZybOrder()
    {
        $Params = MVC::$URL_PARAMS;
        $getArr = [
            'uid' => $_SESSION['_userid'],
            'style' => $Params['style'],
            'stylekey' => $Params['stylekey']
        ];
        $LibYpApi = new LibYpApi();
        $res = $LibYpApi->Get('zyb/buildZybOrder', $getArr);
        $orderId = $res['data'];
        $postArr = [
            'az_id' => $orderId,
            'payBy' => $Params['payBy'],
            'payType' => $Params['payType'],
            'oth' => [
                'from' => mvc::$cfg['PJLAPI']['from']
            ]
        ];
        $res = $LibYpApi->Get('zyb/payZybOrder', [], $postArr);
        if ($Params['payBy'] == 'alipay' && $Params['payType'] != 'app') {
            $res['data']['por_return_data']['pay_form'] = base64_decode($res['data']['por_return_data']['pay_form']);
        }
        $res['data']['az_id'] = $orderId;
        LibFc::ajaxJsonEncode($res);
    }

    /**
     * @method 检查支付
     * @author zhengweihua 
     * @copyright 2022-08-02
     */
    function checkZybOrderPay()
    {
        $Params = mvc::$URL_PARAMS;
        $LibYpApi = new LibYpApi();
        $res = $LibYpApi->Get('zyb/checkZybOrderPay', $Params);
        LibFc::ajaxJsonEncode($res);
    }

    /**
     * @method 资源包使用明细
     * @author zhengweihua 
     * @copyright 2022-08-02
     */
    public function lists()
    {
        $Params  = mvc::$URL_PARAMS;
        $MainBase = new MainBase();
        $where = '';

        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

        foreach ($Params as $filed => $val) {
            $val = is_array($val) ? $val : trim($val);

            if ($val == '') continue;
            switch ($filed) {
                case 'az_style':
                    $where  .= sprintf(" and azl_style='%s'", $val);
                    break;
                case 'azl_az_id':
                    $where  .= sprintf(" and azl_az_id=%d", $val);
                    break;
                case 'azl_atime':
                        $t = explode(' ~ ', $val);
                        $where .= sprintf(" and azl_atime >= %d and azl_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
                    break;
            }
        }
        $lists = [];
        $table = 'api_zyb_list';
		$res = $MainBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count'];
        if($total>0){
            $where  .= sprintf(" and azl_uid=%d order by azl_atime desc",$_SESSION['_userid']);
            $res =  $MainBase->get($table, ['*'], sprintf("%s limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
            $lists = $res['data'];
        }
        LibTpl::Set('pageMsg', LibPage::Show($total, $perPage, true));
        LibTpl::Set('lists',$lists);   
        LibTpl::Set('Params',$Params);
        LibTpl::put();
    }
}
