<?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 Wx_ld extends Report {

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

    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();
        // 时间区域
        if (!$data['start'] || !$data['end']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $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'] ? $det['shop_code'] :session('shop_code');
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $where['is_status'] = 1;
        $data['shop_code'] = $shop_code;
        // $where['c_from'] = 1;
        // $where['customer_type'] = 1;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        // if($data['shop_code']){
        //     if($data['shop_code'] != session('shop_code')){
        //         $flag = 'dj_staff_id';
        //         $where['add_shop_code'] = $data['shop_code'];
        //         $whereD['add_shop_code'] = $data['shop_code'];
        //     }else{
        //         $flag = 'sales_staff_id';
        //         $where['shop_code'] = $data['shop_code'];
        //         $whereD['shop_code'] = $data['shop_code'];
        //     }
        // }
        if($data['consultation_type_id']){
            $consultation_type_id = intval($data['consultation_type_id']);
        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
            $whereD['c.province_id'] = (int)$data['province_id'];
        }
        if ($data['city_id']) {
            $where['city_id'] = (int)$data['city_id'];
            $whereC['city_id'] = (int)$data['city_id'];
            $whereD['c.city_id'] = (int)$data['city_id'];
        }
        if ($data['channel_id']) {//渠道
            $where['customer_channel_id'] = (int)$data['channel_id'];
            $whereC['channel_id'] = (int)$data['channel_id'];
            $whereD['c.customer_channel_id'] = (int)$data['channel_id'];
        }
        if ($data['accessModel_id']) {//获取方式
            $where['access_model_id'] = (int)$data['accessModel_id'];
            $whereD['c.access_model_id'] = (int)$data['accessModel_id'];
        }
        //获取店内所有有话务类型的员工
        // $staffs = getStaffsByWorkType(['shop_code'=>$data['shop_code']]);
        $staffs = getShopStaffs(['shop_code'=>$data['shop_code'],'work_type'=>21]);
        $staffIds = array_column($staffs,'id');

        //电商店shop_code
        $ds_shop_code = controller('crm/Customer', 'lib')->get_shop(['belong_shop_code'=>$data['shop_code'],'is_marketing'=>1]);
        $ds_shop_code = array_column($ds_shop_code,'shop_code');

        $channelCost = db('c_customer_cost')
            ->where('shop_code','in',$ds_shop_code)
            ->where('cost_time', 'between time', [$start, $end])
            ->sum('cost_avg');

        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as mkz,";
        $sql .= "sum(jr_day between '$start' and '$end') as jrkz,";
        $sql .= "sum(is_valid=3 and dj_day between '$start' and '$end') as wx,";//无效
        $sql .= "sum(is_valid=4 and yx_day between '$start' and '$end') as bh,";//驳回
        if($data['consultation_type_id']){
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and yx_day between '$start' and '$end' and dj_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and yx_day between '$start' and '$end' and dj_day < '$start') as zhuanvalid,";//转有效
            // $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and yx_day between '$start' and '$end' and dj_day not between '$start' and '$end') as zhuanvalid,";//转有效
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and dj_day between '$start' and '$end' and (customer_tel is not null and customer_tel <> '')) as tel,";
            $sql .= "sum(yjd_day between '$start' and '$end') as yjd,";
            $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=1 and order_day between '$start' and '$end') as newOrder";
        }else{
            $sql .= "sum(is_valid=1 and yx_day between '$start' and '$end' and dj_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(is_valid=1 and yx_day between '$start' and '$end' and dj_day < '$start') as zhuanvalid,";//转有效
            // $sql .= "sum(is_valid=1 and yx_day between '$start' and '$end' and dj_day not between '$start' and '$end') as zhuanvalid,";//转有效
            $sql .= "sum(is_valid=1 and dj_day between '$start' and '$end' and (customer_tel is not null and customer_tel <> '')) as tel,";

            $sql .= "sum(yjd_day between '$start' and '$end') as yjd,";
            $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";
        }
        $customer= db('c_customerinfo')
            ->where($where)
            ->where('dj_day','between',[$start,$end])
            ->where('shop_code', $data['shop_code'])
            ->field('id,sales_staff_id')
            ->select();
        $allId = array_column($customer,'id');
        $temp = [];
        foreach($customer as $kk=>$vv){
            $temp[$vv['sales_staff_id']] .= $vv['id'].',';
        }
        foreach($temp as $kk=>$vv){
            $temp[$kk] = trim($vv,',');
        }
        $allcost = db('c_customer_from')->where('cid','in',$allId)->column('c_channel_cost','cid');
        $cost = [];
        foreach($temp as $k=>$v){
            $cusId = explode(',',$v);//追踪人的客资id
            foreach($allcost as $ke=>$val){ //所以客资的花费
                if(in_array($ke,$cusId)){ // 是否在当前追踪人的客资中
                    $cost[$k] += $val;
                }
            }
        }


        // 录入客资量（分配）
        $info= db('c_customerinfo')
            ->where($where)
            ->where('shop_code', $data['shop_code'])
//            ->where('sales_staff_id', 'in',$staffIds)
            ->group('sales_staff_id')
            ->column($sql,'sales_staff_id');
//        echo db()->getLastSql();die;
        //营收
        $detail = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($where)
            ->where('c.shop_code', $data['shop_code'])
//            ->where('c.sales_staff_id', 'in',$staffIds)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(d.order_fact) as fact','c.sales_staff_id');
        //套系
        $whereTx['c.c_from'] = 1;
        $whereTx['c.is_status'] = 1;
        $whereTx['c.is_loss'] = 2;
        $whereTx['c.is_success'] = 1;
        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if (session('brandclass_id') != 2) {
            $whereTx['c.customer_type'] = 1;
        }
        $total = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereTx)
            ->where('c.shop_code', $data['shop_code'])
//            ->where('c.sales_staff_id', 'in',$staffIds)
            ->where('o.order_valid', 2)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.sales_staff_id')
            ->column('sum(o.order_amount) as total','c.sales_staff_id');
        $returnData = [];
        $arr = [];
        $staffCost = [];

        foreach ($staffs as $key => $value) {
            $returnData[$key]['staff'] = $value['staffname'];
            $returnData[$key]['cost'] = $cost[$value['id']];
            $returnData[$key]['lrCustomer'] = $info[$value['id']]['mkz'];
            $returnData[$key]['jrCustomer'] = $info[$value['id']]['jrkz'];
            $returnData[$key]['invCustomer'] = $info[$value['id']]['valid'];
            $returnData[$key]['zhuaninvCustomer'] = $info[$value['id']]['zhuanvalid'];
            $returnData[$key]['wx'] = $info[$value['id']]['wx'];
            $returnData[$key]['bh'] = $info[$value['id']]['bh'];
            $returnData[$key]['allTel'] = $info[$value['id']]['tel'];
            $returnData[$key]['yjd'] = $info[$value['id']]['yjd'];
            $returnData[$key]['intoNum'] = $info[$value['id']]['jd'];
            $returnData[$key]['orderNum'] = $info[$value['id']]['newOrder'];
            $returnData[$key]['orderAmount'] = sprintf('%.2f',$total[$value['id']]);
            $returnData[$key]['factMoney'] = sprintf('%.2f',$detail[$value['id']]);
            $returnData[$key]['orderAmountAvg'] = sprintf('%.2f',$total[$value['id']]/$info[$value['id']]['newOrder']);
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$key]['invRate'] = (number_format($returnData[$key]['invCustomer'] / $returnData[$key]['lrCustomer']*100, 2)) . '%';
            // 进店率（ 实际进店 / 有效获取 ）
            $returnData[$key]['intoRate'] = (number_format($returnData[$key]['intoNum'] / $returnData[$key]['invCustomer']*100, 2)) . '%';
            // 邀约进店率（ 邀约进店 / 实际进店 ）
//            $returnData[$key]['yjdRate'] = (number_format($returnData[$key]['intoNum'] / $returnData[$key]['yjd']*100, 2)) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$key]['orderRate'] = (number_format($returnData[$key]['orderNum'] / $returnData[$key]['intoNum']*100, 2)) . '%';
            // 转化率（ 有效新单/有效获取）
            $returnData[$key]['changeRate'] = (number_format($returnData[$key]['orderNum']/$returnData[$key]['invCustomer']*100, 2)) . '%';

            $arr['staff'] = '总计';
            $arr['cost'] +=$cost[$value['id']];
            $arr['lrCustomer'] += $info[$value['id']]['mkz'];
            $arr['jrCustomer'] += $info[$value['id']]['jrkz'];
            $arr['invCustomer'] += $info[$value['id']]['valid'];
            $arr['zhuaninvCustomer'] += $info[$value['id']]['zhuanvalid'];
            $arr['wx'] += $info[$value['id']]['wx'];
            $arr['bh'] += $info[$value['id']]['bh'];
            $arr['allTel'] += $info[$value['id']]['tel'];
            $arr['yjd'] += $info[$value['id']]['yjd'];
            $arr['intoNum'] += $info[$value['id']]['jd'];
            $arr['orderNum'] += $info[$value['id']]['newOrder'];
            $arr['orderAmount'] += $total[$value['id']];
            $arr['factMoney'] += $detail[$value['id']];
        }
        $arr['orderAmount'] = sprintf('%.2f',$arr['orderAmount']);
        $arr['factMoney'] = sprintf('%.2f',$arr['factMoney']);
        $arr['orderAmountAvg'] = sprintf('%.2f',$arr['orderAmount']/$arr['orderNum']);
        $arr['invRate'] = sprintf('%.2f',$arr['invCustomer']/$arr['lrCustomer']*100).'%';
        $arr['intoRate'] = sprintf('%.2f',$arr['intoNum']/$arr['invCustomer']*100).'%';
//        $arr['yjdRate'] = sprintf('%.2f',$arr['intoNum']/$arr['yjd']*100).'%';
        $arr['orderRate'] = sprintf('%.2f',$arr['orderNum']/$arr['intoNum']*100).'%';
        $arr['changeRate'] = sprintf('%.2f',$arr['orderNum']/$arr['invCustomer']*100).'%';
        array_push($returnData,$arr);
        // 导出
        if ($data['need'] == 1) {
            $title = array('员工','花费', '毛客资','接入客资', '有效获取','转有效获取','无效','驳回', '总手机', '邀约量','进店量', '成交量','套系总额', '营收', '套系均值', '有效率', '进店率', '成交率', '转化率');
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$data['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);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' =>$info['shop_code']));
        $this->assign("accessModel", $accessModel);

        //客资地域
        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $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);
//        //查询事业部下的电商店
//        $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')]);
//        $this->assign('shop', $shop);
        //来源渠道
        $shopCode = array_column($shop,'shop_code');
        $channel = db('s_channel')->where('shop_code','in',$shopCode)->order('order_sort')->select();
        $this->assign("channel", $channel);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}
