<?php
/**
 * 报表实现类 网销综合数据分析1
 *
 * ============================================================================
 * 版权所有 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 Wx_group1 extends Report {

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

    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);
        $time1 = time();
        // 权限
        $auth = check_right('menu1521352658');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $title = ['序号','组名', '姓名','毛客资', '接入客资', '有效', '待定', '无效', '有效率', '无效率', '待定率', '电商未获取手机数', '网销获取手机数', '转手机率', '总手机数'];
        $data = input();

        $shopCode = $data['shop_code'];
        //获取店下的小组
        $groupList = db('c_staff_group')->where('shop_code', $shopCode)->select();
        if (empty($groupList)) {
            $return = ['code' => 100, 'msg' => '点击查询,搜索数据', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $returnData = [];
        for ($i = 0; $i < count($title); $i++) {
            $returnData[0][$i] = $title[$i];
        }
        // 时间区域
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        // $where['c.customer_type'] = 1;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if (session('brandclass_id') != 2) {
            $where['c.customer_type'] = 1;
        }
        $where['c.shop_code'] = $shopCode;
        $where['g.shop_code'] = $shopCode;
        if($data['consultation_type_id']){
            $whereT['consultation_type_id'] = intval($data['consultation_type_id']);
        }

        if ($data['province_id']) {
            $where['c.province_id'] = $data['province_id'];
        }
        if ($data['city_id']) {
            $where['c.city_id'] = $data['city_id'];
        }
        $total = [];

        //组内所有人
        $staff = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code',$shopCode)
            ->field('g.id,g.group_name,r.staff_id,r.staff_name')
            ->select();

        if(!$staff[0]['staff_name']){
            $staffIds = implode(',',array_column($staff,'staff_id'));
            $url = "5a18e3fa516a1";
            $res = sx_call($url,array('staff_id'=>$staffIds));
            $staffNames = [];
            if($res['code'] == 200){
                $info = $res['data'];
                foreach($info as $key=>$val){
                    $staffNames[$val['id']] = $val['staffname'];
                }
            }else{
                $return = ['code' => 100, 'msg' => '批量查询小组人员信息失败', 'count' => 0, 'data' => ''];
                return json($return);
            }
        }

        //毛客资
        $djCustomer = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //接入客资
        $allCustomer = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('jr_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //有效
        $validCustomer = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where($whereT)
            ->where('is_valid', 1)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //待定
        $ddCustoemr = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid', 2)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //无效
        $unValidCustomer = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid', 3)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');;
        //微信/QQ  存在微信或QQ 计算一项  电商未获取手机数
        $noTel = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where($whereT)
            ->where('is_first_tel', null)
            ->where('dj_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //转化手机数 原来没有，后来添加
        $zhaunTel = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where($whereT)
            ->where('customer_tel <> "" or customer_tel is not null ')
            ->where('is_first_tel', null)
            ->where('tel_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //转化手机率 转化手机数/第一次没获取到手机的客资数量
        //总手机数
        $allTel = db('c_customerinfo')->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where($whereT)
            ->where('customer_tel <> "" or customer_tel is not null ')
            ->where('tel_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        $returnData = [];
        $arr = [];
        $px = [];
        $arr['id'] = '';
        $arr['name'] = '';
        $arr['staff_name'] = '总计';
        $i = 1;
        //第一个小组
        $gid = $staff[0]['id'];
        //最后一个小组
        $last = end($staff);
        $lastSid = $last['staff_id'];
        $group = [];
        foreach($staff as $k=>$v){

            //小组总计
            $group[$v['id']]['id'] = '';
            $group[$v['id']]['name'] = '';
            $group[$v['id']]['staff_name'] = '总计';
            $group[$v['id']]['dj'] += $djCustomer[$v['staff_id']]['num'] ? $djCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['jrCus'] += $allCustomer[$v['staff_id']]['num'] ? $allCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['valid'] += $validCustomer[$v['staff_id']]['num'] ? $validCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['dd'] += $ddCustoemr[$v['staff_id']]['num'] ? $ddCustoemr[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['unValid'] += $unValidCustomer[$v['staff_id']]['num'] ? $unValidCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['validRate'] = sprintf('%.2f',$group[$v['id']]['valid']/$group[$v['id']]['jrCus'] * 100).'%';//有效率
            $group[$v['id']]['unValidRate'] = sprintf('%.2f',$group[$v['id']]['unValid']/$group[$v['id']]['jrCus'] * 100).'%';//无效率
            $group[$v['id']]['ddValidRate'] = sprintf('%.2f',$group[$v['id']]['dd']/$group[$v['id']]['jrCus'] * 100).'%';//无效率
            $group[$v['id']]['noTel'] += $noTel[$v['staff_id']]['num'] ? $noTel[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['zhaunTel'] += $zhaunTel[$v['staff_id']]['num'] ? $zhaunTel[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['zhaunTelRate'] = sprintf('%.2f',$group[$v['id']]['zhaunTel']/$group[$v['id']]['noTel'] * 100).'%';
            $group[$v['id']]['allTel'] += $allTel[$v['staff_id']]['num'] ? $allTel[$v['staff_id']]['num'] : 0;




            $px['id'] = $i;
            $px['name'] = $v['group_name'];
            $px['staff_name'] = $v['staff_name'] ? $v['staff_name'] : $staffNames[$v['staff_id']];
            $px['dj'] = $djCustomer[$v['staff_id']]['num'] ? $djCustomer[$v['staff_id']]['num'] : 0;
            $px['jrCus'] = $allCustomer[$v['staff_id']]['num'] ? $allCustomer[$v['staff_id']]['num'] : 0;

            $px['valid'] = $validCustomer[$v['staff_id']]['num'] ? $validCustomer[$v['staff_id']]['num'] : 0;

            $px['dd'] = $ddCustoemr[$v['staff_id']]['num'] ? $ddCustoemr[$v['staff_id']]['num'] : 0;
            $px['unValid'] = $unValidCustomer[$v['staff_id']]['num'] ? $unValidCustomer[$v['staff_id']]['num'] : 0;
            $px['validRate'] = sprintf('%.2f',$px['valid']/$px['jrCus'] * 100).'%';//有效率
            $px['unValidRate'] = sprintf('%.2f',$px['unValid']/$px['jrCus'] * 100).'%';//无效率
            $px['ddValidRate'] = sprintf('%.2f',$px['dd']/$px['jrCus'] * 100).'%';//待定率
            $px['noTel'] = $noTel[$v['staff_id']]['num'] ? $noTel[$v['staff_id']]['num'] : 0;
            $px['zhaunTel'] = $zhaunTel[$v['staff_id']]['num'] ? $zhaunTel[$v['staff_id']]['num'] : 0;
            $px['zhaunTelRate'] = sprintf('%.2f',$px['zhaunTel']/$px['noTel'] * 100).'%';
            $px['allTel'] = $allTel[$v['staff_id']]['num'] ? $allTel[$v['staff_id']]['num'] : 0;

            if((!empty($gid) && ($gid != $v['id']))){
                $returnData[]= $group[$gid];
                $gid = $v['id'];
            }
            $returnData[] = $px;
            if($v['staff_id'] == $lastSid){
                $returnData[]= $group[$gid];
            }

            $arr['dj'] += $px['dj'];
            $arr['jrCus'] += $px['jrCus'];
            $arr['valid'] += $px['valid'];
            $arr['dd'] += $px['dd'];
            $arr['unValid'] += $px['unValid'];
            $arr['validRate'] = '';
            $arr['unValidRate'] = '';
            $arr['ddValidRate'] = '';
            $arr['noTel'] += $px['noTel'];
            $arr['zhaunTel'] += $px['zhaunTel'];
            $arr['zhaunTelRate'] = '';
            $arr['allTel'] += $px['allTel'];
            $i++;
        }
        $arr['validRate'] = sprintf('%.2f',$arr['valid']/$arr['jrCus'] * 100).'%';//有效率
        $arr['unValidRate'] = sprintf('%.2f',$arr['unValid']/$arr['jrCus'] * 100).'%';//无效率
        $arr['ddValidRate'] = sprintf('%.2f',$arr['dd']/$arr['jrCus'] * 100).'%';//待定率
        $arr['zhaunTelRate'] = sprintf('%.2f',$arr['zhaunTel']/$arr['noTel'] * 100).'%';
        $returnData[] = $arr;


        //无小组人员
        $allStaff = getStaffsByWorkType(['shop_code'=>$shopCode,'work_type'=>RECEIVE_WORK_TYPE]);
        $staffs = array_column($staff,'staff_id');
        $noGroupStaff = array_column($allStaff,'id');
        $staff_diff_id = array_diff($noGroupStaff,$staffs);
        $staff_diff_id = implode(',',$staff_diff_id);
        $url = '5a18e3fa516a1';
        $res = sx_call($url,['staff_id'=>$staff_diff_id]);
        if($res['code'] == 200){
            $another = $res['data'];
        }
        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as dj,";
        $sql .= "sum(jr_day between '$start' and '$end') as jr,";
        $sql .= "sum(is_valid=2 and yx_day between '$start' and '$end') as dd,";//待定
        $sql .= "sum(is_valid=3 and yx_day between '$start' and '$end') as wx,";//无效
        if($data['consultation_type_id'] && session('brandclass_id') != 8){
            $sql .= "sum(consultation_type_id = ".$data['consultation_type_id']." and is_valid=1 and yx_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(consultation_type_id = ".$data['consultation_type_id']." and is_valid=1 and yx_day between '$start' and '$end' and (customer_tel is not null and customer_tel <> '')) as tel,";

            $sql .= "sum(consultation_type_id = ".$data['consultation_type_id']." and is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";
            $sql .= "sum(consultation_type_id = ".$data['consultation_type_id']." and is_success=1 and order_day between '$start' and '$end') as newOrder";
        }else{
            $sql .= "sum(is_valid=1 and yx_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(is_valid=1 and yx_day between '$start' and '$end' and (customer_tel is not null and customer_tel <> '')) as tel,";
            $sql .= "sum(is_intostore in (2,3) and syjd_day between '$start' and '$end') as jd,";
            $sql .= "sum(is_success=1 and order_day between '$start' and '$end') as newOrder";
        }


        $whereNo['is_status'] = 1;
        $whereNo['c_from'] = 1;
        $whereNo['shop_code'] = $shopCode;
        // $whereNo['customer_type'] = 1;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if (session('brandclass_id') != 2) {
            $whereNo['customer_type'] = 1;
        }
        // 录入客资量（分配）
        $info= db('c_customerinfo')
            ->where($whereNo)
            ->where('sales_staff_id', 'in', $staff_diff_id)
            ->group('sales_staff_id')
            ->column($sql,'sales_staff_id');
        //电商未获取手机数
        $dsNotTel = db('c_customerinfo')
            ->where($whereNo)
            ->where($whereT)
            ->where('is_first_tel',null)
            ->where('sales_staff_id','in', $staff_diff_id)
            ->where('dj_day','between',[$start,$end])
            ->group('sales_staff_id')
            ->column('count(id) as num','sales_staff_id');
        //网销获取手机数
        $wxTel = db('c_customerinfo')
            ->where($whereNo)
            ->where($whereT)
            ->where('is_first_tel',null)
            ->where('customer_tel is not null or customer_tel<>""')
            ->where('sales_staff_id','in', $staff_diff_id)
            ->where('tel_time','between',[$start,$end])
            ->group('sales_staff_id')
            ->column('count(id) as num','sales_staff_id');
        //总手机数
        $tel =  db('c_customerinfo')
            ->where($whereNo)
            ->where($whereT)
            ->where('customer_tel is not null or customer_tel<>""')
            ->where('sales_staff_id','in', $staff_diff_id)
            ->where('tel_time','between',[$start,$end])
            ->group('sales_staff_id')
            ->column('count(id) as num','sales_staff_id');
        $no = [];
        $noG = [];
        $noG['id'] = $i;
        $noG['name'] = '';
        $noG['staff_name'] =  '总计';
        foreach($another as $k=>$v){
            $no['id'] = $i;
            $no['name'] = '无小组';
            $no['staff_name'] = $v['staffname'] ? $v['staffname'] : '';
            $no['dj'] = $info[$v['id']]['dj'] ? $info[$v['id']]['dj'] : 0;
            $no['jrCus'] = $info[$v['id']]['jr'] ? $info[$v['id']]['jr'] : 0;

            $no['valid'] = $info[$v['id']]['valid'] ? $info[$v['id']]['valid'] : 0;

            $no['dd'] = $info[$v['id']]['dd'] ? $info[$v['id']]['dd'] : 0;
            $no['unValid'] = $info[$v['id']]['wx'] ? $info[$v['id']]['wx'] : 0;
            $no['validRate'] = sprintf('%.2f',$no['valid']/$no['jrCus'] * 100).'%';//有效率
            $no['unValidRate'] = sprintf('%.2f',$no['unValid']/$no['jrCus'] * 100).'%';//无效率
            $no['ddValidRate'] = sprintf('%.2f',$no['dd']/$no['jrCus'] * 100).'%';//待定率
            $no['noTel'] = $dsNotTel[$v['id']] ? $dsNotTel[$v['id']] : 0;
            $no['zhaunTel'] = $zhaunTel[$v['id']] ? $zhaunTel[$v['id']] : 0;
            $no['zhaunTelRate'] = sprintf('%.2f',$wxTel['zhaunTel']/$dsNotTel['noTel'] * 100).'%';
            $no['allTel'] = $tel[$v['id']] ? $tel[$v['id']] : 0;
            $returnData[] = $no;
            //无小组人员相加
            $noG['dj'] += $no['dj'];
            $noG['jrCus'] += $no['jrCus'];
            $noG['valid'] += $no['valid'];
            $noG['dd'] += $no['dd'];
            $noG['unValid'] += $no['unValid'];
            $noG['validRate'] ='';
            $noG['unValidRate'] = '';
            $noG['ddValidRate'] = '';
            $noG['noTel'] += $no['noTel'];
            $noG['zhaunTel'] += $no['zhaunTel'];
            $noG['zhaunTelRate'] = '';
            $noG['allTel'] += $no['allTel'];
            $i++;
        }

        $noG['dj'] += $arr['dj'];
        $noG['jrCus'] += $arr['jrCus'];
        $noG['valid'] += $arr['valid'];
        $noG['dd'] += $arr['dd'];
        $noG['unValid'] += $arr['unValid'];
        $noG['validRate'] = sprintf('%.2f',$noG['valid']/$noG['jrCus'] * 100).'%';//有效率
        $noG['unValidRate'] = sprintf('%.2f',$noG['unValid']/$noG['jrCus'] * 100).'%';//无效率
        $noG['ddValidRate'] = sprintf('%.2f',$noG['dd']/$noG['jrCus'] * 100).'%';//待定率
        $noG['noTel'] += $arr['noTel'];
        $noG['zhaunTel'] += $arr['zhaunTel'];
        $noG['zhaunTelRate'] = sprintf('%.2f',$noG['zhaunTel']/$noG['noTel'] * 100).'%';
        $noG['allTel'] += $arr['allTel'];
        $returnData[] = $noG;

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $file = '网销综合数据分析1.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
        // 导出
        if ($data['need'] == 1) {
            unset($returnData[0]);
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$shopCode]);
            $file = $shop[0]['shop_name'].'-'.$ff.'.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            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);
      /*  // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);*/
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        // // 来源渠道
        // $channels = controller('crm/Customer', 'lib')->getChannel();
        // $this->assign('channel', $channels);

        //查询事业部下的电商店
//        $shop = controller('crm/Customer','lib')->shop(['belong_shop_code'=>session('shop_code'),'is_marketing'=>1]);
//        array_push($shop,['shop_code'=>session('shop_code'),'shop_name'=>session('shop_name')]);
        //来源渠道
        $shopCode = array_column($shop,'shop_code');
        $channel = db('s_channel')->where('shop_code','in',$shopCode)->order('order_sort')->select();
        $this->assign("channel", $channel);

        // 客资标记
        $signs = db('STracksign')->where('shop_code',$info['shop_code'])->where('is_delete',1)->select();
        $this->assign('signs', $signs);
        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' => $info['shop_code']));
        $this->assign("accessModel", $accessModel);

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

}