<?php
/**
 * 报表实现类 西安绝对人气 定制 来源渠道 (二级渠道分类) 数据统计
 * *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wangzhenya 2018-08-20 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;
use app\common\lib\mcInterface;

class Cd_customer_access extends Report {

    private $level= 1;
    private $type = 1;
    private $code = 'code1592992364';

    public function getLevel(){
        return $this->level;
    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data(){
        set_time_limit(0);
        $data = input();

        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));

        $det = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id')->where('d.id',$data['did'])->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();

        //店
        if($data['shop_code']){
            $shop_code = $data['shop_code'];
        }elseif($det['shop_code']){
            $shop_code = $det['shop_code'];
        }else{
            $shop_code = session('shop_code');
        }

        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'请选择店面');
        }

        if($data['channel_id']){
            $channels = explode(',',$data['channel_id']);
            $allChannels = getChannels(array('shop_code'=>$shop_code));
            $channelInfos = [];
            foreach ($channels as $key => $value) {
                foreach ($allChannels as $k => $v) {
                    if ($v['channel_name'] == $value) {
                        $channelInfos[] = $v['channel_info_name'];
                        continue;
                    }
                }
            }
            $channelInfos = array_unique($channelInfos);
        }else{
            // 来源渠道
            $channel = controller('crm/Customer', 'lib')->getChannel($shop_code);
            $channels = array_column($channel,'channel_name');
            $channelInfos = array_column($channel,'channel_info_name');
            $channelInfos = array_unique($channelInfos);
        }
        
        if ($data['group_id']) {
            $where['dj_staff'] = ['in',$data['group_id']];
        } 

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        if((int)$data['consultation_type_id']){
            $where['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in (\'1\',\'5\')) as valid,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=2) as dd,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in (\'3\',\'4\')) as unValid,';
        $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in (\'2\',\'3\',\'5\')) as jd,';
        //$sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`,';
        $sql .= 'sum(add_friend_time is not null) as wxl';
        
        $info = db('crm_c_customerinfo')
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('access_model')
            ->column($sql,'access_model');
        $sql1 = db()->getLastSql();


        //成交量
        $orderNum = db('crm_c_customerinfo')->alias('c')
            ->join('crm_s_channel s', 's.id=c.customer_channel_id','left')
            ->join('c_customerorder erp_order', 'erp_order.crm_customer_id=c.id','left')
            // ->join('c_customerorder erp_order', 'erp_order.crm_customer_number=c.customer_number')
            ->where($where)
            ->where('erp_order.orderId is not null')
            ->where('erp_order.blankoutannal','<>',1)
            // ->where('erp_order.yixiaoshishou','>',0)
            ->where('erp_order.payment_money','>',0)
            ->where('erp_order.crm_order_type',1)
            // ->where('c.dj_day', 'between time', [$start, $end])
            ->where('erp_order.targetdate', 'between', [date('Ymd',strtotime($start)), date('Ymd',strtotime($end))])
            ->group('access_model')
            ->column('count(c.id) as cj_order','access_model');

        //营业额
        $moneyData = db('crm_c_customerinfo')->alias('c')
                    ->join('c_customerorder erp_order','erp_order.crm_customer_id=c.id','left')
                    ->where($where)
                    ->where('c.customer_channel','in',$channels)
                    // ->where('dj_day','between time',[$start,$end])
                    ->where('erp_order.orderId is not null')
                    ->where('erp_order.blankoutannal','<>',1)
                    // ->where('erp_order.yixiaoshishou','>',0)
                    ->where('erp_order.payment_money','>',0)
                    ->where('erp_order.crm_order_type',1)
                    ->where('erp_order.targetdate', 'between', [date('Ymd',strtotime($start)), date('Ymd',strtotime($end))])
                    ->group('c.access_model')
                    ->column('sum(erp_order.bargain_money) as  total_money','c.access_model');
        $sql2 = db()->getLastSql();

        $returnData = [];
        $arr = [];
        $k = 0;
        foreach($info as $key=>$v){
            if($v['access_model']){
                $returnData[$k]['access_model'] = $v['access_model'];
            }else{
                $returnData[$k]['access_model'] = '其他';
            }
            $returnData[$k]['mkz'] = $info[$v['access_model']]['mkz'];
            $returnData[$k]['valid'] = $info[$v['access_model']]['valid'];
            $returnData[$k]['unValid'] = $info[$v['access_model']]['unValid'];
            $returnData[$k]['dd'] = $info[$v['access_model']]['dd'];
            $returnData[$k]['yy'] = $info[$v['access_model']]['yy'];
            $returnData[$k]['jd'] = $info[$v['access_model']]['jd'];
            $returnData[$k]['order'] = $orderNum[$v['access_model']]['cj_order'];
            $returnData[$k]['validRate'] = $info[$v['access_model']]['valid'] ? sprintf('%.2f',$info[$v['access_model']]['valid']/$info[$v['access_model']]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddValidRate'] = $info[$v['access_model']]['dd'] ? sprintf('%.2f',$info[$v['access_model']]['dd']/$info[$v['access_model']]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValidRate'] = $info[$v['access_model']]['unValid'] ? sprintf('%.2f',$info[$v['access_model']]['unValid']/$info[$v['access_model']]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddRate'] = $info[$v['access_model']]['dd'] ? sprintf('%.2f',$info[$v['access_model']]['dd']/$info[$v['access_model']]['mkz']*100).'%' : '0%';
            $returnData[$k]['mkzJdRate'] = $info[$v['access_model']]['jd'] ? sprintf('%.2f',$info[$v['access_model']]['jd']/$info[$v['access_model']]['mkz']*100).'%' : '0%';
            $returnData[$k]['validJdRate'] = $info[$v['access_model']]['jd'] ? sprintf('%.2f',$info[$v['access_model']]['jd']/$info[$v['access_model']]['valid']*100).'%' : '0%';
            $returnData[$k]['jdOrderRate'] = $orderNum[$v['access_model']]['cj_order'] ? sprintf('%.2f',$orderNum[$v['access_model']]['cj_order']/$info[$v['access_model']]['jd']*100).'%' : '0%';
            $returnData[$k]['mkzOrderRate'] = $orderNum[$v['access_model']]['cj_order'] ? sprintf('%.2f',$orderNum[$v['access_model']]['cj_order']/$info[$v['access_model']]['mkz']*100).'%' : '0%';
            $returnData[$k]['validOrderRate'] = $inorderNumfo[$v['access_model']]['cj_order'] ? sprintf('%.2f',$orderNum[$v['access_model']]['cj_order']/$info[$v['access_model']]['valid']*100).'%' : '0%';
            $returnData[$k]['totalMoney'] =  floatval($moneyData[$v['access_model']]);
            $returnData[$k]['yjwechat'] = $info[$v['access_model']]['yjwechat']?$info[$v['access_model']]['yjwechat']:0;
            
            //总计
            $arr['access_model'] = '合计';
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['valid'] += $returnData[$k]['valid'];
            $arr['unValid'] += $returnData[$k]['unValid'];
            $arr['dd'] += $returnData[$k]['dd'];
            $arr['yy'] += $returnData[$k]['yy'];
            $arr['jd'] += $returnData[$k]['jd'];
            $arr['order'] += $returnData[$k]['order'];
            $arr['yjwechat'] += $returnData[$k]['yjwechat'];
            $arr['validRate'] = '';
            $arr['unValidRate'] = '';
            $arr['ddValidRate'] = '';
            $arr['ddRate'] = '';
            $arr['mkzJdRate'] = '';
            $arr['validJdRate'] = '';
            $arr['jdOrderRate'] = '';
            $arr['mkzOrderRate'] = '';
            $arr['validOrderRate'] = '';
            $arr['totalMoney'] += floatval($returnData[$k]['totalMoney']);
            $k++;
        }
        if(!empty($arr)){
            $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
            $arr['unValidRate'] = $arr['valid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
            $arr['ddRate'] = $arr['valid'] ? sprintf('%.2f',$arr['dd']/$arr['mkz']*100).'%' : '0%';
            $arr['mkzJdRate'] = $arr['valid'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0%';
            $arr['validJdRate'] = $arr['valid'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '0%';
            $arr['jdOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['jd']*100).'%' : '0%';
            $arr['mkzOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '0%';
            $arr['validOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '0%';
            $arr['ddValidRate'] = $arr['dd'] ? sprintf('%.2f',$arr['dd']/$arr['mkz']*100).'%' : '0%';
            array_unshift($returnData,$arr);
        }
        
        $return['customerinfo'] = $sql1;
        $return['moneyData'] = $sql2;

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channels);
        $return['data'] = $returnData;
       
        return json($return);
    }
    public function show(){
        $code = $this->getCode();
        /*
        $did = strtolower(input('param.did'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id')->where('d.id',$did)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();*/
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id','left')->where('f.code',$menu_code)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();

        //来源渠道
        $channel = getChannelJson(session('shop_code'));
        $this->assign("channel", json_encode($channel));

        //渠道一二级
        $channel2 = getChannelJson12($shop_code);
        $this->assign("channel2",json_encode($channel2));

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>session('brandclass_id')]);
        $this->assign("consumptionType", $consumptionType);

        //事业部下店面
        $mc = new \app\common\lib\mcInterface;
        $shopList = $mc->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
        $this->assign('shopList',$shopList);
        $this->assign("shop_code", $info['shop_code']?$info['shop_code']:session('shop_code'));

        //小组
        $groupStaff = getGroupStaff(['shop_code'=>$info['shop_code']]);
        $this->assign('groupstaff',json_encode($groupStaff));

        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';

        //表格隐藏列
        $this->assign('hiddenColumns',explode('|',cookie('report_cd_customer_access_hidden')));

        $this->assign('title', session('shop_name').'-'.$info['report_name']);
        $this->assign('did', $info['id']);
        $this->assign('today',date('Y-m-d'));
        $this->assign('yestoday',date('Y-m-d',time()));

        return $this->fetch($display);
    }

}