<?php
/**
 * 报表详情 基本模块
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wangzhenya<wangzhenya@suxuantech.cn> 2019-07-25 $
 */
namespace app\crm\controller;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\Log;
use think\Request;
use think\Session;
use PHPExcel_IOFactory;
use PHPExcel;
use Excel5;
use think\Controller;
use app\common\lib\redisQueue;
use app\common\lib\erpInterface;
use app\common\lib\mcInterface;
class Detail extends Base{

    //客服明细
    public function xa_wxGroupDataKfDetail(){
        $input = input("");
   
        $this->assign('data',json_encode($input));
        return $this->fetch();
    }
    //渠道明细
    public function xa_wxGroupDataQdDetail(){
        $input = input("");
   
        $this->assign('data',json_encode($input));
        return $this->fetch();
    }
    //客服明细数据
    public function xaWxGroupDataKfDetailData(){
    	$data = input();
        $sales_group_name = $data['sales_group_name'];
        if(empty($sales_group_name)){
        	return array('code' => 100,'msg'=>'未获取到组名');
        }
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $shop_code = session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        // 基础条件
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.shop_code'] = $shop_code;
        // 消费类型
        if((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }
        // 渠道
        // if($data['channel_id']){
        //     $channels = explode(',',$data['channel_id']);
        // }else{
        //     // 来源渠道
        //     $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        //     $channels = array_column($channels,'channel_name');
        // }
        
        // 所有的组
        if($sales_group_name != '总计'){
        	$groupwhere['group_name'] = $sales_group_name;
        }

        $allGroups = db('c_staff_group')->where('shop_code',$shop_code)->where($groupwhere)->select();
        $allGroupsId = array_column($allGroups, 'id');

        $groupsStaff = db('c_staff_group_relation')->where('group_id','in',$allGroupsId)->select();
        foreach ($groupsStaff as $key => $value) {
        	$groupsStaffName[$value['staff_id']] = $groupsStaff[$key];
        }
        $staff_id = array_column($groupsStaff,'staff_id');

        $sql = '';
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'") as mkz,';//毛客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in (1)) as valid,';//有效客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid=3) as unValid,';//无效客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid=2) as dd,';//待定客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.wechat_status=2) as jiaWx,';//已加微信
        // $sql .= 'sum(yjd_day between "'.$start.'" and "'.$end.'") as yy,';
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in (\'2\',\'3\',\'5\')) as jd,';//实际进店
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in ("2","3","5") and DATE_FORMAT(c.syjd_day,"%w") IN (0,6) ) as wendjd,';//周末进店量
        $sql .= 'sum(c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1) as `order`, ';//成交量
        $sql .= 'sum(c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1 and c.order_type=1) as `onlineorder`, ';// 线上成交量
        // 当日订单量
        $sql .= 'sum(DATE_FORMAT(c.dj_day, "%Y%m%d")=DATE_FORMAT(c.order_day,"%Y%m%d") and c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1 ) as todayOrder, ';
        // 当日全款量
        $sql .= 'sum(DATE_FORMAT(o.bargainoverdate, "%Y%m%d")=DATE_FORMAT(c.order_start_time,"%Y%m%d") and c.order_start_time between "'.$start.'" and "'.$end.'" and c.is_success=1 ) as oneTimeMoneyOrder';
        $info = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->join('c_customer_order o','c.order_number=o.order_sn','left')
            ->where($where)->where($whereT)
            ->where('c.sales_staff_id','in',$staff_id)
            ->group('c.sales_staff_id')
            ->column($sql.',sales_staff', 'c.sales_staff_id');

        // echo db()->getLastSql();
        // die;
        // 组实收
        $factMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where($whereT)
            ->where('c.sales_staff_id','in',$staff_id)
            ->where('order_day', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(c.fact_money) as fact,c.sales_staff_id,c.sales_staff', 'c.sales_staff_id');
        // 组营收
        $totalMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where($whereT)
            ->where('c.sales_staff_id','in',$staff_id)
            ->where('order_day', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(c.totalpay_money) as total,c.sales_staff_id,c.sales_staff', 'c.sales_staff_id');
        // 计算组客资花费
        
        $method = db_config('cost_method_'.session('shop_code'));
        if ($method == 'belong') {
            $whereCost['belong_shop_code'] = $shop_code;
        }
        // $whereCost['belong_shop_code'] = $shop_code;
        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        $channels = array_column($channels,'channel_name');
        // 渠道花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where($whereCost)
            ->where('channel_name','in',$channels)
            ->group('channel_name')
            ->column('sum(cost) as cost','channel_name');
        // 渠道客资
        $cusNum = db('c_customerinfo')->alias('c')
            ->where('c.dj_day', 'between time', [$start, $end])
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->group('c.customer_channel')
            ->column('count(c.id) as num','c.customer_channel');
        $allChannelInfo = [];
        foreach ($cost as $key => $value) {
            $allChannelInfo[$key]['channel_name'] = $key;
            $allChannelInfo[$key]['cost'] = $value;
            $allChannelInfo[$key]['num'] = $cusNum[$key];
            $allChannelInfo[$key]['cb']  = $value / $cusNum[$key];
        }
        // 组渠道客资量
        $groupCusNum = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where('c.sales_staff_id','not null')
            ->where('dj_day', 'between time', [$start, $end])
            ->where('customer_channel','in',$channels)
            ->group('c.sales_staff_id,customer_channel')
            ->field('c.sales_staff_id,c.sales_staff,customer_channel,count(c.id) as num')
            ->select();
        // 组客资花费
        $groupCost = [];
        foreach ($groupCusNum as $key => $value) {
            $groupCost[$value['sales_staff_id']] += $allChannelInfo[$value['customer_channel']]['cb']*$value['num'];
        }

        $returnData = [];
        $arr = [];
        foreach($staff_id as $k=>$v){
            $returnData[$k]['sales_group_name'] = $sales_group_name;
            $returnData[$k]['sales_staff_name'] = $groupsStaffName[$v]['staff_name'];
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            $returnData[$k]['valid'] = $info[$v]['valid'];
            $returnData[$k]['unValid'] = $info[$v]['unValid'];
            $returnData[$k]['yjwechat'] = $info[$v]['jiaWx'];
            $returnData[$k]['wechatRate']= $info[$v]['jiaWx'] ? sprintf('%.2f',$info[$v]['jiaWx']/$info[$v]['mkz']*100).'%' : '0%';
            // $returnData[$k]['dd'] = $info[$v]['dd'];
            // $returnData[$k]['yy'] = $info[$v]['yy'];
            $returnData[$k]['jd'] = $info[$v]['jd'];
            $returnData[$k]['wendjd'] = $info[$v]['wendjd'];
            $returnData[$k]['nwendjd'] = $info[$v]['jd'] - $info[$v]['wendjd'];
            $returnData[$k]['order'] = $info[$v]['order'];
            $returnData[$k]['todayOrder'] = $info[$v]['todayOrder'];
            $returnData[$k]['dayOrderRate'] = $info[$v]['todayOrder'] ? sprintf('%.2f',$info[$v]['todayOrder']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['onlineorder'] = $info[$v]['onlineorder'];
            $returnData[$k]['intoorder'] = $returnData[$k]['order'] - $returnData[$k]['onlineorder'];
            $returnData[$k]['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValidRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddRate'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['mkzJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['jdOrderRate'] = $returnData[$k]['intoorder'] ? sprintf('%.2f',$returnData[$k]['intoorder']/$info[$v]['jd']*100).'%' : '0%';
            $returnData[$k]['mkzOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['cost'] = sprintf('%.2f',$groupCost[$v]);
            $returnData[$k]['mkzCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['mkz']) : '';
            $returnData[$k]['validCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['valid']) : '';
            $returnData[$k]['jdCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['jd']) : '';
            $returnData[$k]['orderCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['order']) : '';
            $returnData[$k]['orderAVG'] =  $info[$v]['order'] ? sprintf('%.2f',$totalMoney[$v]['total']/$info[$v]['order']) : '';
            $returnData[$k]['totalMoney'] =  sprintf('%.2f',$totalMoney[$v]['total']);
            $returnData[$k]['factMoney'] =  sprintf('%.2f',$factMoney[$v]['fact']);
            
            $returnData[$k]['oneTimeMoneyOrder'] = $info[$v]['oneTimeMoneyOrder'];
            $returnData[$k]['oneTimeMoneyOrderRate'] = $info[$v]['oneTimeMoneyOrder'] ? sprintf('%.2f',$info[$v]['oneTimeMoneyOrder']/$info[$v]['order']*100).'%' : '0%';

            $returnData[$k]['ROI'] = $returnData[$k]['totalMoney'] ? sprintf('%.2f',$returnData[$k]['totalMoney']/$returnData[$k]['cost']) : '';
        }
   
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        return $return;
    }
    //渠道明细数据
    public function xaWxGroupDataQdDetailData(){
    	$data = input();
        $sales_group_name = $data['sales_group_name'];
        if(empty($sales_group_name)){
        	return array('code' => 100,'msg'=>'未获取到组名');
        }
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        // $det = db('s_report_form')->alias('f')->join('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();
        // $shop_code = $det['shop_code'];
        $shop_code = session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        // 基础条件
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = $shop_code;
        // 消费类型
        if((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }
        // 渠道
        // if($data['channel_id']){
        //     $channels = explode(',',$data['channel_id']);
        // }else{
        //     // 来源渠道
        //     $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        //     $channels = array_column($channels,'channel_name');
        // }
        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
       
        $channelsName = array_column($channels,'channel_name');
        
        // 所有的组
        if($sales_group_name != '总计'){
        	$groupwhere['group_name'] = $sales_group_name;
        }

        $allGroups = db('c_staff_group')->where('shop_code',$shop_code)->where($groupwhere)->select();
        $allGroupsId = array_column($allGroups, 'id');

        $groupsStaff = db('c_staff_group_relation')->where('group_id','in',$allGroupsId)->select();
        foreach ($groupsStaff as $key => $value) {
        	$groupsStaffName[$value['staff_id']] = $groupsStaff[$key];
        }
        $staff_id = array_column($groupsStaff,'staff_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)) as valid,';//有效客资
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=3) as unValid,';//无效客资
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=2) as dd,';//待定客资
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and wechat_status=2) as jiaWx,';//已加微信
        // $sql .= 'sum(yjd_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(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in ("2","3","5") and DATE_FORMAT(syjd_day,"%w") IN (0,6) ) as wendjd,';//周末进店量
        $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`, ';//成交量
        $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=1) as `onlineorder`, ';// 线上成交量
        // 当日订单量
        $sql .= 'sum(DATE_FORMAT(dj_day, "%Y%m%d")=DATE_FORMAT(order_day,"%Y%m%d") and order_day between "'.$start.'" and "'.$end.'" and is_success=1 ) as todayOrder';
        $info = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where($whereT)
            ->where('c.sales_staff_id','in',$staff_id)
            ->group('c.customer_channel')
            ->column($sql.',c.customer_channel', 'c.customer_channel');
        // echo db()->getLastSql();
        // die;
        // 组实收
        $factMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where($whereT)
            ->where('c.sales_staff_id','in',$staff_id)
            ->where('order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(c.fact_money) as fact,c.customer_channel_id,c.customer_channel', 'c.customer_channel');
        // 组营收
        $totalMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where($whereT)
            ->where('c.sales_staff_id','in',$staff_id)
            ->where('order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(c.totalpay_money) as total,c.customer_channel_id,c.customer_channel', 'c.customer_channel');
        // 计算组客资花费
        $whereCost['shop_code'] = $shop_code;
        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        $channels = array_column($channels,'channel_name');
        // 渠道花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where($whereCost)
            ->where('channel_name','in',$channels)
            ->group('channel_name')
            ->column('sum(cost) as cost','channel_name');
        // 渠道客资
        $cusNum = db('c_customerinfo')
            ->where('dj_day', 'between time', [$start, $end])
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('customer_channel')
            ->column('count(id) as num','customer_channel');
        $allChannelInfo = [];
        foreach ($cost as $key => $value) {
            $allChannelInfo[$key]['channel_name'] = $key;
            $allChannelInfo[$key]['cost'] = $value;
            $allChannelInfo[$key]['num'] = $cusNum[$key];
            $allChannelInfo[$key]['cb']  = $value / $cusNum[$key];
        }        
        // 组渠道客资量
        $groupCusNum = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where('f.sales_group_name','not null')
            ->where('customer_channel','in',$channels)
            ->where('dj_day', 'between time', [$start, $end])
            ->group('c.customer_channel,customer_channel')
            ->field('c.customer_channel_id,c.sales_staff,customer_channel,count(c.id) as num')
            ->select();
        // 组客资花费
        $groupCost = [];
        foreach ($groupCusNum as $key => $value) {
            $groupCost[$value['customer_channel']] += $allChannelInfo[$value['customer_channel']]['cb']*$value['num'];
        }
        $returnData = [];
        $arr = [];
        foreach($channelsName as $k=>$v){
            $returnData[$k]['sales_group_name'] = $sales_group_name;
            $returnData[$k]['channels_name'] = $v;
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            $returnData[$k]['valid'] = $info[$v]['valid'];
            $returnData[$k]['unValid'] = $info[$v]['unValid'];
            $returnData[$k]['yjwechat'] = $info[$v]['jiaWx'];
            $returnData[$k]['wechatRate']= $info[$v]['jiaWx'] ? sprintf('%.2f',$info[$v]['jiaWx']/$info[$v]['mkz']*100).'%' : '0%';
            // $returnData[$k]['dd'] = $info[$v]['dd'];
            // $returnData[$k]['yy'] = $info[$v]['yy'];
            $returnData[$k]['jd'] = $info[$v]['jd'];
            $returnData[$k]['wendjd'] = $info[$v]['wendjd'];
            $returnData[$k]['nwendjd'] = $info[$v]['jd'] - $info[$v]['nwendjd'];
            $returnData[$k]['order'] = $info[$v]['order'];
            $returnData[$k]['todayOrder'] = $info[$v]['todayOrder'];
            $returnData[$k]['dayOrderRate'] = $info[$v]['todayOrder'] ? sprintf('%.2f',$info[$v]['todayOrder']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['onlineorder'] = $info[$v]['onlineorder'];
            $returnData[$k]['intoorder'] = $returnData[$k]['order'] - $returnData[$k]['onlineorder'];
            $returnData[$k]['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValidRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddRate'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['mkzJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['jdOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['jd']*100).'%' : '0%';
            $returnData[$k]['mkzOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['cost'] = sprintf('%.2f',$groupCost[$v]);
            $returnData[$k]['mkzCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['mkz']) : '';
            $returnData[$k]['validCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['valid']) : '';
            $returnData[$k]['jdCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['jd']) : '';
            $returnData[$k]['orderCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['order']) : '';
            $returnData[$k]['orderAVG'] =  $info[$v]['order'] ? sprintf('%.2f',$totalMoney[$v]['total']/$info[$v]['order']) : '';
            $returnData[$k]['totalMoney'] =  sprintf('%.2f',$totalMoney[$v]['total']);
            $returnData[$k]['factMoney'] =  sprintf('%.2f',$factMoney[$v]['fact']);
            $returnData[$k]['ROI'] = $returnData[$k]['totalMoney'] ? sprintf('%.2f',$returnData[$k]['totalMoney']/$returnData[$k]['cost']) : '';
        }

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

}