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

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

    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']);
        if(empty($city)){
            return array('code'=>101,'msg'=>'未设置本地配置,请先去配置');
        }
        if($data['city'] == 1){//本地
            if($city){
                $city_id = 'city_id='.$city;
                $Ccity_id = 'c.city_id='.$city;
            }else{
                $city_id = '';
                $Ccity_id = '';
            }
        }elseif($data['city'] == 2){//外地
            if($city){
                $city_id = 'city_id <>'.$city;
                $Ccity_id = 'c.city_id <>'.$city;
            }else{
                $city_id = '';
                $Ccity_id = '';
            }
        }else{
            $city_id = '';
            $Ccity_id = '';
        }
        // 花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where('shop_code',$shop_code)
            ->where($city_id)
            ->group('channel_id')
            ->column('sum(cost) as cost','channel_id');

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=1) as mkz,';
        $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)
            ->group('customer_channel_id')
            ->column($sql, 'customer_channel_id');
        $whereN['c.is_status'] = 1;
        $whereN['c.c_from'] = 1;
        $whereN['c.customer_type'] = 1;
        // 营收（一销）
        $fact = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($whereN)
            ->where($Ccity_id)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.customer_channel_id')
            ->column('sum(d.order_fact)','c.customer_channel_id');
        // 套系（一销）
        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($whereN)
            ->where($Ccity_id)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.customer_channel_id')
            ->column('sum(o.order_amount)','c.customer_channel_id');

        $channel = controller('crm/Customer','lib')->getChannel($shop_code);

        $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)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->group('channel_id')
                ->column('kpi_id,kpi_value,avg_value,channel_id', 'channel_id');
            $validmubiao = [];
            foreach($channel as $k=>$v){
                $validmubiao[$v['id']] = ceil($kpi[$v['id']]['avg_value']*($endKPI-$startKPI));
            }
        }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)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->group('channel_id')
                ->column('kpi_id,kpi_value,avg_value,channel_id', 'channel_id');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $endKPI)
                ->where('kpi_id', 'validCustomerNumber')
                ->where($city_id)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->group('channel_id')
                ->column('kpi_id,kpi_value,avg_value', 'channel_id');
            $validmubiao = [];
            foreach($channel as $k=>$v){
                $validmubiao[$v['id']] = ceil($kpi[$v['id']]['avg_value']*$this_week)+ceil($kpi_next[$v['id']]['avg_value']*$last_week);
            }
        }
        //进店目标 actualIntoCustomerNumber
        if($startKPI == $endKPI) {
            $kpi = db('s_kpi_staffgoal')
                ->where('month', $startKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where($city_id)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->group('channel_id')
                ->column('kpi_id,kpi_value,avg_value', 'channel_id');
            $jdmubiao = [];
            foreach($channel as $k=>$v){
                $jdmubiao[$v['id']] = ceil($kpi[$v['id']]['avg_value']*($endKPI-$startKPI));
            }
        }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)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->group('channel_id')
                ->column('kpi_id,kpi_value,avg_value', 'channel_id');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $endKPI)
                ->where('kpi_id', 'actualIntoCustomerNumber')
                ->where($city_id)
                ->where('shop_code', $shop_code)
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->group('channel_id')
                ->column('kpi_id,kpi_value,avg_value,channel_id', 'channel_id');
            $jdmubiao = [];
            foreach($channel as $k=>$v){
                $jdmubiao[$v['id']] = ceil($kpi[$v['channel_id']]['avg_value']*$this_week)+ceil($kpi_next[$v['id']]['avg_value']*$last_week);
            }
        }

        $returnData = [];
        $arr = [];
        $arr['channel_name'] = ['总计'];
        foreach($channel as $k=>$v){
            $returnData[$k]['channel_name'] = $v['channel_name'];
            $returnData[$k]['cost'] = $cost[$v['id']] ? sprintf('%.2f',$cost[$v['id']]) : '';
            $returnData[$k]['mkz'] = $info[$v['id']]['mkz'];
            $returnData[$k]['valid'] = $info[$v['id']]['valid'];
            $returnData[$k]['validRate'] = $info[$v['id']]['valid'] ? sprintf('%.2f',$info[$v['id']]['valid']/$info[$v['id']]['mkz']*100) : '0%';
            $returnData[$k]['jd'] = $info[$v['id']]['jd'];
            $returnData[$k]['order'] = $info[$v['id']]['order'];
            $returnData[$k]['zd'] = $info[$v['id']]['zd'];
            $returnData[$k]['fact'] = $fact[$v['id']]? sprintf('%.2f',$fact[$v['id']]) : '';
            $returnData[$k]['amount'] = $amount[$v['id']]? sprintf('%.2f',$amount[$v['id']]) : '';
            $returnData[$k]['avg'] = $fact[$v['id']] ? sprintf('%.2f',$fact[$v['id']]/$info[$v['id']]['order']) : '';
            $returnData[$k]['jdRate'] = $info[$v['id']]['jd'] ? sprintf('%.2f',$info[$v['id']]['jd']/$info[$v['id']]['valid']*100) : '0%';//进店率
            $returnData[$k]['succRate'] = $info[$v['id']]['order'] ? sprintf('%.2f',$info[$v['id']]['order']/$info[$v['id']]['jd']*100) : '0%';//成交率
            $returnData[$k]['orderCost'] = $info[$v['id']]['order'] ? sprintf('%.2f',$cost[$v['id']]/$info[$v['id']]['order']) : '';//订单成本
            $returnData[$k]['notice'] = $fact[$v['id']] ? sprintf('%.2f',$cost[$v['id']]/$fact[$v['id']]*100).'%' : '0%';//广告占比  花费/一销实收
            $returnData[$k]['validmubiao'] = $validmubiao[$v['id']] ? $validmubiao[$v['id']] : '';//有效目标
            $returnData[$k]['validmubiaoRate'] = $validmubiao[$v['id']] ? sprintf('%.2f',$info[$v['id']]['valid']/$validmubiao[$v['id']]*100).'%' : '0%';//完成率
            $returnData[$k]['jdmubiao'] = $jdmubiao[$v['id']] ? $jdmubiao[$v['id']] : '';//进店目标
            $returnData[$k]['jdmubiaoRate'] = $jdmubiao[$v['id']] ? sprintf('%.2f',$info[$v['id']]['jd']/$jdmubiao[$v['id']]*100).'%' : '0%';//完成率
            $arr['cost'] += $cost[$v['id']];
            $arr['mkz'] += $info[$v['id']]['mkz'];
            $arr['valid'] += $info[$v['id']]['valid'];
            $arr['validRate'] = '';
            $arr['jd'] += $info[$v['id']]['jd'];
            $arr['order'] += $info[$v['id']]['order'];
            $arr['zd'] += $info[$v['id']]['zd'];
            $arr['fact'] += $fact[$v['id']];
            $arr['amount'] += $amount[$v['id']];
            $arr['avg'] = '';
            $arr['jdRate'] = '';
            $arr['succRate'] = '';
            $arr['orderCost'] = '';
            $arr['notice'] = '';
            $arr['validmubiao'] += $validmubiao[$v['id']];
            $arr['validmubiaoRate'] = '';
            $arr['jdmubiao'] += $jdmubiao[$v['id']];
            $arr['jdmubiaoRate'] = '';
        }
        $arr['avg'] = $arr['fact'] ? sprintf('%.2f',$arr['fact']/$arr['order']) : '';
        $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
        $arr['jdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '0%';
        $arr['succRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '0%';
        $arr['orderCost'] = $arr['order'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '';
        $arr['notice'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['fact']*100).'%' : '0%';//广告占比  花费/一销实收
        $arr['validmubiaoRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['validmubiao']*100).'%' : '0%';
        $arr['jdmubiaoRate'] = $arr['order'] ? sprintf('%.2f',$arr['jd']/$arr['jdmubiao']*100).'%' : '0%';
        array_push($returnData,$arr);
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channel);
        $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);
    }

}