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

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

    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 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $det = db('crm_s_report_form')->alias('f')->join('crm_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();
        //店
        if($data['shop_code']){
            $shop_code = $data['shop_code'];
        }elseif($det['shop_code']){
            $shop_code = $det['shop_code'];
        }else{
            $shop_code = session('shop_code');
        }

        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'请选择店面');
        }

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        // $where['dj_day'] = ['between time',[$start, $end]];

        $sql = 'is_status = 1 and c_from = 1 and add_shop_code = "'.$shop_code.'" and (dj_day between "'.$start.'" and "'.$end.'") ';

        // 消费类型
        if((int)$data['consultation_type_id']){
            $where['consultation_type_id'] = (int)$data['consultation_type_id'];
            $sql .= ' and consultation_type_id = '.(int)$data['consultation_type_id'];
        }

        // 渠道
        if ($data['customer_channel']) {
            $channelNames = explode(',',$data['customer_channel']);

            $channels = db('crm_s_channel')->where('channel_name', 'in' ,$channelNames)->order("order_sort")->select();
            $channelIds = array_column($channels,'id');
            $where['customer_channel_id'] = ['in',$channelIds];

            $sql .= ' and customer_channel_id in ('.implode(',',$channelIds).')';
        }


        $cityParams = ['type'=>2,'shop_code'=>$shop_code];
        if ($data['province_id']) {
            $cityParams['pid'] = $data['province_id'];
            $city = controller("Customer", "lib")->address($cityParams);

            $where['province_id'] = $data['province_id'];
            $sql .= ' and province_id = "'.$data['province_id'].'"';
        } else {
            //店下所有市
            $city = controller("Customer", "lib")->address($cityParams);
        }

        $search_key = $data['search_key'];
        switch($search_key){
            case 'tel':
                $sql .= ' and customer_tel is not null';
                $osql = 'customer_tel is not null';
                break;
            case 'wx':
                $sql .= ' and customer_wechat is not null';
                $osql = 'customer_wechat is not null';
                break;
            case 'qq':
                $sql .= ' and customer_qq is not null';
                $osql = 'customer_qq is not null';
                break;
            case 'tel-wx':
                $sql .= ' and customer_tel is not null and customer_wechat is not null';
                $osql = 'customer_tel is not null and customer_wechat is not null';
                break;
            case 'nottel':
                $sql .= ' and customer_tel is null';
                $osql = 'customer_tel is null';
                break;
            case 'notwx':
                $sql .= ' and customer_wechat is null';
                $osql = 'customer_wechat is null';
                break;
            case 'onlytel':
                $sql .= ' and customer_tel is not null and customer_wechat is null and customer_qq is null';
                $osql = 'customer_tel is not null and customer_wechat is null and customer_qq is null';
                break;
            case 'onlywx':
                $sql .= ' and customer_wechat is not null and customer_tel is null and customer_qq is null';
                $osql = 'customer_wechat is not null and customer_tel is null and customer_qq is null';
                break;
            case 'onlyqq':
                $sql .= ' and customer_qq is not null and customer_wechat is null and customer_tel is null';
                $osql = 'customer_qq is not null and customer_wechat is null and customer_tel is null';
                break;
        }


        $group = 'city';
        $cKey = 'city';

        $allCus = 'select
            city,
            COUNT(1) AS all_num,
            SUM(is_valid = 1 or is_valid = 5) AS valid_num,
            SUM(is_valid = 2) AS dd_num,
            SUM(is_valid = 3 or is_valid = 4) AS invalid_num,
            SUM(sign_name = "已预约") AS rd_num
            from crm_c_customerinfo
            WHERE '.$sql.'
            GROUP BY '.$group.'
            ';

        $allNum = db()->query($allCus);
        $num = [];
        foreach($allNum as $k => $v){
            if(!$v['city']){
                $v['city'] = '未填写城市';
                $num['未填写城市'] = $v;
            }else{
                $num[$v['city']] = $v;
            }
        }

        // 成交量  (实收金额大于等于500)
        $orderNum = db('crm_c_customerinfo')->alias('c')
            ->join('c_customerorder erp_order', 'erp_order.crm_customer_number=c.customer_number')
            ->where($where)
            ->where($osql)
            ->where('erp_order.orderId is not null')
            ->where('erp_order.blankoutannal','<>',1)
            // ->where('erp_order.yixiaoshishou','>',0)
            ->where('erp_order.payment_money','>',0)
            ->where('erp_order.crm_order_type',1)
            ->where('erp_order.targetdate', 'between', [date('Ymd',strtotime($start)), date('Ymd',strtotime($end))])
            ->group($group)
            ->column('count(c.id) as num', $cKey);




        // 营收额（订单总额）
        /*
        $totalMoney = db('crm_c_customerinfo')->alias('c')
            ->join('c_customerorder erp_order','erp_order.crm_customer_number = c.customer_number')
            ->where($where)
            ->where($osql)
            ->group($group)
            ->column('sum(erp_order.total_money) as total_money', $cKey);
        */

        // 实收（实收金额总和）
        $paymentMoney = db('crm_c_customerinfo')->alias('c')
            ->join('c_customerorder erp_order','erp_order.crm_customer_number = c.customer_number')
            ->join('c_paymentcontent pay','erp_order.orderId = pay.orderId')
            ->where($where)
            ->where($osql)
            ->group($group)
             ->where('erp_order.crm_order_type',1)
            ->where('pay.shop_code',$shop_code)
            ->where('pay.paymentdate', 'between', [date('Ymd',strtotime($start)), date('Ymd',strtotime($end))])
            ->where('pay.suoshu', 'in', ['前期款','前期补款'])
            ->column('sum(erp_order.yixiaoshishou) as payment_money', $cKey);

        $returnData = [];

        $all = [];
        $all['city'] = '总计';

        foreach ($city as $k => $v) {

            $returnData[$k]['city'] = $v['name'];

            $returnData[$k]['lrCustomer'] = $num[$v['name']]['all_num'] ? $num[$v['name']]['all_num'] : 0;
            $returnData[$k]['validCustomer'] = $num[$v['name']]['valid_num'] ? $num[$v['name']]['valid_num'] : 0;
            $returnData[$k]['invalidCustomer'] = $num[$v['name']]['invalid'] ? $num[$v['name']]['invalid'] : 0;
            $returnData[$k]['dd'] = $num[$v['name']]['dd_num'] ? $num[$v['name']]['dd_num'] : 0;
            $returnData[$k]['rdNum'] = $num[$v['name']]['rd_num'] ? $num[$v['name']]['rd_num'] : 0;

            $returnData[$k]['orderNum'] = $orderNum[$v['name']] ? $orderNum[$v['name']] : 0;
            //$returnData[$k]['totalMoney'] = $totalMoney[$v['name']] ? $totalMoney[$v['name']] : '0.00';//营业总额
            $returnData[$k]['paymentMoney'] = $paymentMoney[$v['name']] ? $paymentMoney[$v['name']] : '0.00';//实收

            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$k]['validRate'] = (sprintf('%.2f', $returnData[$k]['validCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            //无效率 （ 无效客资 / 毛客资）
            $returnData[$k]['invalidRate'] = (sprintf('%.2f', $returnData[$k]['invalidCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            //待定率 （ 待定客资 / 毛客资）
            $returnData[$k]['ddRate'] = (sprintf('%.2f', $returnData[$k]['dd'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            //毛客资入店率
            $returnData[$k]['rdRate'] = (sprintf('%.2f', $returnData[$k]['rdNum'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            //有效客资入店率
            $returnData[$k]['validRdRate'] = (sprintf('%.2f', $returnData[$k]['rdNum'] / $returnData[$k]['validCustomer'] * 100)) . '%';
            //入店成交率(成交/入店)
            $returnData[$k]['rdOrderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['rdNum'] * 100)) . '%';
            //毛客资成交率(成交/总客)
            $returnData[$k]['orderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // 有效客资成交率（ 新单 / 有效客资 ）
            $returnData[$k]['validorderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['validCustomer'] * 100)) . '%';
            //营业额
            //$returnData[$k]['totalMoney'] = $totalMoney[$v['id']] ? sprintf('%.2f',$totalMoney[$v['id']]) : '0.00';
            //已收金额
            $returnData[$k]['paymentMoney'] = $paymentMoney[$v['id']] ? sprintf('%.2f',$paymentMoney[$v['id']]) : '0.00';


            $all['lrCustomer']  += $returnData[$k]['lrCustomer'];    //录入总计
            $all['validCustomer'] += $returnData[$k]['validCustomer'];     //有效总计
            $all['invalidCustomer'] += $returnData[$k]['invalidCustomer']; //无效总计
            $all['dd'] += $returnData[$k]['dd'];   //待定总计
            $all['rdNum']    += $returnData[$k]['rdNum'];    //入店量
            $all['orderNum'] += $returnData[$k]['orderNum']; //订单数总计
            //$all['totalMoney']   += $returnData[$k]['totalMoney']; //营业额总计
            $all['paymentMoney']  += $returnData[$k]['paymentMoney']; //实收金额总计

        }

        // 有效率（ 有效获取 / 毛客资 ）
        $all['validRate'] = (sprintf('%.2f', $all['validCustomer'] / $all['lrCustomer'] * 100)) . '%';
        //无效率 （ 无效客资 / 毛客资）
        $all['invalidRate'] = (sprintf('%.2f', $all['invalidCustomer'] / $all['lrCustomer'] * 100)) . '%';
        //待定率 （ 待定客资 / 毛客资）
        $all['ddRate'] = (sprintf('%.2f', $all['dd'] / $all['lrCustomer'] * 100)) . '%';
        //毛客资入店率
        $all['rdRate'] = (sprintf('%.2f', $all['rdNum'] / $all['lrCustomer'] * 100)) . '%';
        //有效客资入店率
        $all['validRdRate'] = (sprintf('%.2f', $all['rdNum'] / $all['validCustomer'] * 100)) . '%';
        //入店成交率(成交/入店)
        $all['rdOrderRate'] = (sprintf('%.2f', $all['orderNum'] / $all['rdNum'] * 100)) . '%';
        //毛客资成交率(成交/总客)
        $all['orderRate'] = (sprintf('%.2f', $all['orderNum'] / $all['lrCustomer'] * 100)) . '%';
        // 有效客资成交率（ 新单 / 有效客资 ）
        $all['validorderRate'] = (sprintf('%.2f', $all['orderNum'] / $all['validCustomer'] * 100)) . '%';

        //$all['totalMoney']   = $all['totalMoney'] ? $all['totalMoney'] : '0.00'; //营业额总计
        $all['paymentMoney'] = $all['paymentMoney'] ? $all['paymentMoney'] : '0.00'; //已收金额总计
        array_push($returnData,$all);

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

        return json($return);

    }

    public function show(){
        /*
        $did = strtolower(input('param.did'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_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();*/
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id','left')->where('f.code',$menu_code)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();

        $brandclass_id = session('brandclass_id');
        $brandclass = session('brandclass');
        $shop_code = session('shop_code');

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$brandclass_id]);
        $this->assign("consumptionType", $consumptionType);

        //来源渠道
        //$channel = getChannelArray23($shop_code);
        $channel = getChannelJson($shop_code);
        $this->assign("channel", json_encode($channel));

        //店
        $mcInterface = new mcInterface();
        $shop = $mcInterface->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
        $this->assign("shop", $shop);
        $this->assign("shop_code", $info['shop_code']?$info['shop_code']:session('shop_code'));

        //省份
        $province = controller("Customer", "lib")->address(['type'=>1,'shop_code'=>$shop_code]);
        $this->assign("province", $province);

        //报表名称
        $code = $this->getCode();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('crm_s_report_form')->where('code', $code)->value('report_name');
        $this->assign('title', $title);

        //表格隐藏列
        $this->assign('hiddenColumns',explode('|',cookie('report_cd_city_columns_hidden')));

        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}