<?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 Jxdt_ds_tc_data_wx extends Report {

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

    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{
            // 来源渠道
            $channel = controller('crm/Customer', 'lib')->getChannel($shop_code);
            $channels = array_column($channel,'channel_name');
        }

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.add_shop_code'] = $shop_code;
        $whereCost['shop_code'] = $shop_code;

        // 网销
        $allStaffs = db('c_customerinfo')
            ->where('dj_day','between',[$start,$end])
            ->where('shop_code',$shop_code)
            ->where('is_status',1)->where('c_from',1)
            ->where('sales_staff_id','>',0)
            ->group('sales_staff')
            ->field('sales_staff,sales_staff_id,customer_channel,count(id) as num')->select();
        $staffs = array_column($allStaffs,'sales_staff');

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and is_success=1) as `order`';        

        $info = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('c.sales_staff','in',$staffs)
            ->group('c.sales_staff')
            ->column($sql, 'c.sales_staff');
        
        $sql1 = db()->getLastSql();
        // die;
        //花费
        $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');
        $sql2 = db()->getLastSql();
        // 渠道客资
        $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');
        $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();
        // 员工客资花费
        $staffCost = [];
        foreach ($staffCusNum as $key => $value) {
            $staffCost[$value['sales_staff']] += $allChannelInfo[$value['customer_channel']]['cb']*$value['num'];
        }
        // 总实收
        $AllTotal = db('c_customerinfo')->alias('c')
            ->join("c_customer_order o","o.customer_id=c.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');
        $sql3 = 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');
        $sql4 = db()->getLastSql();
        $returnData = [];
        $arr = [];
        foreach($staffs as $k=>$v){
            $returnData[$k]['name'] = $v;
            $returnData[$k]['cost'] = $staffCost[$v] ? sprintf('%.2f',$staffCost[$v]) : '0.00';
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            $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]['order'] = $info[$v]['order'];
            $returnData[$k]['Avg'] = $AllTotal[$v] ? sprintf('%.2f',$AllTotal[$v]/$info[$v]['order']) : '0';
            $returnData[$k]['mkzCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['mkz']) : '';
            $returnData[$k]['orderCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['order']) : '';
            $returnData[$k]['money'] = $AllTotal[$v];

            //总计
            $arr['name'] = '总计';
            $arr['cost'] += $returnData[$k]['cost'];
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['totalMoney'] += $returnData[$k]['totalMoney'];
            $arr['factMoney'] += $returnData[$k]['factMoney'];
            $arr['ROI'] = '0.00';
            $arr['order'] += $returnData[$k]['order'];
            $arr['Avg'] = '0.00';
            $arr['mkzCost'] = '0.00';
            $arr['orderCost'] = '0.00';
            $arr['money'] += $AllMoney[$k]['money'];
        }
        // 总计
        $arr['ROI'] = $arr['factMoney'] ? sprintf('%.2f',$arr['factMoney']/$arr['cost']*100) : '0';
        $arr['mkzCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['mkz']) : '0';
        $arr['orderCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '';
        $arr['Avg'] = $arr['money'] ? sprintf('%.2f',$arr['money']/$arr['order']) : '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;
        // 导出
        if ($data['need'] == 1) {
            $title = array('渠道名称', '毛客资', '有效客资', '无效客资', '待定客资', '预约数量', '入店量', '成交量', '有效率', '无效率', '待定率', '毛客资入店率', '有效客资入店率','入店成交率','毛客资成交率','有效客资成交率','花费', '毛客资成本', '有效客资成本','入店成本', '成交成本','成交均价','营业额','已收金额', 'ROI(已收:花费)');
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
            $file = $shop[0]['shop_name'].'-'.$ff.'.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            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);
    }
}