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

class Dsj_ds_data extends Report {

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

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

    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data()
    {
        $data = input();
        $start = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));

        $where['is_status'] = 1;
        $where['c_from'] = 1;

        if($data['consultation_type_id']){
            $where['consultation_type_id'] = intval($data['consultation_type_id']);
        }
        $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'=>'报表配置有误');
        }
        if($data['channel_name']){
            $channel = db('s_channel')->where('channel_name','in',explode(',',trim($data['channel_name'])))->where('shop_code',$shop_code)->order('order_sort')->select();
        }else{
            $channel = controller('crm/Customer','lib')->getChannel($shop_code);
        }
        // 花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where('shop_code','in',$shop_code)
            ->where('channel_name','in',array_column($channel,'channel_name'))
            ->group('channel_name')
            ->column('sum(cost)','channel_name');

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=1) as valid,';
        $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in ("2","3","5")) as jd,';
//            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=2) as jdOrder,';
//            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=1) as `online`,';
//            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`';
        $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and fact_money>0 and order_type=2) as jdOrder,';
        $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and fact_money>0 and order_type=2 and is_success=1) as jdValidOrder,';
        $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and order_type=1) as `online`';


        $info = db('c_customerinfo')
            ->where($where)
            ->where('shop_code','in',$shop_code)
            ->where('customer_channel','in',array_column($channel,'channel_name'))
            ->group('customer_channel')
            ->column($sql,'customer_channel');
//        echo db()->getLastSql();die;
        $whereN['c.is_status'] = 1;
        $whereN['c.c_from'] = 1;
        if($data['consultation_type_id']){
            $whereN['c.consultation_type_id'] = intval($data['consultation_type_id']);
        }
        // 营收（一销）
        $fact = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($whereN)
            ->where('d.pay_type',1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->where('c.shop_code','in',$shop_code)
            ->where('c.customer_channel','in',array_column($channel,'channel_name'))
            ->group('c.customer_channel')
            ->column('sum(d.order_fact)','c.customer_channel');
        // 套系（一销）
        $amount = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($whereN)
            ->where('c.shop_code','in',$shop_code)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->where('c.customer_channel','in',array_column($channel,'channel_name'))
            ->group('c.customer_channel')
            ->column('sum(o.order_amount)','c.customer_channel');
        $returnData = [];
        $total = [];
        $total['channel_name'] = '总计';
        foreach($channel as $k=>$v){
            $arr = [];
            $arr['channel_name'] = $v['channel_name'];
            $arr['cost'] = $cost[$v['channel_name']] ? sprintf('%.2f',$cost[$v['channel_name']]) : '';
            $arr['mkz'] = $info[$v['channel_name']]['mkz'];
            $arr['valid'] = $info[$v['channel_name']]['valid'];
            $arr['validRate'] = $info[$v['channel_name']]['valid'] ? sprintf('%.2f',$info[$v['channel_name']]['valid']/$info[$v['channel_name']]['mkz']*100).'%' : '0%';
            $arr['mkzCost'] = $info[$v['channel_name']]['mkz'] ? sprintf('%.2f',$cost[$v['channel_name']]/$info[$v['channel_name']]['mkz']) : '';//客资成本
            $arr['validCost'] = $info[$v['channel_name']]['valid'] ? sprintf('%.2f',$cost[$v['channel_name']]/$info[$v['channel_name']]['valid']) : '';//有效客资成本
            $arr['jd'] = $info[$v['channel_name']]['jd'];
            $arr['jdRate'] = $info[$v['channel_name']]['jd']+$info[$v['channel_name']]['online']>0 ? sprintf('%.2f',($info[$v['channel_name']]['jd']+$info[$v['channel_name']]['online'])/$info[$v['channel_name']]['valid']*100).'%' : '0%';//进店率
            $arr['jdOrder'] = $info[$v['channel_name']]['jdOrder'];
            $arr['jdValidOrder'] = $info[$v['channel_name']]['jdValidOrder'];
            $arr['online'] = $info[$v['channel_name']]['online'];
            $arr['order'] = $info[$v['channel_name']]['online']+$info[$v['channel_name']]['jdOrder'];
            $arr['orderCost'] = $info[$v['channel_name']]['order'] ? sprintf('%.2f',$cost[$v['channel_name']]/($info[$v['channel_name']]['online']+$info[$v['channel_name']]['jdValidOrder'])) : '';//订单成本
            $arr['orderRate'] = $info[$v['channel_name']]['jdOrder'] ? sprintf('%.2f',($info[$v['channel_name']]['jdValidOrder']+$info[$v['channel_name']]['online'])/$info[$v['channel_name']]['valid']*100).'%' : '0%';//成交率
            $arr['mkzRate'] = $info[$v['channel_name']]['order'] ? sprintf('%.2f',$arr['order']/$info[$v['channel_name']]['mkz']*100).'%' : '0%';//毛客资转化率
            $arr['fact'] = $fact[$v['channel_name']]? sprintf('%.2f',$fact[$v['channel_name']]) : '';
            $arr['amount'] = $amount[$v['channel_name']] ? sprintf('%.2f',$amount[$v['channel_name']]) : '';
            $arr['avg'] = $amount[$v['channel_name']] ? sprintf('%.2f',$amount[$v['channel_name']]/$info[$v['channel_name']]['order']) : '';
            $returnData[] = $arr;

            $total['cost'] += floatval($arr['cost']);
            $total['mkz'] += $arr['mkz'];
            $total['valid'] += $arr['valid'];
            $total['validRate'] = '';
            $total['mkzCost'] = '';
            $total['validCost'] = '';
            $total['jd'] += $arr['jd'];
            $total['jdRate'] = '';
            $total['jdOrder'] += $arr['jdOrder'];
            $total['jdValidOrder'] += $arr['jdValidOrder'];
            $total['online'] += $arr['online'];
            $total['order'] += $arr['order'];
            $total['orderCost'] = '';
            $total['orderRate'] = '';
            $total['mkzRate'] = '';
            $total['fact'] += floatval($arr['fact']);
            $total['amount'] += floatval($arr['amount']);
            $total['avg'] = '';
        }
        $total['validRate'] = $total['valid'] ? sprintf('%.2f',$total['valid']/$total['mkz']*100).'%' : '0%';
        $total['mkzCost'] = $total['cost'] ? sprintf('%.2f',$total['cost']/$total['mkz']) : '';
        $total['validCost'] = $total['cost'] ? sprintf('%.2f',$total['cost']/$total['valid']) : '';
        $total['jdRate'] = $total['jd'] ? sprintf('%.2f',$total['jd']/$total['valid']*100).'%' : '0%';
        $total['orderCost'] = $total['cost'] ? sprintf('%.2f',$total['cost']/$total['order']) : '';
        $total['orderRate'] = $total['order'] ? sprintf('%.2f',$total['jdOrder']/$total['jd']*100).'%' : '0%';
        $total['mkzRate'] = $total['order'] ? sprintf('%.2f',($total['jdOrder']+$total['online'])/$total['mkz']*100).'%' : '0%';
        $total['avg'] = $total['amount'] ? sprintf('%.2f',$total['amount']/$total['order']) : '';
        $returnData[] = $total;

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;

        // 导出
        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'=>$shop_code]);
            $file = $shop[0]['shop_name'].'-'.$ff.'.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    public function show(){
        $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();
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        //已设置的渠道
        $channel = controller('crm/Customer','lib')->getChannel($info['shop_code']);
        $this->assign('channel',$channel);
        $code = $this->getCode();
        $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', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}