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

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

    public function getLevel(){
        return $this->level;

    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data()
    {
        $param = input();
        $time = $param['time'] ? $param['time'] : 'yestoday';
        if($time == 'last_week'){
            $beginLastweek = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
            $endLastweek = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
            $start = date('Y-m-d H:i:s', $beginLastweek);
            $end = date('Y-m-d H:i:s', $endLastweek);
        }elseif($time == 'month'){
            $start = date('Y-m-01', strtotime(date("Y-m-d")));
            $end = date('Y-m-d 23:59:59', strtotime("$start +1 month -1 day"));
        }elseif($time == 'week'){
            $start = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
            $end = date('Y-m-d 23:59:59');
        }else{
            $start = date('Y-m-d 00:00:00',strtotime('-1 day'));
            $end = date('Y-m-d 23:59:59',strtotime('-1 day'));
        }
        $det = db('s_report_form')->alias('f')->join('s_report_detail d','d.form_id=f.id')->where('d.id',$param['did'])->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        $bid = $det['brandclass_id'];
        if(empty($bid)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $info = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$bid]);
        $shopCode = array_column($info,'shop_code');
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        if($param['consultation_type_id']){
            $whereT['consultation_type_id'] = intval($param['consultation_type_id']);
        }
        $returnData[0]['cost'] = db('c_customer_cost')
            ->where('shop_code', 'in',$shopCode)
            ->where('cost_time', 'between time', [$start, $end])
            ->sum('cost_avg');
        //毛客资
        $returnData[0]['mkz'] = db('c_customerinfo')->where('add_shop_code','in',$shopCode)->where('dj_day','between',[$start,$end])->where($where)->count();
        //有效客资
        $returnData[0]['valid'] =  db('c_customerinfo')->where('add_shop_code','in',$shopCode)->where('is_valid',1)->where($where)->where($whereT)->where('yx_day','between',[$start,$end])->count();
//        print_r($valid);die;
        //电话量
        $returnData[0]['tel'] =  db('c_customerinfo')->where('add_shop_code','in',$shopCode)->where('is_valid',1) ->where('customer_tel', '<>', '')->where($where)->where($whereT)->where('yx_day','between',[$start,$end])->count();
        //邀约率
        //进店
        $returnData[0]['jd'] =  db('c_customerinfo')->where('add_shop_code','in',$shopCode)->where('is_intostore',2)->where($where)->where($whereT)->where('syjd_day','between',[$start,$end])->count();
        //成交量
        $returnData[0]['succ'] =  db('c_customerinfo')->where('add_shop_code','in',$shopCode)->where('is_success',1)->where($where)->where($whereT)->where('order_day','between',[$start,$end])->count();
        //套系
        $returnData[0]['total'] =  db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where('c.is_status',1)
            ->where('c.brandclass_id',$bid)
            ->where('c.c_from',1)
            ->where('c.customer_type',1)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->sum('o.order_amount');
        //营收
        $returnData[0]['fact'] =  db('c_customerinfo')->alias('c')->join('c_order_detail d','c.order_number=d.order_sn')
            ->where('c.is_status',1)
            ->where('c.brandclass_id',$bid)
            ->where('c.c_from',1)
            ->where('c.customer_type',1)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->sum('d.order_fact');
        //成交平均
        $returnData[0]['succAVG'] = sprintf('%.2f',$returnData[0]['total']/$returnData[0]['succ']);
        //获取成本
        $returnData[0]['obtain'] = sprintf('%.2f',$returnData[0]['cost']/$returnData[0]['valid']);
        //成交成本
        $returnData[0]['succObtain'] = sprintf('%.2f',$returnData[0]['cost']/$returnData[0]['succ']);
        //转换率 有效订单/有效客资
        $returnData[0]['validOrderRate'] = sprintf('%.2f',$returnData[0]['succ']/$returnData[0]['valid']*100).'%';
        ///毛客资转化率 有效订单/毛客资
        $returnData[0]['mkzRate'] = sprintf('%.2f',$returnData[0]['succ']/$returnData[0]['mkz']*100).'%';

        // 导出
        if ($param['need'] == 1) {
            $title = ['花费','毛客资','有效获取','获取手机','进店','新单','套系','营收','成交平均','获取成本','成交成本','转换率','毛客资转换率'];
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $brandclass = controller('crm/Customer','lib')->getBrands(['brandclass_id'=>$bid]);
            $file = $brandclass[0]['brandclass'].'-'.$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();
        //消费类型
        $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');

        $brandclass = controller('crm/Customer','lib')->getBrands(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign('title', $brandclass[0]['brandclass'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}