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

class Ls_shop_data extends Report {

    private $level=1;
    private $type=3;
    private $code='code1546682857';

    public function getLevel(){
        return $this->level;

    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data()
    {
        $data = input();
        $start = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));

        $where['is_status'] = 1;
        $where['c_from'] = 1;

        if($data['consultation_type_id']){
            $whereT['c.consultation_type_id'] = intval($data['consultation_type_id']);
        }
        $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();
        //已设置的归属店
        // $checked_shop = db_config('dj_shops_'.session('shop_code'));
        // $shop_code = $data['shop_code'] ? explode(',',$data['shop_code']) : array_column($checked_shop,'shop_code');
        $shop_code = $data['shop_code'] ? explode(',',$data['shop_code']) : '';
        if(!$shop_code){
            $mc = new \app\common\lib\mcInterface();
            $temp_shop_code = $mc->getWorkShop(['staff_id'=>session('staff_id')]);
            if($temp_shop_code){
                $shop_code = array_column($temp_shop_code, 'shop_code');
            }
        }

        // 花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where('belong_shop_code','in',$shop_code)
            ->group('belong_shop_code')
            ->column('sum(cost)','belong_shop_code');
        $sql1 = db()->getLastSql();

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        if($data['consultation_type_id']){
            $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=1 and consultation_type_id='.$data['consultation_type_id'].') as valid,';
            $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in ("2","3","5") and consultation_type_id='.$data['consultation_type_id'].') as jd,';
            $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'"  and is_success=2 and is_intostore in ("2","3","5") and consultation_type_id='.$data['consultation_type_id'].') as zd,';
            // $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=2 and consultation_type_id='.$data['consultation_type_id'].') as jdOrder,';
            // $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=1 and consultation_type_id='.$data['consultation_type_id'].') as `online`,';
            // $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and consultation_type_id='.$data['consultation_type_id'].') as `order`';
            $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and fact_money>100 and order_type=2 and consultation_type_id='.$data['consultation_type_id'].') as jdOrder,';
            $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and fact_money>500 and order_type=1 and consultation_type_id='.$data['consultation_type_id'].') as `online`,';
            $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and ((order_type=1 and fact_money>500)or(order_type=2 and fact_money>100)) and consultation_type_id='.$data['consultation_type_id'].') as `order`';
        }else{
            $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=1) as valid,';
            $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_success=2 and is_intostore in ("2","3","5")) as zd,';
            // $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=2) as jdOrder,';
            // $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=1) as `online`,';
            // $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`';
            $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and fact_money>100 and order_type=2) as jdOrder,';
            $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and fact_money>500 and order_type=1) as `online`,';
            $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and ((order_type=1 and fact_money>500)or(order_type=2 and fact_money>100))) as `order`';
        }
        $where_ext = [
            'c.sales_staff_id'  =>  ['>',0],
            'c.shop_code'  =>  ['in',$shop_code],
        ];
        // 渠道
        if($data['channel_id']){
            $channels = explode(',',$data['channel_id']);
            $where_ext['c.customer_channel'] = ['in',$channels];
        }
        // else{
            // 来源渠道
            //$channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            // if(is_array($shop_code)){
            //     foreach($shop_code as $v){
            //         $channel = controller('crm/Customer', 'lib')->getChannel($v);
            //         if($channel){
            //             foreach($channel as $val){
            //                 $channels[] = $val;
            //             }
            //         }
            //     }
            // }else{
                // $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            // }
            // $channels = array_column($channels,'channel_name');
        // }
        $info = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where($where_ext)
            ->group('shop_code')
            ->column($sql,'shop_code');
        $sql2 = db()->getLastSql();
        // echo db()->getLastSql();die;
        $whereN['c.is_status'] = 1;
        $whereN['c.c_from'] = 1;
        // 营收（一销）
        $fact = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($whereN)
            ->where($where_ext)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.shop_code')
            ->column('sum(d.order_fact)','c.shop_code');
        $sql3 = db()->getLastSql();
        // 套系（一销）
        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($whereN)
            ->where($where_ext)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->group('c.shop_code')
            ->column('sum(o.order_amount)','c.shop_code');
        $sql4 = db()->getLastSql();
        $returnData = [];
        $total = [];
        $total['shop_name'] = '总计';
        $shopInfo = getShopInfo();
        foreach($shop_code as $k=>$v){
            $arr = [];
            $arr['shop_name'] = $shopInfo[$v]['shop_name'];
            $arr['cost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]) : '';
            $arr['mkz'] = $info[$v]['mkz'];
            $arr['valid'] = $info[$v]['valid'];
            $arr['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $arr['mkzCost'] = $info[$v]['mkz'] ? sprintf('%.2f',$cost[$v]/$info[$v]['mkz']) : '';//客资成本
            $arr['validCost'] = $info[$v]['valid'] ? sprintf('%.2f',$cost[$v]/$info[$v]['valid']) : '';//有效客资成本
            $arr['jd'] = $info[$v]['jd'];
            $arr['jdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['valid']*100).'%' : '0%';//进店率
            $arr['jdOrder'] = $info[$v]['jdOrder'];
            $arr['online'] = $info[$v]['online'];
            $arr['order'] = $info[$v]['order'];
            $arr['orderCost'] = $info[$v]['order'] ? sprintf('%.2f',$cost[$v]/$info[$v]['order']) : '';//订单成本
            $arr['orderRate'] = $info[$v]['jdOrder'] ? sprintf('%.2f',$info[$v]['jdOrder']/$info[$v]['jd']*100).'%' : '0%';//成交率
            $arr['zd'] = $info[$v]['zd'];
            $arr['mkzRate'] = $info[$v]['order'] ? sprintf('%.2f',($arr['jdOrder']+$arr['online'])/$info[$v]['mkz']*100).'%' : '0%';//毛客资转化率
            $arr['fact'] = $fact[$v]? sprintf('%.2f',$fact[$v]) : '';
            $arr['amount'] = $amount[$v] ? sprintf('%.2f',$amount[$v]) : '';
            $arr['avg'] = $amount[$v] ? sprintf('%.2f',$amount[$v]/$info[$v]['order']) : '';
            $arr['roi'] = $cost[$v] ? sprintf('%.2f',$fact[$v]/$cost[$v]).':1' : '';
            $returnData[] = $arr;
            $total['shop_name'] = '总计';
            $total['cost'] += floatval($arr['cost']);
            $total['mkz'] += $arr['mkz'];
            $total['valid'] += $arr['valid'];
            $total['validRate'] = '';
            $total['mkzCost'] = '';
            $total['validCost'] = '';
            $total['jd'] += $arr['jd'];
            $total['jdRate'] = '';
            $total['jdOrder'] += $arr['jdOrder'];
            $total['online'] += $arr['online'];
            $total['order'] += $arr['order'];
            $total['orderCost'] = '';
            $total['orderRate'] = '';
            $total['zd'] += $arr['zd'];
            $total['mkzRate'] = '';
            $total['fact'] += floatval($arr['fact']);
            $total['amount'] += floatval($arr['amount']);
            $total['avg'] = '';
        }
        $total['validRate'] = $total['valid'] ? sprintf('%.2f',$total['valid']/$total['mkz']*100).'%' : '0%';
        $total['mkzCost'] = $total['cost'] ? sprintf('%.2f',$total['cost']/$total['mkz']) : '';
        $total['validCost'] = $total['cost'] ? sprintf('%.2f',$total['cost']/$total['valid']) : '';
        $total['jdRate'] = $total['jd'] ? sprintf('%.2f',$total['jd']/$total['valid']*100).'%' : '0%';
        $total['orderCost'] = $total['cost'] ? sprintf('%.2f',$total['cost']/$total['order']) : '';
        $total['orderRate'] = $total['order'] ? sprintf('%.2f',$total['jdOrder']/$total['jd']*100).'%' : '0%';
        $total['mkzRate'] = $total['order'] ? sprintf('%.2f',($total['jdOrder']+$total['online'])/$total['mkz']*100).'%' : '0%';
        $total['avg'] = $total['amount'] ? sprintf('%.2f',$total['amount']/$total['order']) : '';
        $total['roi'] = $total['cost'] ? sprintf('%.2f',$total['fact']/$total['cost']).':1' : '';
        $returnData[] = $total;

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

        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['sql4'] = $sql4;
        // 导出
        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(){
        $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();
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        //来源渠道
        $channel = getChannelJson(session('shop_code'));
        $this->assign("channel", json_encode($channel));
        //已设置的归属店
        $checked_shop = db_config('dj_shops_'.session('shop_code'));
        $this->assign('shop',$checked_shop);
        $code = $this->getCode();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('s_report_form')->where('code', $code)->value('report_name');
        $this->assign('title', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }
}