<?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;

class Cd_customer_advertising extends Report {

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

    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);
        }

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        // $whereCost['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(dj_day between "'.$start.'" and "'.$end.'" and is_valid in (\'1\',\'5\',\'4\',\'2\')) as valid,';
        // $sql .= 'sum(c.yjd_action_day between "'.$start.'" and "'.$end.'") as yy,';
        $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('channel_plan_number')
            ->column($sql,'channel_plan_number');
        $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('channel_plan_number')
            ->column('count(c.id) as cj_order','channel_plan_number');

        //营业额
        $moneyData = db('crm_c_customerinfo')->alias('c')
                    ->join('c_customerorder erp_order','c.customer_number=erp_order.crm_customer_number','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.channel_plan_number')
                    ->column('sum(erp_order.bargain_money) as  total_money','c.channel_plan_number');

        $sql2 = db()->getLastSql();

        $returnData = [];
        $arr = [];
        foreach($info as $k=>$v){
            if($v['channel_plan_number']){
                $returnData[$k]['channel_plan_number'] = $v['channel_plan_number'];
            }else{
                $returnData[$k]['channel_plan_number'] = '其他';
            }
            $returnData[$k]['mkz'] = $info[$v['channel_plan_number']]['mkz'];
            $returnData[$k]['valid'] = $info[$v['channel_plan_number']]['valid'];
            $returnData[$k]['unValid'] = $info[$v['channel_plan_number']]['unValid'];
            $returnData[$k]['dd'] = $info[$v['channel_plan_number']]['dd'];
            $returnData[$k]['yy'] = $info[$v['channel_plan_number']]['yy'];
            $returnData[$k]['jd'] = $info[$v['channel_plan_number']]['jd'];
            $returnData[$k]['order'] = $orderNum[$v['channel_plan_number']]['cj_order']?$orderNum[$v['channel_plan_number']]['cj_order']:'0';
            $returnData[$k]['validRate'] = $info[$v['channel_plan_number']]['valid'] ? sprintf('%.2f',$info[$v['channel_plan_number']]['valid']/$info[$v['channel_plan_number']]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddValidRate'] = $info[$v['channel_plan_number']]['dd'] ? sprintf('%.2f',$info[$v['channel_plan_number']]['dd']/$info[$v['channel_plan_number']]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValidRate'] = $info[$v['channel_plan_number']]['unValid'] ? sprintf('%.2f',$info[$v['channel_plan_number']]['unValid']/$info[$v['channel_plan_number']]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddRate'] = $info[$v['channel_plan_number']]['dd'] ? sprintf('%.2f',$info[$v['channel_plan_number']]['dd']/$info[$v['channel_plan_number']]['mkz']*100).'%' : '0%';
            $returnData[$k]['mkzJdRate'] = $info[$v['channel_plan_number']]['jd'] ? sprintf('%.2f',$info[$v['channel_plan_number']]['jd']/$info[$v['channel_plan_number']]['mkz']*100).'%' : '0%';
            $returnData[$k]['validJdRate'] = $info[$v['channel_plan_number']]['jd'] ? sprintf('%.2f',$info[$v['channel_plan_number']]['jd']/$info[$v['channel_plan_number']]['valid']*100).'%' : '0%';
            $returnData[$k]['jdOrderRate'] = $orderNum[$v['channel_plan_number']]['cj_order'] ? sprintf('%.2f',$orderNum[$v['channel_plan_number']]['cj_order']/$info[$v['channel_plan_number']]['jd']*100).'%' : '0%';
            $returnData[$k]['mkzOrderRate'] = $orderNum[$v['channel_plan_number']]['cj_order'] ? sprintf('%.2f',$orderNum[$v['channel_plan_number']]['cj_order']/$info[$v['channel_plan_number']]['mkz']*100).'%' : '0%';
            $returnData[$k]['validOrderRate'] = $orderNum[$v['channel_plan_number']]['cj_order'] ? sprintf('%.2f',$orderNum[$v['channel_plan_number']]['cj_order']/$info[$v['channel_plan_number']]['valid']*100).'%' : '0%';
            $returnData[$k]['totalMoney'] =  round($moneyData[$v['channel_plan_number']]);
            $returnData[$k]['yjwechat'] = $info[$v['channel_plan_number']]['yjwechat']?$info[$v['channel_plan_number']]['yjwechat']:0;
            
            //总计
            $arr['channel_plan_number'] = '合计';
            $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[$k]['ddValidRate'] = '';
            $arr['ddRate'] = '';
            $arr['mkzJdRate'] = '';
            $arr['validJdRate'] = '';
            $arr['jdOrderRate'] = '';
            $arr['mkzOrderRate'] = '';
            $arr['validOrderRate'] = '';
            $arr['totalMoney'] += floatval($returnData[$k]['totalMoney']);
        }
        
        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%';
            
            $arr['totalMoney'] = sprintf('%.2f',$arr['totalMoney']);
            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();

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

        //来源渠道
        $channel = getChannelJson(session('shop_code'));
        $this->assign("channel", json_encode($channel));
        //消费类型
        $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'));

        //表格隐藏列
        $this->assign('hiddenColumns',explode('|',cookie('report_cd_customer_advertising_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);
    }
}