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

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

    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;
        $where['customer_type'] = 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();
        $shop_code = $det['shop_code'];
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        //本地外地
        $city = db_config('sx_city_id_'.$det['brandclass_id']);
        // 花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where('shop_code',$shop_code)
            ->where('city_id',$city)
            ->sum('cost');

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=1) as mkz,';
        if($data['consultation_type_id']){
            $sql .= 'sum(yx_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) and consultation_type_id='.$data['consultation_type_id'].') as jd,';
            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and consultation_type_id='.$data['consultation_type_id'].') as `order`,';
        }else{
            $sql .= 'sum(yx_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)) as jd,';
            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`,';
        }

        $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and (is_intostore=2 or is_intostore=3) and is_success=2) as zd';//走单
        $info = db('c_customerinfo')
            ->where($where)
            ->where('city_id',$city)
            ->field($sql)
            ->find();
        $whereN['c.is_status'] = 1;
        $whereN['c.c_from'] = 1;
        $whereN['c.customer_type'] = 1;
        $whereN['c.add_shop_code'] = $shop_code;
        // 营收（一销）
        $fact = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($whereN)
            ->where('c.city_id',$city)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->sum('d.order_fact');
        // 套系（一销）
        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($whereN)
            ->where('c.city_id',$city)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->sum('o.order_amount');



        $startKPI = date('Y-m',strtotime($start));
        $endKPI = date('Y-m',strtotime($end));
        //有效目标 validCustomerNumber
        if($startKPI == $endKPI) {
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('city_id',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');

            $validmubiao = ceil($kpi*(date('Ymd',strtotime($end))-date('Ymd',strtotime($start))));

        }else{
            //本月占多少天
            //下月第一天
            $next_month_first_day = date('Y-m-01 00:00:00',strtotime($endKPI));
            //本月最后一天
            $last_month_day = date('Ymd',strtotime($next_month_first_day)-1);
            //本周在本月天数
            $this_week_last_day = date('Ymd',strtotime($last_month_day));
            $this_week_first_day = date('Ymd',strtotime($start));
            $this_week = $last_month_day-$this_week_first_day+1;

            //下月占多少天
            //本周在下月天数
            $first_day = date('Ymd',strtotime($next_month_first_day));
            $last_day = date('Ymd',strtotime($end));

            $last_week = $last_day-$first_day+1;
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('city_id',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $endKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('city_id',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $validmubiao = ceil($kpi*$this_week)+ceil($kpi_next*$last_week);

        }
        //进店目标 actualIntoCustomerNumber
        if($startKPI == $endKPI) {
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('city_id',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $jdmubiao = ceil($kpi*(date('Ymd',strtotime($end))-date('Ymd',strtotime($start))));
        }else{
            //本月占多少天
            //下月第一天
            $next_month_first_day = date('Y-m-01 00:00:00',strtotime($endKPI));
            //本月最后一天
            $last_month_day = date('Ymd',strtotime($next_month_first_day)-1);
            //本周在本月天数
            $this_week_last_day = date('Ymd',strtotime($last_month_day));
            $this_week_first_day = date('Ymd',strtotime($start));
            $this_week = $last_month_day-$this_week_first_day+1;

            //下月占多少天
            //本周在下月天数
            $first_day = date('Ymd',strtotime($next_month_first_day));
            $last_day = date('Ymd',strtotime($end));

            $last_week = $last_day-$first_day+1;
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('city_id',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $endKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('city_id',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $jdmubiao = ceil($kpi*$this_week)+ceil($kpi_next*$last_week);

        }

        $returnData = [];
        $returnData[0]['channel_name'] = '本地';
        $returnData[0]['cost'] = $cost ? sprintf('%.2f',$cost) : '';
        $returnData[0]['mkz'] = $info['mkz'];
        $returnData[0]['valid'] = $info['valid'];
        $returnData[0]['validRate'] = $info['valid'] ? sprintf('%.2f',$info['valid']/$info['mkz']*100).'%' : '0%';
        $returnData[0]['jd'] = $info['jd'];
        $returnData[0]['order'] = $info['order'];
        $returnData[0]['zd'] = $info['zd'];
        $returnData[0]['fact'] = $fact? sprintf('%.2f',$fact) : '';
        $returnData[0]['amount'] = $amount? sprintf('%.2f',$amount) : '';
        $returnData[0]['avg'] = $fact ? sprintf('%.2f',$fact/$info['order']) : '';
        $returnData[0]['jdRate'] = $info['jd'] ? sprintf('%.2f',$info['jd']/$info['valid']*100).'%' : '0%';//进店率
        $returnData[0]['succRate'] = $info['order'] ? sprintf('%.2f',$info['order']/$info['jd']*100).'%' : '0%';//成交率
        $returnData[0]['orderCost'] = $info['order'] ? sprintf('%.2f',$cost/$info['order']).'%' : '';//订单成本
        $returnData[0]['notice'] = $fact ? sprintf('%.2f',$cost/$fact*100).'%' : '0%';//广告占比  花费/一销实收
        $returnData[0]['validmubiao'] = $validmubiao ? $validmubiao : '';//有效目标
        $returnData[0]['validmubiaoRate'] = $validmubiao ? sprintf('%.2f',$info['valid']/$validmubiao*100).'%' : '0%';//完成率
        $returnData[0]['jdmubiao'] = $jdmubiao ? $jdmubiao : '';//进店目标
        $returnData[0]['jdmubiaoRate'] = $jdmubiao ? sprintf('%.2f',$info['jd']/$jdmubiao*100).'%' : '0%';//完成率

        //外地
        // 花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where('shop_code',$shop_code)
            ->where('city_id','<>',$city)
            ->sum('cost');
        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=1) as mkz,';
        if($data['consultation_type_id']){
            $sql .= 'sum(yx_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) and consultation_type_id='.$data['consultation_type_id'].') as jd,';
            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and consultation_type_id='.$data['consultation_type_id'].') as `order`,';
        }else{
            $sql .= 'sum(yx_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)) as jd,';
            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`,';
        }

        $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and (is_intostore=2 or is_intostore=3) and is_success=2) as zd';//走单
        $info = db('c_customerinfo')
            ->where($where)
            ->where('city_id','<>',$city)
            ->field($sql)
            ->find();


        // 营收（一销）
        $fact = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($whereN)
            ->where('c.city_id','<>',$city)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->sum('d.order_fact');
        // 套系（一销）
        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($whereN)
            ->where('c.city_id','<>',$city)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->sum('o.order_amount');



        $startKPI = date('Y-m',strtotime($start));
        $endKPI = date('Y-m',strtotime($end));
        //有效目标 validCustomerNumber
        if($startKPI == $endKPI) {
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('city_id','<>',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');

            $validmubiao = ceil($kpi*(date('Ymd',strtotime($end))-date('Ymd',strtotime($start))));

        }else{
            //本月占多少天
            //下月第一天
            $next_month_first_day = date('Y-m-01 00:00:00',strtotime($endKPI));
            //本月最后一天
            $last_month_day = date('Ymd',strtotime($next_month_first_day)-1);
            //本周在本月天数
            $this_week_last_day = date('Ymd',strtotime($last_month_day));
            $this_week_first_day = date('Ymd',strtotime($start));
            $this_week = $last_month_day-$this_week_first_day+1;

            //下月占多少天
            //本周在下月天数
            $first_day = date('Ymd',strtotime($next_month_first_day));
            $last_day = date('Ymd',strtotime($endKPI));

            $last_week = $last_day-$first_day+1;
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('city_id','<>',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $endKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('city_id','<>',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $validmubiao = ceil($kpi*$this_week)+ceil($kpi_next*$last_week);

        }
        //进店目标 actualIntoCustomerNumber
        if($startKPI == $endKPI) {
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('city_id','<>',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $jdmubiao = ceil($kpi*(date('Ymd',strtotime($end))-date('Ymd',strtotime($start))));
        }else{
            //本月占多少天
            //下月第一天
            $next_month_first_day = date('Y-m-01 00:00:00',strtotime($endKPI));
            //本月最后一天
            $last_month_day = date('Ymd',strtotime($next_month_first_day)-1);
            //本周在本月天数
            $this_week_last_day = date('Ymd',strtotime($last_month_day));
            $this_week_first_day = date('Ymd',strtotime($start));
            $this_week = $last_month_day-$this_week_first_day+1;

            //下月占多少天
            //本周在下月天数
            $first_day = date('Ymd',strtotime($next_month_first_day));
            $last_day = date('Ymd',strtotime($endKPI));

            $last_week = $last_day-$first_day+1;
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('city_id','<>',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $endKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where('city_id','<>',$city)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->value('avg_value');
            $jdmubiao = ceil($kpi*$this_week)+ceil($kpi_next*$last_week);

        }
        $returnData[1]['channel_name'] = '外地';
        $returnData[1]['cost'] = $cost ? sprintf('%.2f',$cost) : '';
        $returnData[1]['mkz'] = $info['mkz'];
        $returnData[1]['valid'] = $info['valid'];
        $returnData[1]['validRate'] = $info['valid'] ? sprintf('%.2f',$info['valid']/$info['mkz']*100).'%' : '0%';
        $returnData[1]['jd'] = $info['jd'];
        $returnData[1]['order'] = $info['order'];
        $returnData[1]['zd'] = $info['zd'];
        $returnData[1]['fact'] = $fact? sprintf('%.2f',$fact) : '';
        $returnData[1]['amount'] = $amount? sprintf('%.2f',$amount) : '';
        $returnData[1]['avg'] = $fact ? sprintf('%.2f',$fact/$info['order']) : '';
        $returnData[1]['jdRate'] = $info['jd'] ? sprintf('%.2f',$info['jd']/$info['valid']*100).'%' : '0%';//进店率
        $returnData[1]['succRate'] = $info['order'] ? sprintf('%.2f',$info['order']/$info['jd']*100).'%' : '0%';//成交率
        $returnData[1]['orderCost'] = $info['order'] ? sprintf('%.2f',$cost/$info['order']) : '';//订单成本
        $returnData[1]['notice'] = $fact ? sprintf('%.2f',$cost/$fact*100).'%' : '0%';//广告占比  花费/一销实收
        $returnData[1]['validmubiao'] = $validmubiao ? $validmubiao : '';//有效目标
        $returnData[1]['validmubiaoRate'] = $validmubiao ? sprintf('%.2f',$info['valid']/$validmubiao*100).'%' : '0%';//完成率
        $returnData[1]['jdmubiao'] = $jdmubiao ? $jdmubiao : '';//进店目标
        $returnData[1]['jdmubiaoRate'] = $jdmubiao ? sprintf('%.2f',$info['jd']/$jdmubiao*100).'%' : '0%';//完成率

        //总计
        $returnData[2]['channel_name'] = '总计';
        $returnData[2]['cost'] = sprintf('%.2f',$returnData[0]['cost']+$returnData[1]['cost']);
        $returnData[2]['mkz'] = $returnData[0]['mkz']+$returnData[1]['mkz'];
        $returnData[2]['valid'] = $returnData[0]['valid']+$returnData[1]['valid'];
        $returnData[2]['validRate'] = sprintf('%.2f',$returnData[2]['valid']/$returnData[2]['mkz']*100).'%';
        $returnData[2]['jd'] = $returnData[0]['jd']+$returnData[1]['jd'];
        $returnData[2]['order'] = $returnData[0]['order']+$returnData[1]['order'];
        $returnData[2]['zd'] = $returnData[0]['zd']+$returnData[1]['zd'];
        $returnData[2]['fact'] = sprintf('%.2f',$returnData[0]['fact']+$returnData[1]['fact']);
        $returnData[2]['amount'] = sprintf('%.2f',$returnData[0]['amount']+$returnData[1]['amount']);
        $returnData[2]['avg'] = sprintf('%.2f',$returnData[0]['avg']+$returnData[1]['avg']);
        $returnData[2]['jdRate'] = sprintf('%.2f',$returnData[0]['dRate']+$returnData[1]['dRate']).'%';
        $returnData[2]['succRate'] = sprintf('%.2f',$returnData[0]['succRate']+$returnData[1]['succRate']).'%';
        $returnData[2]['orderCost'] = sprintf('%.2f',$returnData[0]['orderCost']+$returnData[1]['orderCost']);
        $returnData[2]['notice'] = sprintf('%.2f',$returnData[0]['notice']+$returnData[1]['notice']).'%';
        $returnData[2]['validmubiao'] = $returnData[0]['validmubiao']+$returnData[1]['validmubiao'];
        $returnData[2]['validmubiaoRate'] = sprintf('%.2f',$returnData[0]['validmubiaoRate']+$returnData[1]['validmubiaoRate']).'%';
        $returnData[2]['jdmubiao'] = $returnData[0]['jdmubiao']+$returnData[1]['jdmubiao'];
        $returnData[2]['jdmubiaoRate'] = sprintf('%.2f',$returnData[0]['jdmubiaoRate']+$returnData[1]['jdmubiaoRate']).'%';
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array( '渠道名称', '花费','毛客资', '有效客资', '有效率','进店', '订单', '走单', '一销套系', '一销实收', '一销均价', '进店率', '成交率', '订单成本', '广告占比','有效目标','完成率','进店目标','完成率');
            $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);
        $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);
    }

}