<?php
/**
 * 报表实现类 成都 渠道每日客资数据统计
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wangyining 2020-06-03 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;

class Cd_channel_days_cus_data extends Report {

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

    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 00:00:00', 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'=>'请选择店面');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        // $where['customer_type'] = 1;
        $where['add_shop_code'] = $shop_code;

        $whereC['shop_code'] = $shop_code;

        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }

        // 地域id，拼接where条件
        if ($data['province']) {
            $where['province_id'] = (int)$data['province'];
            $whereC['province_id'] = (int)$data['province'];
        }

        if ($data['city']) {
            $where['city_id'] = (int)$data['city'];
            $whereC['city_id'] = (int)$data['city'];
        }

        // if ($data['customer_channel']) {
        //     $channelNames = explode(',',$data['customer_channel']);

        //     $channels = db('crm_s_channel')->where('channel_name', 'in' ,$channelNames)->select();
        // } else {
        //     // 来源渠道
        //     $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        // }
        // $channelIds = array_column($channels,'id');

        $info_group = 'channel_info_name';
        $group = 'channel_info_name';
        $key_channel = 'channel_info_name';
        
        if ($data['customer_channel']) {
           $channels = explode(',',$data['customer_channel']);
            $channel_data = db('crm_s_channel')->where("channel_name","in",$data['customer_channel'])->order("order_sort")->select();
            $channel_datas = array_column($channel_data, 'channel_info_name');
            // asort($channel_datas);
            $channelData = [];
            foreach($channel_datas as $key=>$value){
                $channelData[] = $channel_data[$key];
            }
            $info_group = 'customer_channel';
            $group = 'channel_name';
            $key_channel = 'channel_name';
            
        }elseif($data['erji_channel_id']){
            // 来源渠道
            $channels = explode(',',$data['erji_channel_id']);
            $channel_data = db('crm_s_channel')->where("channel_info_name","in",$data['erji_channel_id'])->order("order_sort")->select();
            $channel_datas = array_column($channel_data, 'channel_info_name');
            // asort($channel_datas);
            $channel_datas = array_unique($channel_datas);
            $channelData = [];
            foreach($channel_datas as $key=>$value){
                $channelData[] = $channel_data[$key];
            }
        }else{
            // 来源渠道
            $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            $channel_datas = array_column($channels, 'channel_info_name');
            // asort($channel_datas);
            $channel_datas = array_unique($channel_datas);
            $channelData = [];
            foreach($channel_datas as $key=>$value){
                $channelData[] = $channels[$key];
            }
            $channels = array_column($channels,'channel_info_name');
        }
        if($data['customer_channel']){
            if($data['data_type'] == 1){
                $where['customer_channel'] = ['in',$channels];
            }elseif($data['data_type'] == 2){
                $where['channel_name'] = ['in',$channels];
            }    
        }else{
            $where['channel_info_name'] = ['in',$channels];
        }
        
        $days = controller('Setting','lib')->prDates($start,$end);

        //客资
        if($data['data_type'] == 1){
           
            $all = db('crm_c_customerinfo')->alias('i')
                ->join('crm_s_channel s','i.customer_channel=s.channel_name','left')
                ->where($where)
                ->where('dj_day BETWEEN "'.$start.'" AND "'.$end.'"')
                ->field('DATE(dj_day)AS days,customer_channel_id as channel_id,customer_channel as channel_name,COUNT(1)AS num,channel_info_name')
                ->group('DATE(dj_day),'.$info_group)
                ->select();
                $return['infosql'] =  db()->getLastSql();
        }elseif($data['data_type'] == 2){
            //花费
            $all = db('crm_s_channel_cost')
                ->where($whereC)
                ->where('cost_date BETWEEN "'.$start.'" AND "'.$end.'"')
                ->field('DATE(cost_date)AS days,channel_id,channel_name,sum(cost)AS num,channel_info_name')
                ->group('DATE(cost_date),'.$group)
                ->select();
                $return['money'] = db()->getLastSql();
        }
    
        $list = [];
        foreach($all as $k => $v){
            // var_dump($v);
            $list[$v[$key_channel]]['channel_info_name'] = $v['channel_info_name'];
            if($data['customer_channel']){
                $list[$v[$key_channel]]['channel_name'] = $v['channel_name'];
            }
            //花费金额 保留两位小数
            $list[$v[$key_channel]][$v['days']] = $data['data_type'] == 1 ? $v['num'] : sprintf('%.2f', $v['num']);
            
            $arr['channel_info_name'] = '总计';
            $arr['channel_name'] = '';
            $arr[$v['days']] += $list[$v[$key_channel]][$v['days']];
        }
        //var_dump($list);die;
        $list[] = $arr;
        
        //给每个渠道没有数据的日期 展示0
        foreach($list as $k => $v){
            foreach($days as $dk => $dv){
                if($v[$dv] == 0){
                    $list[$k][$dv] = 0;
                }
            }
        }
        //把没数据的渠道 展示0
        foreach($channelData as $key => $val){
            if(count($list[$val[$key_channel]]) == 0){
                foreach($days as $k => $v){
                    $list[$val[$key_channel]]['channel_info_name'] = $val['channel_info_name'];
                    if($data['customer_channel']){
                        $list[$val[$key_channel]]['channel_name'] = $val['channel_name'];
                    }
                    $list[$val[$key_channel]][$v] = 0;
                }
            }
        }
        // var_dump($list);die;
        //求每个渠道合计
        foreach($list as $key => $val){
            $num = $val;
            unset($num[$key]);
            
            //花费金额 保留两位小数
            $list[$key]['sum'] = $data['data_type'] == 1 ? array_sum($num) : sprintf('%.2f', array_sum($num));
        }

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($list);
        $return['data'] = $list;

        return json($return);
    }

    public function show(){
        /*
        $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();
        $city = db('crm_s_shop_address')->where('shop_code',$info['shop_code'])->where('type',2)->select();

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

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

        //可操作店
        $mc = new \app\common\lib\mcInterface();
        $shopData = $mc->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
        $this->assign('shopData',$shopData);
        $this->assign("shop_code", $info['shop_code']?$info['shop_code']:session('shop_code'));

        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);

        //来源渠道
        //$channel = controller("Customer", "lib")->getChannel($info['shop_code']);
        //$this->assign("channel", $channel);
        $channel = getChannelJson($info['shop_code']);
        $this->assign("channel", json_encode($channel));


        $code = $this->getCode();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('crm_s_report_form')->where('code', $code)->value('report_name');
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }



}