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

class Qqbaby_wx_type_data extends Report {

    private $level=1;
    private $type=3;
    private $code='code1544689337';

    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();


        $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'=>'报表配置有误');
        }

        $staff_id = $data['staff_id'];
        if(!$staff_id){
            $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$shop_code]);
            foreach($staff as $k=>$v){
                $staff[$k]['staff_id'] = $v['id'];
                $staff[$k]['staff_name'] = $v['staffname'];
            }
        }else{
            $info = sx_call('5a18e3fa516a1',['staff_id'=>$staff_id]);
            if($info['code'] == 200){
                $staff = $info['data'];
                foreach($staff as $k=>$v){
                    $staff[$k]['staff_id'] = $v['id'];
                    $staff[$k]['staff_name'] = $v['staffname'];
                }
            }
        }
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id'],'id'=>$data['consultation_type_id']]);

        $start = $data['start'] ? date('Y-m-d', strtotime($data['start'])) : date('Y-m-d 00:00:00');
        $end =  $data['end'] ? date('Y-m-d 23:59:59', strtotime($data['end'])) : date('Y-m-d 23:59:59');


        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = $shop_code;
        if($data['customer_type']){
            $where['customer_type'] = $data['customer_type'];
        }



        $dj_staff_id = array_column($staff,'staff_id');
        $consultation_type_id = $data['consultation_type_id'] ? intval($data['consultation_type_id']) : 0;

        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as mkz,";//毛客资
        $sql .= "sum(is_valid=3 and dj_day between '$start' and '$end') as wx,";//无效
        $sql .= "sum(is_valid=2 and dj_day between '$start' and '$end') as dd,";//待定
        if($consultation_type_id){
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and dj_day between '$start' and '$end') as valid,";//有效
            if($data['consulation_shop_code']){
                $sql .= "sum(consultation_type_id = ".$consultation_type_id." and consulation_shop_code='".$data['consulation_shop_code']."' and is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";//进店
                $sql .= "sum(consultation_type_id = ".$consultation_type_id." and consulation_shop_code='".$data['consulation_shop_code']."'  and is_success!=2 and order_start_time between '$start' and '$end') as `order`";
            }else{
                $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";//进店
                $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_success!=2 and order_start_time between '$start' and '$end') as `order`";
            }

        }else{
            $sql .= "sum(is_valid=1 and dj_day between '$start' and '$end') as valid,";//有效
            if($data['consulation_shop_code']){
                $sql .= "sum(is_intostore in (2,3)  and consulation_shop_code='".$data['consulation_shop_code']."'  and syjd_day between '$start' and '$end') as jd,";//进店
                $sql .= "sum(is_success!=2  and consulation_shop_code='".$data['consulation_shop_code']."'  and order_start_time between '$start' and '$end') as `order`";
            }else{
                $sql .= "sum(is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";//进店
                $sql .= "sum(is_success!=2 and order_start_time between '$start' and '$end') as `order`";
            }
        }

        $info = db('c_customerinfo')
            ->where($where)
            ->where('sales_staff_id','in',$dj_staff_id)
            ->group('consultation_type')
            ->column($sql,'consultation_type');

        $whereTx['c.is_status'] = 1;
        $whereTx['c.c_from'] = 1;
        $whereTx['c.shop_code'] = $shop_code;
        if($data['customer_type']){
            $whereTx['c.customer_type'] = $data['customer_type'];
        }

        if($data['consultation_type_id']){
            $whereTx['c.consultation_type_id'] = $data['consultation_type_id'];
        }
        //套系总额
//        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
//            ->where($whereTx)
//            ->where('o.create_time', 'between time', [$start, $end])
//            ->where('c.dj_staff_id','in',$dj_staff_id)
//            ->group('c.dj_staff_id')
//            ->column('sum(o.order_amount) as total','c.dj_staff_id');

        //营收
        $fact = db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where($whereTx)
            ->where('c.sales_staff_id','in',$dj_staff_id)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.consultation_type')
            ->column('sum(d.order_fact) as fact','c.consultation_type');

        $returnData = [];
        $arr = [];
        $px = [];
        $px['name'] = '总计';
        foreach($consumptionType as $k=>$v){
            $arr['name'] = $v['consumption_name'];
            $arr['mkz'] = $info[$v['consumption_name']]['mkz'] ? $info[$v['consumption_name']]['mkz'] : '';
            $arr['valid'] = $info[$v['consumption_name']]['valid'] ? $info[$v['consumption_name']]['valid'] : '';
            $arr['wx'] = $info[$v['consumption_name']]['wx'] ? $info[$v['consumption_name']]['wx'] : '';
            $arr['dd'] = $info[$v['consumption_name']]['dd'] ? $info[$v['consumption_name']]['dd'] : '';
            $arr['jd'] = $info[$v['consumption_name']]['jd'] ? $info[$v['consumption_name']]['jd'] : '';
            $arr['order'] = $info[$v['consumption_name']]['order'] ? $info[$v['consumption_name']]['order'] : '';
            $arr['fact'] = $fact[$v['consumption_name']] ? sprintf('%.2f',$fact[$v['consumption_name']]) : '';
            $arr['avg'] = $fact[$v['consumption_name']] ? sprintf('%.2f',$fact[$v['consumption_name']]/$info[$v['consumption_name']]['order']) : '';
            $arr['validRate'] = $info[$v['consumption_name']]['valid']/$info[$v['consumption_name']]['mkz']>0 ? sprintf('%.2f',$info[$v['consumption_name']]['valid']/$info[$v['consumption_name']]['mkz']*100).'%' : '';
            $arr['orderRate'] = $info[$v['consumption_name']]['order']/$info[$v['consumption_name']]['jd']>0 ? sprintf('%.2f',$info[$v['consumption_name']]['order']/$info[$v['consumption_name']]['jd']*100).'%' : '';
            $arr['mkzOrderRate'] = $info[$v['consumption_name']]['order']/$info[$v['consumption_name']]['jd']>0 ? sprintf('%.2f',$info[$v['consumption_name']]['order']/$info[$v['consumption_name']]['mkz']*100).'%' : '';
            array_push($returnData,$arr);
            $px['mkz'] += $arr['mkz'];
            $px['valid'] += $arr['valid'];
            $px['wx'] += $arr['wx'];
            $px['dd'] += $arr['dd'];
            $px['jd'] += $arr['jd'];
            $px['order'] += $arr['order'];
            $px['fact'] += $arr['fact'];
            $px['avg'] = '';
            $px['validRate'] = '';
            $px['orderRate'] = '';
        }
        $px['avg'] = $px['fact']>0 ? sprintf('%.2f',$px['fact']/$px['order']) : '';
        $px['validRate'] = $px['valid']/$px['mkz']>0 ? sprintf('%.2f',$px['valid']/$px['mkz']*100).'%' : '';
        $px['orderRate'] = $px['order']/$px['jd']>0 ? sprintf('%.2f',$px['order']/$px['jd']*100).'%' : '';
        $px['mkzOrderRate'] = $px['order']/$px['jd']>0 ? sprintf('%.2f',$px['order']/$px['mkz']*100).'%' : '';
        array_push($returnData,$px);

        // 导出
        if ($data['need'] == 1) {
            $title = ['消费类型','毛客资','有效客资','无效客资','待定客资','进店','成交','实收','均价','客资有效率','订单转化率'];
            $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['code'] = 0;
            $return['msg'] = '';
            $return['data'] = $returnData;
            $return['count'] = count($returnData);
            return json($return);
        }
    }

    public function show(){
        $code = $this->getCode();
        $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();
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);

        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$info['shop_code']]);
        $this->assign('staff', $staff);
        $channel = controller('crm/Customer','lib')->getChannel($info['shop_code']);
        $this->assign('channel', $channel);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        //意向店面
        $shops = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$info['brandclass_id'],'is_op2'=>1]);
        $this->assign('shops', $shops);
        $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', $shop[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}