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

class Xa_staff_data extends Report {

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

    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);
        $title = ['姓名', '头像', '手机','订单','实收'];
        $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'];
        $shop_code = session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }

        $groupList = db('c_staff_group')->where('shop_code', $shop_code)->select();
        $staff = db('c_staff_group_relation r')->join('c_staff_group g','r.group_id=g.id')->where('g.shop_code',$shop_code)->select();
        $sales_staff_id = array_column($staff,'staff_id');

        $gid = $data['group_id'];
        if($gid){
            $staff = db('c_staff_group_relation')->where('group_id',$gid)->select();
        }
        $ids = [];
        foreach($staff as $k=>$v){
            if(empty($v['staff_name'])){
                $ids[] = $v['staff_id'];
                unset($staff[$k]);
            }
        }
        if(!empty($ids)){
            $info = sx_call('5a18e3fa516a1',['staff_id'=>$ids]);
            if($info['code'] == 200){
                $data1 = $info['data'];
                foreach($data1 as $k=>$v){
                    $staff[] = [
                        'group_id'=>$gid,
                        'staff_id'=>$v['id'],
                        'staff_name'=>$v['staffname'],
                    ];
                }
            }
        }

        // 时间区域
        if($data['time'] == 'today'){
            $time = getdateArea('today');
        }elseif($data['time'] == 'week'){
            $time = getdateArea('week');
        }elseif($data['time'] == 'month'){
            $time = getdateArea('month');
        }else{
            $time = getdateArea('today');
        }

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;

        $staffCus = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.sales_staff_id', 'in', $sales_staff_id)
            ->where('c.shop_code', 'in', $shop_code)
            ->whereTime('c.dj_day', 'between', $time)
            ->group('c.sales_staff_id')
            ->column('count(c.id) as num', 'c.sales_staff_id');

        $staffOrder = db('c_customerinfo')->alias('c')->join('c_customer_from r', 'c.id=r.cid')
            ->where($where)
            ->where('c.sales_staff_id', 'in', $sales_staff_id)
            ->where('c.shop_code', 'in', $shop_code)
            ->where('c.is_success', 1)
            ->whereTime('c.order_day', 'between', $time)
            ->group('c.sales_staff_id')
            ->order('num desc')
            ->column('count(c.id) as num', 'c.sales_staff_id');
        $queryOrder['order'] = db()->getLastSql();

        $money =  db('c_customerinfo')->alias('c')
            ->join('c_customer_from r', 'c.id=r.cid')
            ->join('c_customer_order o','o.customer_id=c.id')
            ->where($where)
            ->where('c.sales_staff_id', 'in', $sales_staff_id)
            ->where('c.shop_code', 'in', $shop_code)
            ->where('c.is_success', 1)
            ->whereTime('c.order_day', 'between', $time)
            ->group('c.sales_staff_id')
            ->order('num desc')
            // ->column('sum(o.order_fact+o.earnest_money) as num', 'c.sales_staff_id');
            ->column('sum(o.order_fact) as num', 'c.sales_staff_id');

        $returnData = [];
        $arr = [];
        $px = [];
        $px['name'] = '总计';
        $total= 0;

        foreach($staff as $k=>$v){
            if($v['staff_name']){
                $arr['name'] = $v['staff_name'];
            }else{
                $sStaffinfo = getStaffInfoById($v['staff_id']);
                $arr['name'] = $sStaffinfo['staff_name'] ? $sStaffinfo['staff_name'] : $sStaffinfo['staffname'];
            }
            if(file_exists(ROOT_PATH."public/upload/pic/".$v['staff_id'].".jpg")){
                $arr['photo'] = "<img width='35px' src='/upload/pic/".$v['staff_id'].'.jpg'."'>";
            }else{
                $arr['photo'] = "<img width='35px' src='/img/user_tt_b.jpg"."'>";
            }
            //$arr['tel'] = $v['telephone'] ? $v['telephone'] : '&nbsp;';
            $arr['cus'] = $staffCus[$v['staff_id']];
            $arr['order'] = $staffOrder[$v['staff_id']] ? $staffOrder[$v['staff_id']] : '&nbsp;';
            $arr['orderRate'] = $staffOrder[$v['staff_id']] ? sprintf('%.2f',$staffOrder[$v['staff_id']]/$staffCus[$v['staff_id']]*100).'%' : '0%';
            $arr['money'] = $money[$v['staff_id']] ? sprintf('%.2f',$money[$v['staff_id']]): '&nbsp;';
            array_push($returnData,$arr);

            $px['photo'] = '&nbsp;';
            //$px['tel'] = '&nbsp;';
            $px['cus'] += $staffCus[$v['staff_id']];
            $px['order'] += $staffOrder[$v['staff_id']];
            $px['money'] += sprintf('%.2f',$money[$v['staff_id']]);
        }
        $px['orderRate'] = $px['order'] ? sprintf('%.2f',$px['order']/$px['cus']*100).'%' : '0%';
        $sort = 'SORT_DESC';
        $returnData = my_sort($returnData,'order',$sort);
        array_push($returnData,$px);
        // 导出
        if ($data['need'] == 1) {
            $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 {
            //所有订单
            $all = db('c_customerinfo')->where('shop_code',$shop_code) ->where('sales_staff_id','in',$sales_staff_id)->where('is_status',1)->where('c_from',1)->whereTime('order_day',$time)->where('is_success',1)->count('id');
            //各小组人员订单
            $gOrder = db('c_customerinfo')->alias('c')->join('c_customer_from r', 'c.id=r.cid')
                ->where('c.is_status',1)
                ->where('c.c_from',1)
                ->where('c.shop_code', 'in', $shop_code)
                ->where('c.is_success', 1)
                ->whereTime('c.order_day', $time)
                ->group('c.sales_staff_id')
                ->order('num desc')
                ->column('count(c.id) as num', 'c.sales_staff_id');
            $groupStaff = db('c_staff_group_relation r')->join('c_staff_group g','r.group_id=g.id')
                ->where('g.shop_code',$shop_code)
                ->select();
            $order = [];
            $gInfo = [];
            foreach($groupStaff as $k=>$v){
                $order[$v['group_id']] += $gOrder[$v['staff_id']];
            }
            foreach($groupList as $k=>$v){
                $gInfo[$v['id']] = $v['group_name'].'('.$order[$v['id']].')';
            }
            /*foreach($gOrder as $k=>$v){
                if($v['sales_group_id'] > 0){
                    $gInfo[$v['sales_group_id']] = $v['sales_group_name'].'('.$v['num'].')';
                }
            }*/
            $gInfo[0] = '全部('.$all.')';
            $return['code'] = 200;
            $return['msg'] = '';
            $return['count'] = count($returnData);

            $return['data'] = $returnData;
            $return['gOrder'] = $gInfo;
            $return['sql'] = $queryOrder;

            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_code = $info['shop_code'];
        if (!$shop_code) {
            $shop_code = session('shop_code');
        }
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
        $groupList = db('c_staff_group')->where('shop_code', $shop_code)->select();

        $staff = db('c_staff_group_relation r')->join('c_staff_group g','r.group_id=g.id')->where('g.shop_code',$shop_code)->select();

        // 时间区域
        // $time = 'month';
        $time = getdateArea('month');

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;

        $sales_staff_id = array_column($staff,'staff_id');

        $staffCus = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.sales_staff_id', 'in', $sales_staff_id)
            ->where('c.shop_code', 'in', $shop_code)
            ->whereTime('c.dj_day', 'between', $time)
            ->group('c.sales_staff_id')
            ->column('count(c.id) as cusNum', 'c.sales_staff_id');

        $staffOrder = db('c_customerinfo')->alias('c')
            ->join('c_customer_from r', 'c.id=r.cid')
            ->where($where)
            ->where('c.sales_staff_id', 'in', $sales_staff_id)
            ->where('c.shop_code', 'in', $shop_code)
            ->where('c.is_success',1)
            ->whereTime('c.order_day', 'between', $time)
            ->group('c.sales_staff_id')
            ->order('num desc')
            ->column('count(c.id) as num', 'c.sales_staff_id');

        $money =  db('c_customerinfo')->alias('c')
            ->join('c_customer_from r', 'c.id=r.cid')
            // ->join('c_customer_order o','o.customer_id=c.id')
            ->where($where)
            ->where('c.sales_staff_id', 'in', $sales_staff_id)
            ->where('c.shop_code', 'in', $shop_code)
            ->where('c.is_success',1)
            ->whereTime('c.order_day', 'between', $time)
            ->group('c.sales_staff_id')
            ->order('num desc')
            ->column('sum(c.fact_money) as num', 'c.sales_staff_id');
        $returnData = [];
        $arr = [];
        $px = [];
        $px['name'] = '总计';
        $total= 0;
        foreach($staff as $k=>$v){
            if($v['staff_name']){
                $arr['name'] = $v['staff_name'];
            }else{
                $sStaffinfo = getStaffInfoById($v['staff_id']);
                $arr['name'] = $sStaffinfo['staff_name'] ? $sStaffinfo['staff_name'] : $sStaffinfo['staffname'];
            }

            if(file_exists(ROOT_PATH."public/upload/pic/".$v['staff_id'].".jpg")){
                $arr['photo'] = "<img width='35px' src='/upload/pic/".$v['staff_id'].'.jpg'."'>";
            }else{
                $arr['photo'] = "<img width='35px' src='/img/user_tt_b.jpg"."'>";
            }
            // $arr['tel'] = $v['telephone'] ? $v['telephone'] : '&nbsp;';
            $arr['cus'] = $staffCus[$v['staff_id']];
            $arr['order'] = $staffOrder[$v['staff_id']] ? $staffOrder[$v['staff_id']] : '&nbsp;';
            $arr['orderRate'] = $staffOrder[$v['staff_id']] ? sprintf('%.2f',$staffOrder[$v['staff_id']]/$staffCus[$v['staff_id']]*100).'%' : '0%';
            $arr['money'] = $money[$v['staff_id']] ? sprintf('%.2f',$money[$v['staff_id']]): '&nbsp;';
            array_push($returnData,$arr);
            $px['photo'] = '&nbsp;';
            // $px['tel'] = '&nbsp;';
            $px['cus'] += $staffCus[$v['staff_id']];
            $px['order'] += $arr['order'];
            $px['money'] += $arr['money'];
        }
        $px['orderRate'] = $px['order'] ? sprintf('%.2f',$px['order']/$px['cus']*100).'%' : '0%';
        $sort = 'SORT_DESC';
        $returnData = my_sort($returnData,'order',$sort);
        array_push($returnData,$px);
        $this->assign('return',$returnData);
        //所有订单
        /*$all = db('c_customerinfo')->where('shop_code',$info['shop_code'])
            ->where('sales_staff_id','in',$sales_staff_id)
            ->where('is_status',1)
            ->where('c_from',1)
            ->whereTime('order_day',$time)
            ->where('is_success',1)
            ->count('id');*/
        //各小组订单

        $gOrder = db('c_customerinfo')->alias('c')->join('c_customer_from r', 'c.id=r.cid')
            ->where('c.is_status',1)
            ->where('c.c_from',1)
            ->where('c.shop_code', 'in', $shop_code)
            ->where('c.is_success', 1)
            ->whereTime('c.order_day', $time)
            ->group('c.sales_staff_id')
            ->order('num desc')
            ->column('count(c.id) as num', 'c.sales_staff_id');
        $groupStaff = db('c_staff_group_relation r')->join('c_staff_group g','r.group_id=g.id')
            ->where('g.shop_code',$shop_code)
            ->select();
        $order = [];
        $gInfo = [];
        foreach($groupStaff as $k=>$v){
            $order[$v['group_id']] += $gOrder[$v['staff_id']];
        }
        foreach($groupList as $k=>$v){
            $groupList[$k]['order'] = $order[$v['id']];
        }

        $this->assign('all',array_sum($gOrder));
        $this->assign('groupList', $groupList);


        $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);
    }

}