<?php
/**
 * 报表实现类 QQbaby网销每日数据
 *
 * ============================================================================
 * 版权所有 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_staff_data extends Report {

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

    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]);
            $mc = new \app\common\lib\mcInterface();
            $res = $mc->getStaffByIds(array('staff_id'=>$staff_id));

            if($info !== false){
                $staff = $info;
                foreach($staff as $k=>$v){
                    $staff[$k]['staff_id'] = $v['id'];
                    $staff[$k]['staff_name'] = $v['staffname'];
                }
            }
        }

        $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'];
        }

        $sales_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,";//毛客资
        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,";//有效
            $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`,";
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_success!=2 and is_intostore in (2,3) and syjd_day between '$start' and '$end') as `zd`,";//走单
        }else{
            $sql .= "sum(is_valid=1 and dj_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";//进店
            $sql .= "sum(is_success!=2 and order_day between '$start' and '$end') as `order`,";
            $sql .= "sum(is_success=2 and is_intostore in (2,3)  and syjd_day between '$start' and '$end') as `zd`,";//走单
        }
        $sql .= "sum(customer_tel is not null and tel_time between '$start' and '$end') as tel";

        $info = db('c_customerinfo')
            ->where($where)
            ->where('sales_staff_id','in',$sales_staff_id)
            ->group('sales_staff_id')
            ->column($sql,'sales_staff_id');
        //卡扣 调ERP接口
        $staff_name = array_column($staff,'staffname');

        $whereTx['c.is_status'] = 1;
        $whereTx['c.c_from'] = 1;
        $whereTx['c.shop_code'] = $shop_code;
        if($data['customer_type']){
            $where['c.customer_type'] = $data['customer_type'];
        }
        //套系总额
//        $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.sales_staff_id','in',$sales_staff_id)
//            ->group('c.sales_staff_id')
//            ->column('sum(o.order_amount) as total','c.sales_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',$sales_staff_id)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(d.order_fact) as fact','c.sales_staff_id');
        $returnData = [];
        $arr = [];
        $px = [];
        $px['name'] = '总计';
        $total= 0;
        foreach($staff as $k=>$v){
            $arr['name'] = $v['staffname'];
            $arr['mkz'] = $info[$v['id']]['mkz'] ? $info[$v['id']]['mkz'] : '';
            $arr['valid'] = $info[$v['id']]['valid'] ? $info[$v['id']]['valid'] : '';
            $arr['jd'] = $info[$v['id']]['jd'] ? $info[$v['id']]['jd'] : '';
            $arr['order'] = $info[$v['id']]['order'] ? $info[$v['id']]['order'] : '';
            $arr['zd'] = $info[$v['id']]['zd'] ? $info[$v['id']]['zd'] : '';
            $arr['tel'] = $info[$v['id']]['tel'] ? $info[$v['id']]['tel'] : '';
            $arr['kk'] = '';
            $arr['bkk'] = '';
            $arr['bfact'] = '';
            $arr['fact'] = $fact[$v['id']] ? sprintf('%.2f',$fact[$v['id']]) : '';
            $arr['avg'] = $fact[$v['id']]/$info[$v['id']]['order']>0 ? sprintf('%.2f',$fact[$v['id']]/$info[$v['id']]['order']) : '';
            $arr['validRate'] = $info[$v['id']]['valid']/$info[$v['id']]['mkz']>0 ? sprintf('%.2f',$info[$v['id']]['valid']/$info[$v['id']]['mkz']*100).'%' : '';
            $arr['orderRate'] = $info[$v['id']]['order']/$info[$v['id']]['mkz']>0 ? sprintf('%.2f',$info[$v['id']]['order']/$info[$v['id']]['jd']*100).'%' : '';
            $arr['telRate'] = $info[$v['id']]['tel']/$info[$v['id']]['mkz']>0 ? sprintf('%.2f',$info[$v['id']]['tel']/$info[$v['id']]['mkz']*100).'%' : '';
            array_push($returnData,$arr);
            $px['mkz'] += $arr['mkz'];
            $px['valid'] += $arr['valid'];
            $px['jd'] += $arr['jd'];
            $px['order'] += $arr['order'];
            $px['zd'] += $arr['zd'];
            $px['tel'] += $arr['tel'];
            $px['kk'] += $arr['kk'];
            $px['bkk'] += $arr['bkk'];
            $px['bfact'] += $arr['bfact'];
            $px['fact'] += $arr['fact'];
            $px['avg'] = '';
            $px['validRate'] = '';
            $px['orderRate'] = '';
            $px['telRate'] ='';
        }
        $px['avg'] = $px['fact']/$px['order']>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['mkz']>0 ? sprintf('%.2f',$px['order']/$px['jd']*100).'%' : '';
        $px['telRate'] =$px['tel']/$px['mkz']>0 ? sprintf('%.2f',$px['tel']/$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);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        $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);
    }

}