<?php

/**
 * +----------------------------------------------------------------------
 * | Created By PhpStorm
 * +----------------------------------------------------------------------
 * | DATE: 2021/3/25
 * +----------------------------------------------------------------------
 * | TIME: 10:47
 * +----------------------------------------------------------------------
 * | Author: YangXing(925032253@qq.com)
 * +----------------------------------------------------------------------
 * | Class: servicePushAction 服务推送管理
 * +----------------------------------------------------------------------
 */

class servicePushAction
{
    //服务推送
    public function index()
    {
        LibRule::Check('JS05');
        $param = mvc::$URL_PARAMS;
        $where = '';
        $page = isset($param['page']) && $param['page'] > 0 ? (int) $param['page'] : 1;
        $pageSize = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];
        //TODO 过滤字段
        if(is_numeric($param['status'])){
            $where .= sprintf(" and stu_status='%s'",$param['status']);
        }
        if($param['shop_name']){
            $where .= sprintf(" and pl_shop.shop_name like'%%%s%%'",$param['shop_name']);
        }
        if($param['username']) {
            $LibYpApi = new LibYpApi();
            $post = [
                'filed' => ['u_id'],
                'where' => sprintf(" and (u_name like '%%%s%%' or u_nickname like '%%%s%%' or u_mobile like '%%%s%%')", LibFc::Escape($param['username']), LibFc::Escape($param['username']), LibFc::Escape($param['username'])),
                'oneRow' => false
            ];
            $userArr = $LibYpApi->Get('user/getUser', [], $post);
            $userArr = array_column($userArr['data'], 'u_id');
            if (!empty($userArr)) $where .= sprintf(" and pl_shop.shop_pu_id in(%s)", implode(',', $userArr));
        }
        $PjlBase = new PjlBase();
        $count = $PjlBase->get('pl_tuisong join pl_shop on stu_shop_id=shop_id',['count(*) as count'],$where,true);

        if($count['data']['count'] > 0){
            $where .= sprintf(" group by stu_shop_id order by stu_shop_id limit %s,%s",($page-1)*$pageSize,$pageSize);

            $data = $PjlBase->get('pl_tuisong join pl_shop on stu_shop_id=shop_id',['pl_shop.shop_name,pl_shop.shop_pu_id,pl_tuisong.*','pl_shop.shop_tsfw_vin_count'],$where);
            $weekArr = [
                1 => '周一',
                2 => '周二',
                3 => '周三',
                4 => '周四',
                5 => '周五',
                6 => '周六',
                0 => '周日'
            ];
            $brandList = (new ComBase)->get('bc_brand', ['brand_id','brand_name'], ' order by brand_initial');
            $brandList = array_column($brandList['data'],'brand_name','brand_id');
            LibTpl::Set('brand',$brandList);
            $stuShopId = implode(',',array_column($data['data'],'stu_shop_id'));
            $brandId = $PjlBase->get('pl_tuisong_brand',['stb_shop_id','stb_brand_id'],sprintf(" and stb_shop_id in(%s)",$stuShopId));
            $temp = [];
            if(!empty($brandId['data'])){
                foreach ($brandId['data'] as $id){
                    $temp[$id['stb_shop_id']][] = $brandList[$id['stb_brand_id']];
                }
            }
            $cityId = $PjlBase->get('pl_tuisong_city join yp_province_city on stc_pc_id=pc_id',['pl_tuisong_city.*','pc_name_des'],sprintf(" and stc_shop_id in (%s)",$stuShopId));
            $cityId = $cityId['data'];
            $cityData = [];
            if(!empty($cityId)){

                foreach ($cityId as $value){
                    if(strpos($value['pc_name_des'],',') !== false){
                        $cityData[$value['stc_shop_id']][] = $value['pc_name_des'];
                    }
                }
            }
            foreach ($data['data'] as &$value){
                if(isset($temp[$value['stu_shop_id']])){
                    $value['stu_brand_id'] = implode('<br>',$temp[$value['stu_shop_id']]);
                }else{
                    $value['stu_brand_id'] = '';
                }
                if(isset($cityData[$value['stu_shop_id']])){
                    foreach ($cityData[$value['stu_shop_id']] as &$y){
                        $y = str_replace(',','',$y);
                    }
                    $value['stu_city'] = implode('<br>',$cityData[$value['stu_shop_id']]);
                }else{
                    $value['stu_city'] = '';
                }
                switch ($value['stu_status']){
                    case '1':
                        $value['stu_status_name'] = '<span class="green">启用</span>';
                        break;
                    case '0':
                        $value['stu_status_name'] = '<span class="orange">停用</span>';
                        break;
                    case '-1':
                        $value['stu_status_name'] = '<span class="gray">禁用</span>';
                        break;
                }
                $value['stu_bhour'] = str_split($value['stu_bhour'],2);
                $value['stu_bhour'] = implode(":",$value['stu_bhour']);
                $value['stu_ehour'] = str_split($value['stu_ehour'],2);
                $value['stu_ehour'] = implode(":",$value['stu_ehour']);
                if(!empty($value['stu_weeks']) || $value['stu_weeks'] == 0){
                    $value['stu_weeks'] = explode(',',$value['stu_weeks']);
                    foreach ($value['stu_weeks'] as &$v){
                        if(isset($weekArr[$v])){
                            $v = $weekArr[$v];
                        }
                    }
                    $value['stu_weeks'] = implode(',',$value['stu_weeks']);
                }
            }
        }


        LibTpl::Set('title','推送服务');
        LibTpl::Set('page',LibPage::Show($count['data']['count'], $pageSize));
        LibTpl::Set('data',$data['data'] ?: []);
        LibTpl::Set('param',$param);
        LibTpl::Put();
    }

    public function addPush()
    {
        LibRule::Check('JS05');
        if(!empty($_POST)){
            $shopId = (int) $_POST['ts']['stu_shop_id'];
            $hour = [];
            /*if(!empty($_POST['ts']['stu_bhour'])){
                $hour = explode(' ~ ', str_replace(':', '', $_POST['ts']['stu_bhour']));
            }
            $_POST['ts']['stu_daymax'] = (int) $_POST['ts']['stu_daymax'];
            if($_POST['ts']['stu_daymax'] > 32767){
                LibFc::ajaxJsonEncode(['status' => false,'data' => '日推限制数超过MySql最大限制']);
            }
            if(mb_strlen($_POST['ts']['stu_remark']) > 255){
                LibFc::ajaxJsonEncode(['status' => false,'data' => '备注长度超过MySql最大限制']);
            }*/
            $baseArr = [
                'stu_status' => (int) $_POST['ts']['stu_status'],
               /* 'stu_bhour' => isset($hour[0]) ? $hour['0'] : '',
                'stu_ehour' => isset($hour[1]) ? $hour['1'] : '',
                'stu_weeks' => !empty($_POST['ts']['stu_weeks'] ) ? implode(',', $_POST['ts']['stu_weeks']) : '',
                'stu_daymax' => (int) $_POST['ts']['stu_daymax'] ?: '',*/
                'stu_remark' => $_POST['ts']['stu_remark'] ? htmlentities($_POST['ts']['stu_remark']) : ''
            ];
            $PjlBase = new PjlBase;
            $data = $PjlBase->get('pl_tuisong',['1'],sprintf(" and stu_shop_id=%d",$shopId),true);
            if(empty($data['data'])){
                $baseArr['stu_shop_id'] = $shopId;
                $result = $PjlBase->add('pl_tuisong',$baseArr);
            }else{
                $result = $PjlBase->set('pl_tuisong',$baseArr,sprintf(" and stu_shop_id=%d",$shopId));
            }
            LibFc::ajaxJsonEncode($result);
        }else{
            throw new Exception('请求错误','1001');
        }
    }

    public function give()
    {
        LibRule::Check('JS07');
        $_POST['tuc_change'] = (int) $_POST['tuc_change'];
        if($_POST['tuc_change'] <= 0){
            LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        }
        if((int) $_POST['tuc_shop_id'] <= 0){
            LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        }
        $postData = [
            'tuc_shop_id' => (int) $_POST['tuc_shop_id'],
            'tuc_uid' => (int) $_POST['tuc_uid'],
            'tuc_style' => 'vin',
            'tuc_change' => $_POST['tuc_change'],
            'tuc_des' => '系统赠送',
            'tuc_by' => $_SESSION['admin_uname'],
            'tuc_remark' => $_POST['tuc_remark']
        ];
        $result = (new LibYpApi)->Get('pjl/changeTsfwPac',[],$postData,true);
        LibFc::ajaxJsonEncode($result);
    }

    //推送赠送记录
    public function getPushGiveRecord()
    {
        LibRule::Check('JS07');
        $param = mvc::$URL_PARAMS;
        $page = isset($param['page']) && $param['page'] > 0 ? (int) $param['page'] : 1;
        $pageSize = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];

        $PjlBase= new PjlBase();
        $where = sprintf(" and tuc_des like '%%%s%%'",'赠送');
        foreach($param as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
                case 'betime':
                    $t = explode(' ~ ', $v);
                    $where .= sprintf(" and tul_atime >= %d and tul_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
                    break;
                case 'shop_name':
                    $where .= sprintf(" and pl_shop.shop_name like '%%%s%%'",$v);
                    break;
                case 'username':
                    $LibYpApi = new LibYpApi();
                    $post = [
                        'filed' => ['u_id'],
                        'where' => sprintf(" and (u_name like '%%%s%%' or u_nickname like '%%%s%%' or u_mobile like '%%%s%%')", LibFc::Escape($param['username']), LibFc::Escape($param['username']), LibFc::Escape($param['username'])),
                        'oneRow' => false
                    ];
                    $userArr = $LibYpApi->Get('user/getUser', [], $post);
                    $userArr = array_column($userArr['data'], 'u_id');
                    if (!empty($userArr)) $where .= sprintf(" and pl_shop.shop_pu_id in(%s)", implode(',', $userArr));
                    break;

            }
        }


        $count = $PjlBase->get('pl_tuisong_change left join pl_shop on tuc_shop_id=shop_id',['count(*) as count'],$where,true);
        if($count['data']['count'] > 0 ){
            $where .= sprintf(" order by tuc_id desc limit %d,%d",($page-1)*$pageSize,$pageSize);
            $list = $PjlBase->get('pl_tuisong_change left join pl_shop on tuc_shop_id=shop_id', ['pl_tuisong_change.*,pl_shop.shop_name'], $where);
            $uIds = array_filter(array_unique(array_column($list['data'],'tuc_uid')));
            $LibYpApi = new LibYpApi();
            $post = [
                'filed' => ['u_name','u_id'],
                'where' => sprintf(" and u_id in (%s)", implode(',',$uIds)),
                'oneRow' => false
            ];
            $userArr = $LibYpApi->Get('user/getUser', [], $post);
            $userArr = array_column($userArr['data'], 'u_name','u_id');
            foreach ($list['data'] as &$value){
                if(isset($userArr[$value['tuc_uid']])){
                    $value['tuc_uid'] = $userArr[$value['tuc_uid']];
                }
            }
            LibTpl::Set('list',$list['data']);
        }

        LibTpl::Set('page',LibPage::Show($count['data']['count'],$pageSize));
        LibTpl::Set('title','赠送次数变更记录');
        LibTpl::Set('param',$param);
        LibTpl::Put();
    }

    public function addPage()
    {
        LibRule::Check('JS05');
        $param = mvc::$URL_PARAMS;
        $shopId = (int) $param['shop_id'];
        if((int) $shopId <= 0){
            throw new Exception('参数错误','1001');
        }
        $PjlBase = new PjlBase;
        $shopData = $PjlBase->get('pl_shop',['shop_id','shop_name'],sprintf(" and shop_id=%d",$shopId),true);
        if (empty($shopData['data'])){
            throw new Exception('店铺不存在','1002');
        }
        $data = $PjlBase->get('pl_tuisong',['*'],sprintf(" and stu_shop_id=%d",$shopId),true);
        $weekArr = [
            1=>'周一',
            2=>'周二',
            3=>'周三',
            4=>'周四',
            5=>'周五',
            6=>'周六',
            0=>'周日'
        ];
        if(!empty($data['data'])){
            $data['data']['stu_bhour'] = str_split($data['data']['stu_bhour'],2);
            $data['data']['stu_bhour'] = implode(":",$data['data']['stu_bhour']);
            $data['data']['stu_ehour'] = str_split($data['data']['stu_ehour'],2);
            $data['data']['stu_ehour'] = implode(":",$data['data']['stu_ehour']);
            $data['data']['stu_weeks'] = explode(',',$data['data']['stu_weeks']);
        }
        LibTpl::Set('title','推送服务');
        LibTpl::Set('param',$param);
        LibTpl::Set('tsArr',$data['data'] ?: []);
        LibTpl::Set('shopData',$shopData);
        LibTpl::Set('weekArr',$weekArr);
        LibTpl::Put();
    }

    public function pushRecord()
    {
        LibRule::Check('JS06');
        $param = mvc::$URL_PARAMS;
        $page = isset($param['page']) && $param['page'] > 0 ? (int) $param['page'] : 1;
        $pageSize = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];

        $fastTime = [
            '本月'=>date('Y-m-01').' ~ '.date('Y-m-d'),
            '上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
            '本年'=>date('Y-01-01').' ~ '.date('Y-m-d')
        ];
        LibTpl::Set('fastTime', $fastTime);
        $groupByArr = [
            'day'=>['日统计', '%Y-%m-%d'],
            'month'=>['月统计', '%Y-%m'],
            'year'=>['年统计', '%Y']
        ];
        LibTpl::Set('groupByArr', $groupByArr);
        $param['group'] = empty($groupByArr[$param['group']]) ? 'day': $param['group'];
        $groupBy = $groupByArr[$param['group']][1];
        $PjlBase= new PjlBase();
        $param['betime'] = empty($param['betime'])? $fastTime['本月']: $param['betime'];

        foreach($param as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
                case 'betime':
                    $t = explode(' ~ ', $v);
                    $where .= sprintf(" and tul_atime >= %d and tul_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
                    break;
            }
        }
        $group = '';
        $table = 'pl_tuisong_list';
        if($param['is_shop']){
            $table = 'pl_tuisong_list inner join pl_shop on shop_id=tul_shop_id';
            $group = sprintf(" group by FROM_UNIXTIME(tul_atime, '%s'),tul_shop_id ORDER BY FROM_UNIXTIME(tul_atime, '%s') desc", $groupBy, $groupBy);
            $field = ["shop_name,FROM_UNIXTIME(tul_atime, '".$groupBy."') as tul_atime, count(*) as count,sum(CASE WHEN tul_tuc_id > 0 THEN 1 ELSE 0 END) as tul_mon_id_count"];
        }else{
            $group = sprintf(" group by FROM_UNIXTIME(tul_atime, '%s') ORDER BY FROM_UNIXTIME(tul_atime, '%s') desc", $groupBy, $groupBy);
            $field = ["FROM_UNIXTIME(tul_atime, '".$groupBy."') as tul_atime, count(*) as count,sum(CASE WHEN tul_tuc_id > 0 THEN 1 ELSE 0 END) as tul_mon_id_count"];
        }
        $sql = sprintf("select %s from %s where 1=1 %s", implode(',', $field), $table, $where.$group);

        $count =$PjlBase->get('('.$sql.') as tt',['count(*) as count'],'',true);
        if($count['data']['count'] > 0){
            if($param['is_shop']){
                $group = sprintf(" group by FROM_UNIXTIME(tul_atime, '%s'),tul_shop_id ORDER BY FROM_UNIXTIME(tul_atime, '%s') desc", $groupBy, $groupBy);
            }else{
                $group = sprintf(" group by FROM_UNIXTIME(tul_atime, '%s') ORDER BY FROM_UNIXTIME(tul_atime, '%s') desc", $groupBy, $groupBy);
            }
            $wheres = $where;
            $wheres .= sprintf(" and tul_style='vin'");
            $wheress = $where;
            $wheress .= sprintf(" and tul_style='model'");
            $vinCount = $PjlBase->get($table,["FROM_UNIXTIME(tul_atime, '".$groupBy."') as tul_atime,count(DISTINCT tul_vin) as vin_count"],$wheres.$group);
            if(!empty($vinCount['data'])){
                $vinCount = array_column($vinCount['data'],'vin_count','tul_atime');
            }else{
                $vinCount = [];
            }
            $modelCount = $PjlBase->get($table,["FROM_UNIXTIME(tul_atime, '".$groupBy."') as tul_atime,count(DISTINCT tul_mod3_id) as mod_count"],$wheress.$group);
            if(!empty($modelCount['data'])){
                $modelCount = array_column($modelCount['data'],'mod_count','tul_atime');
            }else{
                $modelCount = [];
            }
            $where .= $group;
            $where .= sprintf(" limit %d,%d",($page-1)*$pageSize,$pageSize);
            $list = $PjlBase->get($table, $field, $where);

            foreach ($list['data'] as &$value){
                if(isset($vinCount[$value['tul_atime']])){
                    $value['vin_count'] = $vinCount[$value['tul_atime']];
                }else{
                    $value['vin_count'] = '';
                }
                if(isset($modelCount[$value['tul_atime']])){
                    $value['model_count'] = $modelCount[$value['tul_atime']];
                }else{
                    $value['model_count'] = '';
                }
                $value['tul_mon_id_count'] = $value['tul_mon_id_count'] ?: '';
            }
            LibTpl::Set('list',$list['data']);
        }

        LibTpl::Set('page',LibPage::Show($count['data']['count'],$pageSize));
        LibTpl::Set('title','推送统计');
        LibTpl::Set('param',$param);
        LibTpl::Put();
    }

    public function pushApplyRecord()
    {
        LibRule::Check('JS05');
        $param = mvc::$URL_PARAMS;
        $page = isset($param['page']) && $param['page'] > 0 ? (int) $param['page'] : 1;
        $pageSize = empty($_COOKIE['perPage'])? 20: (int) $_COOKIE['perPage'];
        $PjlBase = new PjlBase();
        $where = '';
        if(is_numeric($param['status'])){
            $where .= sprintf(" and tua_status='%s'",$param['status']);
        }
        if($param['betime']){
            $temp = explode('~',$param['betime']);
            foreach ($temp as &$date){
                $date = strtotime($date);
            }
            $where .= sprintf(" and tua_atime >= %d and tua_atime <= %d",$temp['0'],$temp['1']);
        }
        $count = $PjlBase->get('pl_tuisong_applay',['count(*) as count'],$where,true);
        $statusName = [
            '-1' => '<span class="gray">无效</span>',
            '0' => '<span class="orange">待处理</span>',
            '1' => '<span class="green">已处理</span>'
        ];
        LibTpl::Set('statusName',$statusName);
        if($count['data']['count'] > 0){
            $where .= sprintf(" order by tua_atime desc,field(tua_status,0,1,-1) limit %d,%d",($page-1)*$pageSize,$pageSize);
            $list = $PjlBase->get('pl_tuisong_applay left join pl_shop on tua_pu_id=shop_id',['pl_tuisong_applay.*','pl_shop.shop_name','shop_vip_etime svip_etime'],$where);
            $uId = array_column($list['data'],'tua_pu_id');
            $post = [
                'filed'=>['u_id','u_name','u_mobile'],
                'where'=>sprintf(" and u_id in (%s)", implode(',',$uId))
            ];
            $LibYpApi = new LibYpApi();
            $userInfo = $LibYpApi->get('user/getUser', [], $post);
            $userInfo = $userInfo['data'];
            $userInfo =  array_column($userInfo,null,'u_id');
            LibTpl::Set('userlist',$userInfo);
            LibTpl::Set('list',$list['data']);
        }

        LibTpl::Set('title','推送申请记录');
        LibTpl::Set('param',$param);
        LibTpl::Set('page',LibPage::Show($count['data']['count'], $pageSize));
        LibTpl::Put();
    }

    public function audit()
    {
        LibRule::Check('JS05');
        $_POST['tua_remark'] = trim($_POST['tua_remark']);
        if(!is_numeric($_POST['tua_status'])){
            LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        }
        $result = (new PjlBase())->set('pl_tuisong_applay',['tua_remark' => $_POST['tua_remark'],'tua_status' =>   $_POST['tua_status']],sprintf(" and tua_id=%d",$_POST['tua_id']));
        LibFc::ajaxJsonEncode($result);
    }
}
