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

class Jxdt_wx_staff_data extends Report {

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

    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('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'=>'报表配置有误');
        }
        // 渠道
        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((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.add_shop_code'] = $shop_code;
        // 所有追踪人
        $allStaffs = db('c_customerinfo')->alias('c')
            ->where('dj_day','between',[$start,$end])
            ->where('shop_code',$shop_code)
            ->where('sales_staff_id','>',0)
            ->where($where)
            ->group('sales_staff')
            ->field('sales_staff,sales_staff_id')->select();
        $staffs = array_column($allStaffs,'sales_staff');

        $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 in (3)) as unValid,';
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.wechat_status=2) as jiaWx,';//已加微信
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.yjd_day IS NOT NULL) as yy,';
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in (\'2\',\'3\',\'5\')) as jd,';
        $sql .= 'sum(c.order_start_time between "'.$start.'" and "'.$end.'" and c.is_success!=2) as `order`, ';        
        // 线上成交量
        $sql .= 'sum(c.order_start_time between "'.$start.'" and "'.$end.'" and c.is_success!=2 and c.order_type=1) as `onlineorder`';
        // 基础数据
        $info = db('c_customerinfo')->alias('c')
            // ->join('c_customer_from f','c.id=f.cid','left')
            ->where($where)->where($whereT)
            ->where('customer_channel','in',$channels)
            ->where('c.sales_staff','in',$staffs)
            ->group('c.sales_staff')
            ->column($sql, 'c.sales_staff');
        $sql1 = db()->getLastSql();
        // 总实收
        $AllTotal = db('c_customerinfo')->alias('c')
            ->join("c_customer_order o","o.customer_id=c.id","left")
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->where('c.sales_staff','in',$staffs)
            ->group('c.sales_staff')
            ->column('sum(o.order_amount) as total', 'c.sales_staff');
        $sql2 = db()->getLastSql();
        // 总营收
        $AllFact = db('c_customerinfo')->alias('c')
            ->join("c_customer_order o","o.customer_id=c.id","left")
            ->join("c_order_detail d","d.order_sn=o.order_sn","left")
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->where($where)->where('d.pay_type', 1)
            ->where('c.customer_channel','in',$channels)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->where('c.sales_staff','in',$staffs)
            ->group('c.sales_staff')
            ->column('sum(d.order_fact) as fact', 'c.sales_staff');
        $sql2_1 = db()->getLastSql();
        // 线上实收
        $onlineTotal = db('c_customerinfo')->alias('c')
            ->join("c_customer_order o","o.customer_id=c.id","left")
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('c.order_type',1)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->where('c.sales_staff','in',$staffs)
            ->group('c.sales_staff')
            ->column('sum(c.totalpay_money) as total', 'c.sales_staff');
        $sql3 = db()->getLastSql();
        // 线上营收
        $onlineFact = db('c_customerinfo')->alias('c')
            ->join("c_customer_order o","o.customer_id=c.id","left")
            ->join("c_order_detail d","d.order_sn=o.order_sn","left")
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->where($where)->where('d.pay_type', 1)->where('c.order_type',1)
            ->where('c.customer_channel','in',$channels)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->where('c.sales_staff','in',$staffs)
            ->group('c.sales_staff')
            ->column('sum(d.order_fact) as fact', 'c.sales_staff');
        $sql3_1 = db()->getLastSql();
        // 计算客资花费
        $whereCost['shop_code'] = $shop_code;
        // $whereCost['belong_shop_code'] = $shop_code;
        // 渠道花费
        $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');
        $sql4 = db()->getLastSql();
        // var_dump($cost);die;
        // 渠道客资
        $cusNum = db('c_customerinfo')->alias('c')
            ->where('dj_day', 'between time', [$start, $end])
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('customer_channel')
            ->column('count(id) as num','customer_channel');
        $sql5 = db()->getLastSql();
        $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];
        }
        // 员工渠道客资量
        $staffCusNum = db('c_customerinfo')->alias('c')
            ->where('c.dj_day', 'between time', [$start, $end])
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('c.sales_staff,c.customer_channel')
            ->field('c.sales_staff,c.customer_channel,count(c.id) as num')
            ->select();
        $sql6 = db()->getLastSql();
        // 员工客资花费
        $staffCost = [];
        foreach ($staffCusNum as $key => $value) {
            $staffCost[$value['sales_staff']] += $allChannelInfo[$value['customer_channel']]['cb']*$value['num'];
        }
        $returnData = [];
        $arr = [];
        foreach($staffs as $k=>$v){
            $returnData[$k]['staff_name'] = $v;
            // 投产数据
            $returnData[$k]['cost'] = $staffCost[$v] ? sprintf('%.2f',$staffCost[$v]) : '0.00';
            $returnData[$k]['totalMoney'] = $AllTotal[$v] ? sprintf('%.2f',$AllTotal[$v]) : '0.00';
            $returnData[$k]['factMoney'] = $AllFact[$v] ? sprintf('%.2f',$AllFact[$v]) : '0.00';
            $returnData[$k]['ROI'] = $returnData[$k]['factMoney'] ? sprintf('%.2f',$returnData[$k]['factMoney']/$returnData[$k]['cost']) : '0%';
            // 网销总转化数据
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            // $returnData[$k]['mkzCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['mkz']) : '';
            $returnData[$k]['valid'] = $info[$v]['valid'];
            // $returnData[$k]['validCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['valid']) : '';
            $returnData[$k]['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValid'] = $info[$v]['unValid'];
            $returnData[$k]['unValidRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['jiaWx'] = $info[$v]['jiaWx'];
            $returnData[$k]['jiaWxRate'] = $info[$v]['jiaWx'] ? sprintf('%.2f',$info[$v]['jiaWx']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['order'] = $info[$v]['order'];
            $returnData[$k]['mkzOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
            // 转化成本
            $returnData[$k]['jdCost'] = $returnData[$k]['cost'] ? sprintf('%.2f',$returnData[$k]['cost']/$info[$v]['jd']) : '';
            $returnData[$k]['orderCost'] = $returnData[$k]['cost'] ? sprintf('%.2f',$returnData[$k]['cost']/$info[$v]['order']) : '';
            // 网销线下转化数据
            $returnData[$k]['yy'] = $info[$v]['yy'];
            $returnData[$k]['yyRate'] = $info[$v]['yy'] ? sprintf('%.2f',$info[$v]['yy']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['jd'] = $info[$v]['jd'];
            $returnData[$k]['mkzJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['intoorder'] = $info[$v]['order'] - $info[$v]['onlineorder'];
            $returnData[$k]['intoorderRate'] = $returnData[$k]['intoorder'] ? sprintf('%.2f',$returnData[$k]['intoorder']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['intoTotalMoney'] = sprintf('%.2f',$AllTotal[$v]-$onlineTotal[$v]);
            $returnData[$k]['intoFactMoney'] = sprintf('%.2f',$AllFact[$v]-$onlineFact[$v]);
            $returnData[$k]['intoMoneyRate'] = $returnData[$k]['intoFactMoney'] ? sprintf('%.2f',$returnData[$k]['intoFactMoney']/$returnData[$k]['intoTotalMoney']*100).'%' : '0%';
            $returnData[$k]['intoAvg'] = $returnData[$k]['intoTotalMoney'] ? sprintf('%.2f',$returnData[$k]['intoTotalMoney']/$returnData[$k]['intoorder']) : '0';
            // 网销线上转化数据
            $returnData[$k]['onlineorder'] = $info[$v]['onlineorder'];
            $returnData[$k]['onlineorderRate'] = $info[$v]['onlineorder'] ? sprintf('%.2f',$info[$v]['onlineorder']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['onlineTotalMoney'] = sprintf('%.2f',$onlineTotal[$v]);
            $returnData[$k]['onlineFactlMoney'] = sprintf('%.2f',$onlineFact[$v]);
            $returnData[$k]['onlineAvg'] = $returnData[$k]['onlineTotalMoney'] ? sprintf('%.2f',$returnData[$k]['onlineTotalMoney']/$returnData[$k]['onlineorder']) : '0';
            //总计
            $arr['staff_name'] = '总计';
            $arr['cost'] += $returnData[$k]['cost'];
            $arr['totalMoney'] += $returnData[$k]['totalMoney'];
            $arr['factMoney'] += $returnData[$k]['factMoney'];
            $arr['ROI'] = '0.00';
            // 推广数据
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['mkzCost'] = '0.00';
            $arr['valid'] += $returnData[$k]['valid'];
            $arr['validCost'] = '0.00';
            $arr['validRate'] = '0%';
            $arr['unValid'] += $returnData[$k]['unValid'];
            $arr['unValidRate'] = '0.00%';
            // 网销总转化数据
            $arr['jiaWx'] += $returnData[$k]['jiaWx'];
            $arr['jiaWxRate'] = '0%';
            $arr['order'] += $returnData[$k]['order'];
            $arr['mkzOrderRate'] = '0%';
            // 转化成本
            $arr['jdCost'] = '0.00';
            $arr['orderCost'] = '0.00';
            // 网销线下转化数据
            $arr['yy'] += $returnData[$k]['yy'];
            $arr['yyRate'] = '0%';
            $arr['jd'] += $returnData[$k]['jd'];
            $arr['mkzJdRate'] = '0%';
            $arr['intoorder'] += $returnData[$k]['intoorder'];
            $arr['intoorderRate'] = '0%';
            $arr['intoTotalMoney'] += $returnData[$k]['intoTotalMoney'];
            $arr['intoFactMoney'] += $returnData[$k]['intoFactMoney'];
            $arr['intoMoneyRate'] = '0%';
            $arr['intoAvg'] = '0.00';
            // 网销线上转化数据
            $arr['onlineorder'] += $returnData[$k]['onlineorder'];
            $arr['onlineorderRate'] = '0%';
            $arr['onlineTotalMoney'] += $returnData[$k]['onlineTotalMoney'];
            $arr['onlineFactlMoney'] += $returnData[$k]['onlineFactlMoney'];
            $arr['onlineAvg'] = '0.00';
        }
        // 总计
        $arr['ROI'] = $arr['factMoney'] ? sprintf('%.2f',$arr['factMoney']/$arr['cost']) : '0';
        $arr['mkzCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['mkz']) : '0';
        $arr['validCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['valid']) : '0';
        $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
        $arr['unValidRate'] = $arr['unValid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['jiaWxRate'] = $arr['jiaWx'] ? sprintf('%.2f',$arr['jiaWx']/$arr['mkz']*100).'%' : '0%';
        $arr['mkzOrderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '0%';
        $arr['jdCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['jd']) : '';
        $arr['orderCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '';
        $arr['yyRate'] = $arr['yy'] ? sprintf('%.2f',$arr['yy']/$arr['mkz']*100).'%' : '0%';
        $arr['mkzJdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0%';
        $arr['intoorderRate'] = $arr['intoorder'] ? sprintf('%.2f',$arr['intoorder']/$arr['mkz']*100).'%' : '0%';
        $arr['intoMoneyRate'] = $arr['intoFactMoney'] ? sprintf('%.2f',$arr['intoFactMoney']/$arr['intoTotalMoney']*100).'%' : '0%';
        $arr['intoAvg'] = $arr['intoTotalMoney'] ? sprintf('%.2f',$arr['intoTotalMoney']/$arr['intoorder']) : '0';
        $arr['onlineorderRate'] = $arr['onlineorder'] ? sprintf('%.2f',$arr['onlineorder']/$arr['mkz']*100).'%' : '0%';
        $arr['onlineAvg'] = $arr['onlineTotalMoney'] ? sprintf('%.2f',$arr['onlineTotalMoney']/$arr['onlineorder']) : '0';

        $returnData[] = $arr;

        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['sql4'] = $sql4;

        $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('s_report_form')->alias('f')->join('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();
        //来源渠道
        $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);

        $info = db('s_report_form')->where('code', $code)->field('report_class_name,report_name')->find();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $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);
    }
}