<?php
/**
 *  城市花园 大屏控制器
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong<lilong@suxuantech.cn> $
 */
namespace app\crm\controller;
use think\Controller;
// use app\index\controller\Base;
use think\Queue;
use think\Request;

class Citygarden extends Controller{
    
    protected $ds_shop_code = 'XBB079';
    protected $wx_shop_code = 'XBB079';

    // 所有电商shop_code
    protected $ds_shop_codes = [
        '0' => [
            'shop_code' => 'XBB079',
            'shop_name' => '北京城市花园婚纱摄影',
            'base_name' => '北京城市花园婚纱摄影',
        ],
    ];

    // 所有网销shop_code
    protected $wx_shop_codes = [
        '0' => [
            'shop_code' => 'XBB079',
            'shop_name' => '北京城市花园婚纱摄影',
            'base_name' => '北京城市花园婚纱摄影',
        ],
    ];
    protected $noinConsultation = ['礼服租售','产品加做','业务单','美容跟妆','网打预付'];
    // 大屏页面  2018-07-26
    public function index(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        
        $this->assign('title','城市花园 【电商战报大屏】');
        return $this->fetch();
    }

    // 移动端大屏
    public function mobile(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        $this->assign('title','城市花园 【电商战报大屏】');
        return $this->fetch();
    }
    /*----------------------------------------------------------  ----------------------------------------------------------*/
    // 页面实时数据
    public function baseData(){
        // echo 'START==>'.microtime(true).'<br />';
        // 权限
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        //今天
        $tData['start']     = date('Y-m-d 00:00:00');
        $tData['end']       = date('Y-m-d 23:59:59');
        //本月
        $mdate = getdateArea('this_month');
        $mData['start']     = date('Y-m-d 00:00:00',strtotime($mdate[0]));
        $mData['end']       = date('Y-m-d 23:59:59');

        /* -------- 电商相关 -------- */
        $tData['shop_code'] = $this->ds_shop_code;
        $mData['shop_code'] = $this->ds_shop_code;

        // 转化漏斗下方的率, 客户来源（customer_cource）是电商的有效客资，按登记时间统计 / 客户来源（customer_cource）是电商的毛客资客资
        $tData['customer_cource'] = '电商';
        $mData['customer_cource'] = '电商';
        $allCusT = controller('crm/Citygarden', 'lib')->getCustomerNum($tData);
        $allCusM = controller('crm/Citygarden', 'lib')->getCustomerNum($mData);
        $validCusT = controller('crm/Citygarden', 'lib')->getInvCustomerNum($tData);
        $validCusM = controller('crm/Citygarden', 'lib')->getInvCustomerNum($mData);
        $returnData['dayChangeRate']  = number_format( ($validCusT / $allCusT)*100, 0).'%';
        $returnData['monthChangeRate']= number_format( ($validCusM / $allCusM)*100, 0).'%';
        unset($tData['customer_cource'], $mData['customer_cource']);
        // 有效客资 按的登记时间统计有效客资
        $validCustomerT = controller('crm/Citygarden', 'lib')->getInvCustomerNum($tData);
        $validCustomerM = controller('crm/Citygarden', 'lib')->getInvCustomerNum($mData);
        $returnData['validCustomer'] = $validCustomerT.' / '.$validCustomerM;

        /* -------- 网销相关 -------- */
        $tData['shop_code'] = $this->wx_shop_code;
        $mData['shop_code'] = $this->wx_shop_code;

        // 预计进店
        $readyIntoT = controller('crm/Citygarden', 'lib')->readyIntoNum($tData);
        $readyIntoM = controller('crm/Citygarden', 'lib')->readyIntoNum($mData);
        $returnData['readyInto'] = $readyIntoT.' / '.$readyIntoM;
        // 未进店客
        $notIntoT = controller('crm/Citygarden', 'lib')->notIntoNum($tData);
        $notIntoM = controller('crm/Citygarden', 'lib')->notIntoNum($mData);
        $returnData['notInto'] = $notIntoT.' / '.$notIntoM;
        // 进店成交
        $intoOrderT = controller('crm/Citygarden', 'lib')->intoOrderNum($tData);
        $intoOrderM = controller('crm/Citygarden', 'lib')->intoOrderNum($mData);
        $returnData['intoOrder'] = $intoOrderT.' / '.$intoOrderM;
        // 网付订单
        $onlineOrderT = controller('crm/Citygarden', 'lib')->onlineOrderNum($tData);
        $onlineOrderM = controller('crm/Citygarden', 'lib')->onlineOrderNum($mData);
        $returnData['onlineOrder'] = $onlineOrderT.' / '.$onlineOrderM;
        // exit;
        // 进店流失
        $intoLossT = controller('crm/Citygarden', 'lib')->intoLossNum($tData);
        $intoLossM = controller('crm/Citygarden', 'lib')->intoLossNum($mData);
        $returnData['intoLoss'] = $intoLossT.' / '.$intoLossM;
        // 成交率 新单（targettime） / （预计进店 - 未进店客）
        $orderRateT = number_format( ($intoOrderT / ($readyIntoT-$notIntoT) )*100, 0).'%';
        $orderRateM = number_format( ($intoOrderM / ($readyIntoM-$notIntoM) )*100, 0).'%';
        $returnData['orderRate'] = $orderRateT.' / '.$orderRateM;

        unset($tData,$mData,$mdate, $allCusT,$allCusM, $validCusT,$validCusM, $validCustomerT,$validCustomerM, $readyIntoT,$readyIntoM, $notIntoT,$notIntoM, $intoOrderT,$intoOrderM, $intoLossT,$intoLossM, $orderRateT,$orderRateM);
        return json($returnData);
    }
    // 转化漏斗 （日） 图
    public function dayChangeRate(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        $post = input('post.');

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

        $returnData = $this->getChangeLdData($data);

        return json($returnData);
    }
    // 转化漏斗 （月） 图
    public function monthChangeRate(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        $post = input('post.');

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

        $returnData = $this->getChangeLdData($data);

        return json($returnData);
    }
    // 转化漏斗数据 
    public function getChangeLdData($data){
        $data['shop_code'] = $this->ds_shop_code;
        $data['customer_cource'] = '电商';
        // 毛客资
        $customerNum = controller('crm/Citygarden', 'lib')->getCustomerNum($data);
        $returnData[0]['name'] = '毛客资量';
        $returnData[0]['data'] = $customerNum;
        // 有效客资
        $invCustomer = controller('crm/Citygarden', 'lib')->getInvCustomerNum($data);

        $returnData[1]['name'] = '有效客资';
        $returnData[1]['data'] = $invCustomer;

        $data['shop_code'] = $this->wx_shop_code;
        // 进店/邀约 量
        $intoCustomer= controller('crm/Citygarden', 'lib')->getIntoCustomerNum($data);
        $returnData[2]['name'] = '进店';
        $returnData[2]['data'] = $intoCustomer;
        // 新单 量
        $orderNumber = controller('crm/Citygarden', 'lib')->getOrderNumberNum($data);
        $returnData[3]['name'] = '订单';
        $returnData[3]['data'] = $orderNumber;
        return $returnData;
    }
    // 订单来源排名  (图)
    public function orderCource(){
        //本月
        $mdate = getdateArea('this_month');
        $params['start']     = date('Y-m-d 00:00:00',strtotime($mdate[0]));
        $params['end']       = date('Y-m-d 23:59:59');

        $params['shop_code'] = $this->wx_shop_code;
        $num = controller('crm/Citygarden', 'lib')->getOrderNumCource($params);
        // echo db()->getLastSql();
        // var_dump($num);
        // exit;
        // 调mc获取所有客户来源
        $courceList = controller('crm/Citygarden', 'lib')->getCource();
        // var_dump($courceList);
        // exit;
        $temp = [];
        foreach ($courceList as $key => $value) {
            $temp[$key]['name']= $value['cus_name'];
            $temp[$key]['num'] = $num[$value['cus_name']] ? $num[$value['cus_name']] : 0;
        }
        $sort_order = 'SORT_DESC';
        $arr = my_sort($temp, 'num', $sort_order);
        $cList = [];
        foreach ($arr as $key => $value) {
            $cList[$key] = $value['name'];
        }
        $returnData['data']  = $arr;
        $returnData['cource']= $cList;
        unset($params,$num,$courceList,$temp,$arr,$cList);
        return json($returnData);
    }
    /*----------------------------------------------------------  ----------------------------------------------------------*/
    // 本月有效客资量走势 图  按照登记时间取有效客资
    public function monthCustomerNumber(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where['is_status']    = 1;
        $where['c_from']       = 1;
        $where['customer_type']= 1;
        $where['is_valid']     = 1;

        // echo microtime(true).'<br />';
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);
        // 查一下缓存
        $day = date('Ymd');
        $monthCustomerNumber = cache('monthCustomerNumber_'.$day);
        if (!$monthCustomerNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    $monthCustomerNumber =[];
                    break;
                }
                $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $data['end']   = date('Y-m-d 23:59:59', strtotime($value));
                $customerNum = db('c_customerinfo')
                    ->where($where)
                    ->where('add_shop_code', 'in', $this->ds_shop_code)
                    ->where('dj_day', 'between time', [$data['start'], $data['end']])
                    ->count();
                $monthCustomerNumber[$key] = $customerNum;
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthCustomerNumber_'.$day, json_encode($monthCustomerNumber));
        }
        // echo microtime(true).'<br />';
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // 今天的数量
        $customerNum = db('c_customerinfo')
            ->where($where)
            ->where('add_shop_code', 'in', $this->ds_shop_code)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->count();

        array_push($monthCustomerNumber, $customerNum);
        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'有效客资量',
                'data' =>$monthCustomerNumber,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('有效客资量');
        $returnData['data'] = $arr;
        unset($where,$date,$timezone,$monthCustomerNumber,$customerNum,$zone,$arr);
        return json($returnData);
    }
    // 本月网络新单量走势 图
    public function monthNewOrderNumber(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;

        set_time_limit(0);
        // 起始时间
        // echo microtime(true).'<br />';
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);
        // 查缓存
        $day = date('Ymd');
        $monthNewOrderNumber = cache('monthNewOrderNumber_'.$day);
        // var_dump($monthNewOrderNumber);exit;
        if (!$monthNewOrderNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    $monthNewOrderNumber =[];
                    break;
                }
                $param['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $param['end']   = date('Y-m-d 23:59:59', strtotime($value));
                $param['shop_code'] = $this->wx_shop_code;
                $orderNum = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 'in',[1,3])
                    ->where('shop_code', 'in', $this->wx_shop_code)
                    ->where('order_start_time', 'between time', [$param['start'], $param['end']])
                    ->count();
                // $orderNum = controller('crm/Citygarden', 'lib')->getOrderNumberNum($param);
                $monthNewOrderNumber[$key] = $orderNum;
                unset($param,$orderNum);
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthNewOrderNumber_'.$day, json_encode($monthNewOrderNumber));
        }
        // echo microtime(true).'<br />';
        // 日 开始结束时间
        $paramT['start'] = date('Y-m-d 00:00:00', time());
        $paramT['end'] = date('Y-m-d 23:59:59', time());
        $paramT['shop_code'] = $this->wx_shop_code;
        // 今天的数量
        $orderNum = db('c_customerinfo')
            ->where($where)
            ->where('is_success', 'in',[1,3])
            ->where('shop_code', 'in', $this->wx_shop_code)
            ->where('order_start_time', 'between time', [$paramT['start'], $paramT['end']])
            ->count();
        // $orderNum = controller('crm/Citygarden', 'lib')->getOrderNumberNum($paramT);
        array_push($monthNewOrderNumber, $orderNum);

        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'新单量',
                'data' =>$monthNewOrderNumber,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('新单量');
        $returnData['data'] = $arr;
        unset($where,$date,$timezone,$monthNewOrderNumber,$paramT,$orderNum,$zone,$arr);
        return json($returnData);
    }
    // 有效客资目标及进度
    public function getTargetValid(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $wx = '';
        foreach ($this->wx_shop_codes as $key => $value) {
            $wx .= $value['shop_code'].',';
        }
        $wx = trim($wx, ',');

        $this_month = date('Y-m');
        // 获取网销店下所有的部门目标设定
        $target = db('s_kpi_staffgoal')
            ->where('kpi_id', 'validCustomerNumber')
            ->where('shop_code', 'in',$wx)
            ->where('flag', 'shop')
            ->where('month', $this_month)
            ->group('shop_code')
            ->column('sum(kpi_value) as count, sum(avg_value) as avg, shop_name, shop_code','shop_code');

        $date = getdateArea('this_month');
        $month_start= date('Y-m-d 00:00:00',strtotime($date[0]));
        $month_end  = date('Y-m-d 23:59:59',strtotime($date[1]));
        
        $alread = db('c_customerinfo')
            ->where('is_status', 1)
            ->where('c_from', 1)
            ->where('shop_code', 'in',$wx)
            ->where('is_valid', 1)
            ->where('dj_day', 'between time', [$month_start, $month_end])
            ->group('shop_code')
            ->column('count(*) as num','shop_code');
        // echo db()->getLastSql();
        // var_dump($alread);exit;

        $result = [];
        if (!$target) {
            $result['valid_target'] = 0;
            $result['valid_alread'] = 0;
        }else{
            $result['valid_target'] = 0;
            $result['valid_alread'] = 0;
            foreach ($target as $key => $value) {
                $shop_code = $value['shop_code'];
                $result['valid_target'] += $value['count'];
                $result['valid_alread'] += $alread[$shop_code];
            }
        }
        unset($target,$alread);
        return json($result);
    }
    // 订单目标及进度
    public function getTargetOrder(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $wx = '';
        foreach ($this->wx_shop_codes as $key => $value) {
            $wx .= $value['shop_code'].',';
        }
        $wx = trim($wx, ',');

        $this_month = date('Y-m');
        // 获取网销店下所有的部门目标设定
        $target = db('s_kpi_staffgoal')
            ->where('kpi_id', 'orderNumber')
            ->where('shop_code', 'in',$wx)
            ->where('flag', 'shop')
            ->where('month', $this_month)
            ->group('shop_code')
            ->column('sum(kpi_value) as count, sum(avg_value) as avg, shop_name, shop_code','shop_code');

        $date = getdateArea('this_month');
        $param['start']= date('Y-m-d 00:00:00',strtotime($date[0]));
        $param['end']  = date('Y-m-d 23:59:59',strtotime($date[1]));
        $param['shop_code'] = $wx;
        $alread = controller('crm/Citygarden', 'lib')->getOrderNumberNum($param);
        // echo db()->getLastSql();
        // var_dump($alread);exit;
        $result = [];
        if (!$target) {
            $result['order_target'] = 0;
            $result['order_alread'] = 0;
        }else{
            $result['order_target'] = 0;
            $result['order_alread'] = 0;
            foreach ($target as $key => $value) {
                $shop_code = $value['shop_code'];
                $result['order_target'] += $value['count'];
                $result['order_alread'] += $alread;
            }
        }
        unset($target,$alread);
        return json($result);
    }
    /*----------------------------------------------------------  ----------------------------------------------------------*/
    // 两个排行  网销订单率月排名
    public function rankData(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');

        $date = getdateArea('this_month');
        $start= date('Y-m-d 00:00:00',strtotime($date[0]));
        $end  = date('Y-m-d 23:59:59',strtotime($date[1]));

        // 统计网销的有效客资数
        $where['c_from']        = 1;
        $where['is_valid']      = 1;
        $where['is_status']     = 1;
        $where['customer_type'] = 1;

        $sql .= "sum(is_valid=1 and dj_day between '".$start."' and '".$end."') as valiNum,";//qq
        $sql .= "sum(is_success in (1,3) and order_start_time between '".$start."' and '".$end."') as orderNum,";//微信
        $allNum = db('c_customerinfo')
            ->where($where)
            ->where('shop_code', 'in', $this->wx_shop_code)
            ->where('sales_staff_id', '>', 0)
            ->group('sales_staff_id')
            ->column($sql.'sales_staff','sales_staff_id');

        $temp = [];
        foreach ($allNum as $key => $value) {
            if ($value['valiNum']==0 || $value['orderNum']==0) {
                continue;
            }else{
                $temp[$key]['sales_staff'] = $value['sales_staff'];
                $temp[$key]['valiNum']  = $value['valiNum'];
                $temp[$key]['orderNum'] = $value['orderNum'];
                $temp[$key]['oRate']    = $value['orderNum'] / $value['valiNum'];
                $temp[$key]['orderRate']= number_format( ($value['orderNum'] / $value['valiNum'])*100, 0).'%';
            }
        }
        // 排名，从高到低
        $sort_order = 'SORT_DESC';
        $returnData['wxRankTop'] = array_slice(my_sort($temp, 'oRate', $sort_order), 0, 10);
        // 排名，从低到高
        $sort_order = 'SORT_ASC';
        $returnData['wxRankDown'] = array_slice(my_sort($temp, 'oRate', $sort_order), 0,10);
        return json($returnData);
    }
    // 渠道（二级渠道）分布柱状图 
    public function channelCustomer(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        // 日 开始结束时间
        // $start = date('Y-m-d 00:00:00', time());
        // $end   = date('Y-m-d 23:59:59', time());
        $date = getdateArea('this_month');
        $start= date('Y-m-d 00:00:00',strtotime($date[0]));
        $end  = date('Y-m-d 23:59:59',strtotime($date[1]));

        $where = [
            'c.is_status'=> 1,
            'c.c_from'   => 1,
            'c.customer_type'=>1,
        ];
        // 毛客资
        $cusNum = db('c_customerinfo')->alias('c')
            ->join('s_channel s', 'c.customer_channel_id=s.id', 'left')
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->where('c.add_shop_code', 'in', $this->ds_shop_code)
            ->group('s.channel_info_name')
            ->column('count(c.id) as num ,s.channel_info_name', 's.channel_info_id');
        // 有效客资
        $valNum = db('c_customerinfo')->alias('c')
            ->join('s_channel s', 'c.customer_channel_id=s.id', 'left')
            ->where($where)
            ->where('c.is_valid', 1)
            ->where('dj_day', 'between time', [$start, $end])
            ->where('c.add_shop_code', 'in', $this->ds_shop_code)
            ->group('s.channel_info_name')
            ->column('count(c.id) as num ,s.channel_info_name', 's.channel_info_id');

        // 获取所有电商渠道
        $channels = controller('crm/Citygarden', 'lib')->getChannel();
        $temp = [];
        foreach ($channels as $key => $value) {
            $temp[$key]['name']  = $value['channel_name'];
            $temp[$key]['cusNum']= $cusNum[$value['id']]['num'] ? (int)$cusNum[$value['id']]['num'] : 0;
            $temp[$key]['valNum']= $valNum[$value['id']]['num'] ? (int)$valNum[$value['id']]['num'] : 0;
        }
        $sort_order = 'SORT_DESC';
        $temp = my_sort($temp, 'cusNum', $sort_order);
        
        foreach ($temp as $key => $value) {
            $returnData['name'][] = $value['name'];
            // 毛客资
            $returnData['data']['0']['name'] = '毛客资';
            $returnData['data']['0']['num'][]= $value['cusNum'];
            
            // 有效客资
            $returnData['data']['1']['name'] = '有效客资';
            $returnData['data']['1']['num'][]= $value['valNum'];
            
        }
        unset($cusNum,$valNum,$channels,$temp);

        return json($returnData);
    }
}