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

class Ls_wx_data extends Report {

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

    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']) {
            $return = ['code' => 200, 'msg' => '请选择开始时间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        if (!$data['end']) {
            $return = ['code' => 200, 'msg' => '请选择结束时间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $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'=>'报表配置有误');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = $shop_code;
        $consultation_type_id = $data['consultation_type_id'] ? intval($data['consultation_type_id']) : HS_TYPE;
        // 地域id，拼接where条件
        if ($data['province_id'] && $data['province_id'] != 'undefined') {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
        }
        if ($data['city_id'] && $data['city_id'] != 'undefined') {
            $where['city_id'] = (int)$data['city_id'];
            $whereC['city_id'] = (int)$data['city_id'];
        }

        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$shop_code]);
        $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 yx_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 order_type=1 and is_success=1 and order_day between '$start' and '$end') as order1,";//网付
//            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and order_type=2 and is_success=1 and order_day between '$start' and '$end') as order2,";//进店订单
//            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_success=1 and order_day between '$start' and '$end') as `order`,";
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and order_type=1 and fact_money>500 and order_start_time between '$start' and '$end') as order1,";//网付
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and order_type=2 and fact_money>100 and order_start_time between '$start' and '$end') as order2,";//进店订单
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and ((order_type=1 and fact_money>500)or(order_type=2 and fact_money>100)) and order_start_time between '$start' and '$end') as `order`,";
        }else{
            $sql .= "sum(is_valid=1 and yx_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(order_type=1 and is_success=1 and order_day between '$start' and '$end') as order1,";//网付
//            $sql .= "sum(order_type=2 and is_success=1 and order_day between '$start' and '$end') as order2,";//进店订单
//            $sql .= "sum(is_success=1 and order_day between '$start' and '$end') as `order`,";
            $sql .= "sum(order_type=1 and fact_money>500 and order_start_time between '$start' and '$end') as order1,";//网付
            $sql .= "sum(order_type=2 and fact_money>100 and order_start_time between '$start' and '$end') as order2,";//进店订单
            $sql .= "sum(((order_type=1 and fact_money>500)or(order_type=2 and fact_money>100)) and order_start_time between '$start' and '$end') as `order`,";
        }
        $sql .= "sum(customer_wechat is not null and wechat_time between '$start' and '$end') as wx";

        $info = db('c_customerinfo')
            ->where($where)
            ->group('sales_staff_id')
            ->column($sql,'sales_staff_id');

        $whereTx['c.is_status'] = 1;
        $whereTx['c.c_from'] = 1;
        $whereTx['c.shop_code'] = $shop_code;
        //套系总额
        $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])
            ->group('c.sales_staff_id')
            ->column('sum(o.order_amount) as total','c.sales_staff_id');

        //营收
        $detail = db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where($whereTx)
            ->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 = [];
        $total = [];
        $total['name'] = '总计';
        foreach ($staff as $k => $v) {
            $arr = [];
            $arr['name'] = $v['staffname'];
            //毛客资
            $arr['mkz'] = $info[$v['id']]['mkz'];
            //有效客资
            $arr['valid'] = $info[$v['id']]['valid'];
            //进店
            $arr['jd'] = $info[$v['id']]['jd'];
            //网付
            $arr['order1'] = $info[$v['id']]['order1'];
            //进店订单
            $arr['order2'] = $info[$v['id']]['order2'];
            //新单
            $arr['order'] = $info[$v['id']]['order'];
            //套系 总额
            $arr['total'] = sprintf('%.2f',$amount[$v['id']]);
            //营收
            $arr['fact'] = sprintf('%.2f',$detail[$v['id']]);
            $arr['avg'] = sprintf('%.2f',$amount[$v['id']]) ? sprintf('%.2f',$amount[$v['id']]/$arr['order']) : '';
            //加微数
            $arr['wx'] = $info[$v['id']]['wx'];
            //加微率
            $arr['wxRate'] = $info[$v['id']]['wx'] ? sprintf('%.2f',$info[$v['id']]['wx']/$info[$v['id']]['mkz']*100).'%' : '';
            //订单转化率
            $arr['orderRate'] = $info[$v['id']]['order'] ? sprintf('%.2f',$info[$v['id']]['order']/$info[$v['id']]['valid']*100).'%' : '';
            //进店转化率
            $arr['jdRate'] = $info[$v['id']]['jd'] ? sprintf('%.2f',$info[$v['id']]['jd']/$info[$v['id']]['valid']*100).'%' : '';
            //进店成交率
            $arr['jdSuccRate'] = $info[$v['id']]['order'] ? sprintf('%.2f',$info[$v['id']]['order2']/$info[$v['id']]['jd']*100).'%' : '';

            array_push($returnData, $arr);
            $total['mkz'] += $arr['mkz'];
            $total['valid'] += $arr['valid'];
            $total['jd'] += $arr['jd'];
            $total['order1'] += $arr['order1'];
            $total['order2'] += $arr['order2'];
            $total['order'] += $arr['order'];
            $total['total'] += floatval($arr['total']);
            $total['fact'] += floatval($arr['fact']);
            $total['avg'] = '';
            $total['wx'] += $arr['wx'];
            $total['wxRate'] = '';
            $total['orderRate'] = '';
            $total['jdRate'] = '';
            $total['jdSuccRate'] = '';
        }


        $total['avg'] = number_format($total['total'] / $total['order'], 2);
        $total['wxRate'] = number_format($total['wx'] / $total['mkz'] * 100, 2) . '%';
        $total['orderRate'] = number_format($total['order'] / $total['valid'] * 100, 2) . '%';
        $total['jdRate'] = number_format($total['jd'] / $total['valid'] * 100, 2) . '%';
        $total['jdSuccRate'] = number_format($total['order2'] / $total['jd'] * 100, 2) . '%';
        array_push($returnData,$total);
        // 导出
        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['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);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['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);
        //查询事业部下的电商店
//        $shop = controller('crm/Customer','lib')->shop(['belong_shop_code'=>session('shop_code'),'is_marketing'=>1]);
//        $this->assign('shop', $shop);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}