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

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

    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).')';
        }


        if ($data['group_id']) {
            $staffGroup = [['id'=>$data['group_id'],'group_name'=>$data['group_name']]];
        } else {
            //店下所有小组
            $mcInterface = new mcInterface();
            $staffGroup = $mcInterface->getGroupInfo(['shop_code'=>$shop_code]);
        }

        $group = 'sales_group_name';
        $cKey = 'sales_group_name';

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

        $sql1 = $allCus;
        $allNum = db()->query($allCus);
        $num = [];
        foreach($allNum as $k => $v){
            $num[$v['sales_group_name']] = $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('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('c.dj_day', 'between time', [$start, $end])
            ->where('erp_order.targetdate', 'between', [date('Ymd',strtotime($start)), date('Ymd',strtotime($end))])
            ->group($group)
            ->column('count(c.id) as num', $cKey);
        $sql2 = db()->getLastSql();

        // 营收额（订单总额）
        $totalMoney = db('crm_c_customerinfo')->alias('c')
            ->join('c_customerorder erp_order','erp_order.crm_customer_number = c.customer_number')
            ->where($where)
            ->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('sum(erp_order.bargain_money) as total_money', $cKey);

        $sql3 = db()->getLastSql();

        // 实际收入（实收金额总和）
        $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('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', ['前期款','前期补款'])
            ->group($group)
            ->column('sum(erp_order.yixiaoshishou) as payment_money', $cKey);
        $sql4 = db()->getLastSql();

        $returnData = [];
        $totalMoneyNum = 0;
        $paymentMoneyNum = 0;
        $all = [];
        $all['group_id'] = '';
        $all['group_name'] = '总计';

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

            $returnData[$k]['group_id'] = $v['id'];
            $returnData[$k]['group_name'] = $v['group_name'];

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

            // 有效率（ 有效获取 / 毛客资 ）
            $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['group_name']] ? $totalMoney[$v['group_name']] : '0.00';
            //实收
            $returnData[$k]['paymentMoney'] = $paymentMoney[$v['group_name']] ? $paymentMoney[$v['group_name']] : '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']; //订单数总计
            $totalMoneyNum   += $returnData[$k]['totalMoney']; //营业额总计
            $paymentMoneyNum += $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']   = $totalMoneyNum ? $totalMoneyNum : '0.00'; //营业额总计
        $all['paymentMoney'] = $paymentMoneyNum ? $paymentMoneyNum : '0.00'; //已收金额总计
        array_push($returnData,$all);

        if($data['need'] == 1){
            $title = ['ID','小组','总客资','有效量','无效量','待定量','入店量','成交量','有效率','无效率','待定率','毛客资入店率','有效客资入店率','入店成交率','毛客资成交率','有效客资成交率','营业额','已收金额'];

            $code = $this->getCode();
            $name = db('crm_s_report_form')->where('code', $code)->value('report_name');
            $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
            $file = $shopInfo[0]['shop_name'].'-'.$name.'.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        }


        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['sql4'] = $sql4;

        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 = 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']:$shop_code);

        //小组
        $group = $mcInterface->getGroupInfo(['shop_code'=>$shop_code]);
        $this->assign("group", $group);

        //报表名称
        $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_groupstaff_columns_hidden')));

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

}