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

class Ds_region_ld extends Report {

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

    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']));
//        $shop_code = session('shop_code');

        $id = db('s_report_form')->where('code', $this->getCode())->value('id');
        $det = db('s_report_detail')->where('form_id',$id)->field('shop_code,brandclass_id')->find();
        $shop_code = $det['shop_code'] ? $det['shop_code'] :session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['add_shop_code'] = $shop_code;

        $whereC['c.is_status'] = 1;
        $whereC['c.c_from'] = 1;
        $whereC['c.customer_type'] = 1;
        $whereC['c.add_shop_code'] = $shop_code;
        if($data['consultation_type_id']){
            $whereT['consultation_type_id'] = $data['consultation_type_id'];
        }
        if ($data['channel']) {
            if ($data['province_id']) {
                $province_id = intval($data['province_id']);
                $where['province_id'] = $province_id;
                $whereC['c.province_id'] = $province_id;
                // 城市列表
                $city = db('s_shop_address')->where('shop_code', $shop_code)->where('pid', $province_id)->where('type', 2)->select();
                if ($data['city_id']) {
                    $city_id = intval($data['city_id']);
                    $where['city_id'] = $city_id;
                    $whereC['c.city_id'] = $city_id;
                    // 城市列表
                    $city = [
                        [
                            'id' => $city_id,
                            'name' => $data['city_name'] ? $data['city_name'] : '',
                        ]
                    ];
                }
            } else {
                // 城市列表
                $city = db('s_shop_address')->where('shop_code', $shop_code)->where('type', 2)->select();
            }
            $group = 'city_id';
            $field = 'city';
            $groupC = 'c.city_id';
            $fieldC = 'c.city';
        } else {
            $city = controller("Customer", "lib")->address(['type' => 1]);//省
            $group = 'province_id';
            $field = 'province';
            $groupC = 'c.province_id';
            $fieldC = 'c.province';
        }
        $notIn = array_column($city,'id');
        if ($data['channel']) {
            // 花费
            $channelCost = db('s_channel_cost')->alias('c')
                ->where('c.cost_date', 'between time', [$start, $end])
                ->where('c.shop_code', $shop_code)
                ->group('city_id')
                ->column('sum(c.cost) as cost,c.city_name', 'c.city_id');
        } else {
            // 花费
            $channelCost = db('s_channel_cost')->alias('c')
                ->where('c.cost_date', 'between time', [$start, $end])
                ->where('c.shop_code', $shop_code)
                ->group('province_id')
                ->column('sum(c.cost) as cost,c.province_name', 'c.province_id');
        }

        // 录入客资量
        $allCustomer = db('c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 有效客资量
        $validCustomer = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_valid', 1)
            ->where('yx_day', 'between time', [$start, $end])
//            ->field('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
//        echo db()->getLastSql();die;
        // 待定客资量
        $ddCustomer = db('c_customerinfo')
            ->where($where)
            ->where('is_valid', 2)
            ->where('yx_day', 'between time', [$start, $end])
//            ->field('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 总手机  手机号不为空的客资总数（按录入时间计算）
        $allTel = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_valid', 1)
            ->where('customer_tel', '<>', '')
            ->where('yx_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 进店数量
        $intoNum = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_intostore', 'in', '2,3')
            ->where('syjd_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 有效订单 数

        $orderNum = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 营收（实际收入  不区分有效无效）
        $factMoney = db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where($whereC)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group($groupC)
            ->column('sum(d.order_fact) as fact_money,'.$fieldC, $groupC);
        // 套系均值（有效单套系应收款均值）
        $order_amount_avg = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereC)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group($group)
            ->column('sum(o.order_amount) as totalpay_money,'.$fieldC,$groupC);
        $returnData = [];
        $arr = [];
        $arr['name'] = '总计';
        foreach ($city as $k => $v) {
            $returnData[$k]['name'] = $v['name'];
            $returnData[$k]['channelCost'] = $channelCost[$v['id']]['cost'] ? sprintf('%.2f', $channelCost[$v['id']]['cost']) : 0;
            $returnData[$k]['lrCustomer'] = $allCustomer[$v['id']]['num'] ? $allCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['invCustomer'] = $validCustomer[$v['id']]['num'] ? $validCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['dd'] = $ddCustomer[$v['id']]['num'] ? $ddCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['allTel'] = $allTel[$v['id']]['num'] ? $allTel[$v['id']]['num'] : 0;
            $returnData[$k]['intoNum'] = $intoNum[$v['id']]['num'] ? $intoNum[$v['id']]['num'] : 0;
            $returnData[$k]['orderNum'] = $orderNum[$v['id']]['num'] ? $orderNum[$v['id']]['num'] : 0;
            $returnData[$k]['factMoney'] = $factMoney[$v['id']]['fact_money'] ? sprintf('%.2f',$factMoney[$v['id']]['fact_money']) : 0;
            $returnData[$k]['totalAmount'] = $order_amount_avg[$v['id']]['totalpay_money'] ? sprintf('%.2f',$order_amount_avg[$v['id']]['totalpay_money']) : 0;
            $returnData[$k]['orderAmountAvg'] = $order_amount_avg[$v['id']]['totalpay_money'] ?
                sprintf('%.2f', $order_amount_avg[$v['id']]['totalpay_money']/$returnData[$k]['orderNum']) : 0;
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$k]['invRate'] = (sprintf('%.2f', $returnData[$k]['invCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // 进店率（ 实际进店 / 有效获取 ）
            $returnData[$k]['intoRate'] = (sprintf('%.2f', $returnData[$k]['intoNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$k]['orderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['intoNum'] * 100)) . '%';
            // 转化率（ 有效新单 / 有效获取 ）
            $returnData[$k]['changeRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 毛客资成本
            $returnData[$k]['customerCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['lrCustomer']);
            // 有效获取成本
            $returnData[$k]['invCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['invCustomer']);
            // 新单成本
            $returnData[$k]['orderCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['orderNum']);
            // ROI（实收：花费）(营收)
            $returnData[$k]['ROI'] = sprintf('%.2f',intval($returnData[$k]['factMoney'])/intval
                    ($returnData[$k]['channelCost'])).':1';

            $arr['channelCost'] += $channelCost[$v['id']]['cost'];   // 花费总计
            $arr['lrCustomer']  += $allCustomer[$v['id']]['num'];    // 录入总计
            $arr['invCustomer'] += $validCustomer[$v['id']]['num'];   // 有效总计
            $arr['dd'] += $ddCustomer[$v['id']]['num'];   // 有效总计
            $arr['allTel']      += $allTel[$v['id']]['num'];        // 总手机总计
            $arr['intoNum']     += $intoNum[$v['id']]['num'];       // 进店总计
            $arr['orderNum']    += $orderNum[$v['id']]['num'];      // 订单总计
            $arr['factMoney']   += $factMoney[$v['id']]['fact_money']; // 营收总计
            $arr['totalAmount']   += $order_amount_avg[$v['id']]['totalpay_money']; // 营收总计

        }
        //无省市客资
        $no['name'] = '其它';
        $no['channelCost'] = '';
        if($where['province_id'])unset($where['province_id']);
        if($where['city_id'])unset($where['city_id']);
        $sql = ' '.$group.' not in('.implode(',',$notIn).') or '.$group.' is null ';
        // 录入客资量
        $no['lrCustomer'] = db('c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->where($sql)
            ->count();
        $no['invCustomer'] = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_valid', 1)
            ->where('yx_day', 'between time', [$start, $end])
            ->where($sql)
            ->count();
        $no['dd'] = db('c_customerinfo')
            ->where($where)
            ->where('is_valid', 2)
            ->where('yx_day', 'between time', [$start, $end])
            ->where($sql)
            ->count();
        $no['allTel'] = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_valid', 1)
            ->where('customer_tel', '<>', '')
            ->where('yx_day', 'between time', [$start, $end])
            ->where($sql)
            ->count();
        $no['intoNum'] = db('c_customerinfo')
            ->where($where)
            ->where('is_intostore', 'in', '2,3')
            ->where('syjd_day', 'between time', [$start, $end])
            ->where($sql)
            ->count();
        // 有效订单 数
        $no['orderNum'] = db('c_customerinfo')
            ->where($where)
            ->where($whereT)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
            ->where($sql)
            ->count();
        // 营收（实际收入  不区分有效无效）
        $no['factMoney'] = db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where($whereC)
            ->where('c.'.$group.' is null or c.'.$group.'=0')
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->sum('d.order_fact');
        $no['factMoney'] = sprintf('%.2f',$no['factMoney']);
        // 套系均值（有效单套系应收款均值）
        $no['totalAmount'] = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereC)
            ->where('c.is_success', 1)
            ->where('c.'.$group.' is null or c.'.$group.'=0')
            ->where('c.order_day', 'between time', [$start, $end])
            ->sum('o.order_amount');

        $no['orderAmountAvg'] = sprintf('%.2f', $no['totalAmount'] / $no['orderNum']);
        $no['invRate'] = sprintf('%.2f', $no['invCustomer'] / $no['lrCustomer'] * 100) . '%';
        $no['intoRate'] = (sprintf('%.2f', $no['intoNum'] / $no['invCustomer'] * 100)) . '%';
        $no['orderRate'] = (sprintf('%.2f', $no['orderNum'] / $no['intoNum'] * 100)) . '%';
        $no['invRate'] = (sprintf('%.2f', $no['invCustomer'] / $no['lrCustomer'] * 100)) . '%';
        $no['changeRate'] = (sprintf('%.2f', $no['orderNum'] / $no['invCustomer'] * 100)) . '%';
        $no['customerCost'] = (sprintf('%.2f', $no['channelCost'] / $no['lrCustomer']));
        $no['invCost'] = (sprintf('%.2f', $no['channelCost'] / $no['invCustomer']));
        $no['orderCost'] = (sprintf('%.2f', $no['channelCost'] / $no['orderNum']));
        $no['ROI'] = sprintf('%.2f',intval($no['factMoney'])/intval($no['channelCost'])).':1';
        array_push($returnData,$no);
        //有城市的+无城市的
        $arr['channelCost'] += floatval($no['channelCost']);
        $arr['lrCustomer'] += $no['lrCustomer'];
        $arr['invCustomer'] += $no['invCustomer'];
        $arr['dd'] += $no['dd'];
        $arr['allTel'] += $no['allTel'];
        $arr['intoNum'] += $no['intoNum'];
        $arr['orderNum'] += $no['orderNum'];
        $arr['factMoney'] += floatval($no['factMoney']);
        $arr['totalAmount']   = sprintf('%.2f',$arr['totalAmount']+$no['totalAmount']);
        $arr['orderAmountAvg'] = sprintf('%.2f', $arr['totalAmount']/ $arr['orderNum']);
        $arr['invRate'] = sprintf('%.2f', $arr['invCustomer'] / $arr['lrCustomer'] * 100) . '%';
        $arr['intoRate'] = (sprintf('%.2f', $arr['intoNum'] / $arr['invCustomer'] * 100)) . '%';
        $arr['orderRate'] = (sprintf('%.2f', $arr['orderNum'] / $arr['intoNum'] * 100)) . '%';
        $arr['invRate'] = (sprintf('%.2f', $arr['invCustomer'] / $arr['lrCustomer'] * 100)) . '%';
        $arr['changeRate'] = (sprintf('%.2f', $arr['orderNum'] / $arr['invCustomer'] * 100)) . '%';
        $arr['customerCost'] = (sprintf('%.2f', $arr['channelCost'] / $arr['lrCustomer']));
        $arr['invCost'] = (sprintf('%.2f', $arr['channelCost'] / $arr['invCustomer']));
        $arr['orderCost'] = (sprintf('%.2f', $arr['channelCost'] / $arr['orderNum']));
        $arr['ROI'] = sprintf('%.2f',intval($arr['factMoney'])/intval($arr['channelCost'])).':1';
        array_push($returnData,$arr);
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($city);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array('地域', '花费', '毛客资', '有效获取','待定客资', '总手机', '邀约进店', '新单', '一销营收','一销套系', '一销套系均值', '有效率', '进店率', '成交率', '转化率', '毛客资成本', '有效获取成本', '新单成本', 'ROI');
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $file = session('department_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();
        $city = db('s_shop_address')->where('shop_code',$info['shop_code'])->where('type',2)->select();
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);

        $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');
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}