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

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

    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']) : '';


        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$shop_code]);
        //花费
        $cost = db('c_staff_channel_cost')
            ->where('shop_code',$shop_code)
            ->where('day','between',[$start,$end])
            ->group('staff_id')
            ->column('sum(cost)','staff_id');
        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as mkz,";//毛客资
        $sql .= "sum(customer_wechat is not null and add_friend_time is not null and dj_day between '$start' and '$end') as wxj,";//微信通过数 有微信，并且加好友的
        $sql .= "sum(customer_wechat is not null and dj_day between '$start' and '$end') as wx,";//微信数 有微信的
        if($consultation_type_id){
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and (is_intostore=2 or is_intostore=3 or is_intostore=5) 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 is_success=1 and order_day between '$start' and '$end') as `order2`,"; //进店订单
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_intostore=2 and is_success=1 and order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql .= "sum(onsultation_type_id = ".$consultation_type_id." and is_valid=1 and dj_day between '$start' and '$end') as `yx`";//有效客资
        }else{
            $sql .= "sum((is_intostore=2 or is_intostore=3 or is_intostore=5) 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(is_success=1 and order_day between '$start' and '$end') as `order2`,"; //进店订单
            $sql .= "sum(order_type=2 and is_success=1 and order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql .= "sum(is_valid=1 and dj_day between '$start' and '$end') as `yx`";//有效客资
        }

        $info = db('c_customerinfo')
            ->where($where)
            ->group('sales_staff_id')
            ->column($sql,'sales_staff_id');
//         echo db()->getLastSql();die;
        $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('c.order_start_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['staff_name'] = '总计';
        $wx = 0;
        foreach ($staff as $k => $v) {
            $arr = [];
            $arr['brandclass'] = session('brandclass');
            $arr['staff_name'] = $v['staffname'];
            $wx += $info[$v['id']]['wx'];
            //花费
            $arr['cost'] = $cost[$v['id']];
            //毛客资
            $arr['mkz'] = $info[$v['id']]['mkz'];

            //客资成本
            $arr['kzcb'] = $info[$v['id']]['mkz'] ? sprintf('%.2f',$cost[$v['id']]/$info[$v['id']]['mkz']) : '';
            //微信通过数
            $arr['wxj'] = $info[$v['id']]['wxj'];
            //微信通过率
            // $arr['wxRate'] = $info[$v['id']]['wxj'] ? sprintf('%.2f',$info[$v['id']]['wxj']/$info[$v['id']]['wx']*100).'%' : '';
            //有效客资
            $arr['yx'] = $info[$v['id']]['yx'];
            //进店
            $arr['jd'] = $info[$v['id']]['jd'];
            //网付
            $arr['online'] = $info[$v['id']]['order1'];
            //进店成交 进店订单
            $arr['jdOrder'] = $info[$v['id']]['order'];
            //总订单
            $arr['order'] = $info[$v['id']]['order']+$info[$v['id']]['order1'];
            //实收
            $arr['fact'] = sprintf('%.2f',$detail[$v['id']]);
            //营收 总额
            $arr['total'] = sprintf('%.2f',$amount[$v['id']]);
            //毛客资转化率
            $arr['mkzRate'] = $info[$v['id']]['mkz'] ? sprintf('%.2f',($info[$v['id']]['jd']+info[$v['id']]['order1'])/$info[$v['id']]['mkz']*100).'%' : '';
            //订单转化率
            $arr['ddRate'] = $info[$v['id']]['mkz'] ? sprintf('%.2f',$arr['order']/$info[$v['id']]['mkz']*100).'%' : '';
            //客资有效率
            $arr['kz_yx'] = $info[$v['id']]['mkz'] ? sprintf('%.2f',$info[$v['id']]['yx']/$info[$v['id']]['mkz']*100).'%' : '';
            //有效客资转化率
            $arr['yx_kzRate'] = $info[$v['id']]['yx'] ? sprintf('%.2f',($info[$v['id']]['jd']+info[$v['id']]['order1'])/$info[$v['id']]['yx']*100).'%' : '';
            //加微率
            $arr['jwl'] = $info[$v['id']]['mkz'] ? sprintf('%.2f',$info[$v['id']]['wxj']/$info[$v['id']]['mkz']*100).'%' : '';
            //成交成本
            $arr['orderCost'] = $cost[$v['id']] ? sprintf('%.2f',$cost[$v['id']]/$arr['order']) : '';
            //实收均价
            $arr['avg'] = sprintf('%.2f',$detail[$v['id']]) ? sprintf('%.2f',$detail[$v['id']]/$arr['order']) : '';
            //投产
            $arr['tc'] = $cost[$v['id']] ? sprintf('%.2f',$detail[$v['id']]/$cost[$v['id']]) : '';

            array_push($returnData, $arr);
            $total['cost'] += $arr['cost'];
            $total['mkz'] += $arr['mkz'];
            $total['yx'] += $arr['yx'];
            $total['wxj'] += $arr['wxj'];
            $total['ddRate'] = '';
            $total['jd'] += $arr['jd'];
            $total['online'] += $arr['online'];
            $total['order'] += $arr['order'];
            $total['mkzRate'] = '';
            $total['kzcb'] = '';
            $total['jdOrder'] += $arr['jdOrder'];
            $total['orderRate'] = '';
            $total['tc'] += floatval($arr['tc']);
            $total['orderCost'] += floatval($arr['orderCost']);
            $total['avg'] = '';
            $total['fact'] += floatval($arr['fact']);
            $total['total'] += floatval($arr['total']);
        }

        $total['kzcb'] = $total['mkz'] ? sprintf('%.2f',$total['cost']/$total['mkz']) : '';
        $total['mkzRate'] = number_format(($total['jd']+total['online']) / $total['mkz'] * 100, 2) . '%';
        $total['ddRate'] = number_format($total['order'] / $total['mkz'] * 100, 2) . '%';
        $total['kz_yx'] = number_format($total['yx'] / $total['mkz'] * 100, 2) . '%';
        $total['yx_kzRate'] = number_format(($total['jd']+$total['online']) / $total['yx'] * 100, 2) . '%';
        $total['jwl'] = number_format($total['wxj'] / $total['mkz'] * 100, 2) . '%';
        $total['orderRate'] = number_format($total['order'] / $total['jd'] * 100, 2) . '%';
        $total['avg'] = number_format($total['fact'] / $total['order'], 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['staff'] = $staff;
            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);
    }

}