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

class Shop_pk extends Report {

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

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

        $time = date('Y-m-d', strtotime($data['time']));
        if (!$time) {
            $return = ['code' => 100, 'msg' => '请选择日期', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        if(empty($timeArea)){
            $timeArea[0] = '00:00:00';
            $timeArea[1] = '23:59:59';
        }
        if ($time) {
            $start = $time . ' ' . $timeArea[0];
            $end = $time . ' ' . $timeArea[1];
        } else {
            $start = date('Y-m-d').' ' . $timeArea[0];
            $end = date('Y-m-d').' ' . $timeArea[1];
        }
        $id = db('s_report_form')->where('code', $this->getCode())->value('id');
        $det = db('s_report_detail')->where('form_id',$id)->field('shop_code,brandclass_id')->find();
        $shop_code = $det['shop_code'];
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $flag = 'ds';
        //判断是电商还是网销
        if ($shop_code[0]['is_marketing'] == 1) {
            $flag = 'ds';//毛客资（电商）
            $where['add_shop_code'] =  $shop_code;
            $title = ['组名', '员工', '毛客资'];
        } else if($shop_code[0]['is_marketing'] == 3 || $shop_code[0]['is_marketing'] == 4){
            $flag = 'wx';//有效客资，进店量（网销），订单量（门店）
            $where['shop_code'] = $shop_code;
            $title = ['组名', '员工', '有效客资', '进店量', '订单量'];
        }
        if($det['brandclass_id'] != 8){
            $whereT['consultation_type_id'] = HS_TYPE;
        }
        $returnData = [];
        $url = '5a01766b4a3dd';
        $res = sx_call($url, array('shop_code' =>$shop_code));
        if ($res['code'] == 200) {//店下的所有人员
            $allStaff = $res['data'];
        } else {
            return array('code' => 206, 'msg' => '查询店内所有人员接口调用失败', 'data' => '');
        }
        $groupInfo = db('c_staff_group')->alias('g')
            ->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code',session('shop_code'))
            ->column('g.group_name,r.staff_id,r.staff_name','r.staff_id');
        $staffIds = array_column($allStaff,'id');
        if($flag == 'ds'){
            $mkz = db('c_customerinfo')
                ->where($where)
                ->where('dj_staff_id', 'in',$staffIds)
                ->where('dj_day', 'between', [$start, $end])
                ->group('dj_staff_id')
                ->column('count(id) as num','dj_staff_id');
        }else{
            $valid = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('sales_staff_id', 'in',$staffIds)
                ->where('is_valid', 1)
                ->where('yx_day', 'between', [$start, $end])
                ->group('sales_staff_id')
                ->column('count(id) as num','sales_staff_id');
            $jd = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('is_intostore',2)
                ->where('sales_staff_id', 'in',$staffIds)
                ->where('syjd_day', 'between', [$start, $end])
                ->group('sales_staff_id')
                ->column('count(id) as num','sales_staff_id');
            $order = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('is_success',1)
                ->where('sales_staff_id','in',$staffIds)
                ->where('order_day', 'between', [$start, $end])
                ->group('sales_staff_id')
                ->column('count(id) as num','sales_staff_id');
        }
        $total= [];
        $total['group_name'] = '';
        $total['staff'] = '总计';
        foreach($allStaff as $k=>$v){
            $arr['group_name'] = $groupInfo[$v['id']]['group_name'];
            $arr['staff']= $v['staffname'];
            if($flag == 'ds'){
                $arr['mkz'] = $mkz[$v['id']];
                $total['mkz'] += $arr['mkz'];
            }else{
             $arr['valid'] = $valid[$v['id']];
             $arr['jd'] = $jd[$v['id']];
             $arr['order'] = $order[$v['id']];

             $total['valid'] += $arr['valid'];
             $total['jd'] += $arr['jd'];
             $total['order'] += $arr['order'];
            }
            array_push($returnData,$arr);
        }
        array_push($returnData,$total);
        // 导出
        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 {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = count($returnData);
            $return['data'] = $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']]);
        $this->assign('shop', $shop);

        // crm省    列表
        /*$data['type'] = 1;
        $data['shop_code'] = $shop_code;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);*/
        $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']);
        //查询事业部下的电商店
//        $shop = controller('crm/Customer','lib')->shop(['belong_shop_code'=>session('shop_code'),'is_marketing'=>1]);
        return $this->fetch($display);
    }

}