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

class Zzbb_channel_yj_week_data_dianshang extends Report {
    private $level=1;
    private $type =1;
    private $code ='code1593597324';

    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();

        $date = explode(" - ", $data['date']);

        $start = $date[0] ? $date[0] : date("Y-m-d",strtotime("-7 day"));
        $end = $date[1] ? $date[1] : date('Y-m-d');
        $d1 = strtotime($start);
        $d2 = strtotime($end);
        $Days = round(($d2-$d1)/3600/24);
        if ($Days > 31) {
            $return['code'] = 100;
            $return['msg'] = '日期范围请选择一个月31天内。';

            return json($return);
        }

        $det = db('crm_s_report_form')->alias('f')->join('crm_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'=>'报表配置有误');
        }
        // ordernote 订单备注 order表
        // allfc 所有服次 currentfc 当前服次
        // c_paymentcontent  payclass =3 充值
        // c_paymentcontent  isshishou=实收 
        // c_paymentcontent  payment_money 小于 0 退款
        // c_paymentcontent  paytype 付款方式 
        // selectman 选片师 sp表
        // cameraman 摄影师 photo表
        // mentor_a  引导师A photo表
        // dresser   化妆师 photo表
        // crm_c_customerinfo  客资量  条件where customer_channel 渠道 and  dj_day 点击时间 and is_status=1 and c_from=1  
        //进店量 条件where wangfutype = 进店
        //进店率 进店/客资量
        $returnData = [];
        // $today = date('Ymd',strtotime($start));
        $start = date('Ymd',strtotime($start));
        $end = date('Ymd',strtotime($end));
        $recTime = microtime(true).'<br />';
        $allOrderIds = db('c_customerorder')->alias('o')//订单表
            ->join('c_customerphoto ph', 'o.orderId=ph.orderId','left')//拍照表
            ->join('c_customersp sp', 'o.orderId=sp.orderId','left')//选片表
            ->join('c_paymentcontent p','o.orderId=p.orderId','left')//收款表
            ->where('o.shop_code="'.$shop_code.'" and o.targetdate between "'.$start.'" and "'.$end.'"')
            ->whereOr('ph.shop_code="'.$shop_code.'" and ph.photodate between "'.$start.'" and "'.$end.'"')
            ->whereOr('sp.shop_code="'.$shop_code.'" and sp.selectday between "'.$start.'" and "'.$end.'"')
            ->whereOr('p.shop_code="'.$shop_code.'" and p.paymentdate between "'.$start.'" and "'.$end.'"')
            // ->page($page)->limit($limit)
            ->group('o.orderId')->column('o.orderId','o.orderId');
        $sql0 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        // 当日订单客资
        $orderField = 'o.targetdate,o.orderId,c.wphone,c.wname,c.customer_channel,c.bbithdate,o.payment_money,o.nopayment_money,o.bargain_money,o.yixiaoshishou,o.supplementary_money,o.old_bargain_money,o.shengjimoney,o.ordernote,ch.channel_info_name,o.total_money,o.wangfutype';
        $todayOrder = db('c_customerorder')->alias('o')
            ->join('c_customerinfo c', 'c.customerid=o.customerid','left')//客资信息表
            ->join('c_customerorder_servicefc fc', 'fc.orderId=o.orderId','left')
            ->join('crm_s_channel ch', 'ch.channel_name=c.customer_channel','left')//渠道
            ->join('crm_c_customerinfo crm_c', 'crm_c.customer_number=o.crm_customer_number','left')
            // ->fetchSql(true)
            ->where('o.orderId','in',$allOrderIds)
            ->where('o.targetdate','between',[$start,$end])
            ->order('ch.channel_info_name')
            ->group('o.orderId')
            ->column($orderField.',fc.allfc,crm_c.order_start_time,crm_c.jr_day','o.orderId');
        $sql1 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        // echo $sql1;die;
        foreach ($todayOrder as $key => $value) {
            // 渠道
            $returnData[$value['customer_channel']]['qd'] = $value['channel_info_name'];
            // 渠道 名称
            $returnData[$value['customer_channel']]['qdmc'] = $value['customer_channel'];

            if ($value['bargain_money'] > 0) {
                if ($value['allfc']>1) {
                    // 成长套
                    $returnData[$value['customer_channel']]['ysczt'] += 1;
                }else{
                    // 单套
                    $returnData[$value['customer_channel']]['ysdt'] += 1;
                }
            }
            // 客户欠款
            $returnData[$value['customer_channel']]['qk'] = $value['nopayment_money'];

            //一销 订单量
            if ($value['bargain_money'] > 0) {
                $returnData[$value['customer_channel']]['yx'] += 1;
            }
            //一销 金额
            $returnData[$value['customer_channel']]['yxjine'] += $value['bargain_money'];
            
            // 订单备注
            $returnData[$value['customer_channel']]['bz'] = $value['ordernote'];
            $returnData[$value['customer_channel']]['orderId'] = $value['orderId'];

            //进店量 条件where wangfutype = 进店
            if ($value['wangfutype']=='进店') {
                $returnData[$value['customer_channel']]['jdl'] += 1;
            }

            // 平均成交时长  （订单开始时间order_start_time  -  接入日期jr_day）(单位：小时，累加) / 订单量
            if ($value['order_start_time']&&$value['jr_day']) {
                $returnData[$value['customer_channel']]['sc_lj'] += intval(strtotime($value['order_start_time'])-strtotime($value['jr_day']));
            }else{
                $returnData[$value['customer_channel']]['sc_lj'] += 0;
            }
        }
        $recTime .= microtime(true).'<br />';

        //客资信息表      当日咨询量   客户渠道customer_channel
        $allOrderzxl = db('crm_c_customerinfo')->alias('c')
            ->join('c_customerorder o', 'c.customer_number=o.crm_customer_number','left')//客资信息表
            // ->where("c.dj_day between '$start' and '$end'")
            ->where("c.is_status",1)
            ->where("c.c_from",1)
            ->where("o.shop_code",$shop_code)
            ->group('c.customer_channel')
            ->field("c.customer_channel,c.dj_day,sum(c.dj_day between '".$start."' and '".$end."') as mkz")
            ->select();
        $sql0 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        foreach ($allOrderzxl as $key => $value) {
            //客资量
            $returnData[$value['customer_channel']]['mkz'] = $value['mkz'] == 0 ? '' : $value['mkz'];
        }

        // 今日拍照客资 同一天 有可能拍照两次 所以不能使用 column
        $todayPhoto = db('c_customerorder')->alias('o')
            ->join('c_customerinfo c', 'c.customerid=o.customerid','left')
            ->join('c_customerphoto ph', 'ph.orderId=o.orderId','left')
            ->join('crm_s_channel ch', 'ch.channel_name=c.customer_channel','left')//渠道
            ->where('o.orderId','in',$allOrderIds)
            ->where('ph.photodate','between',[$start,$end])
            ->order('ph.photodate')
            ->field($orderField.',ph.photodate,ph.cameraman,ph.mentor_a,ph.dresser,ph.currentfc,ph.photonote,ph.qqphotomoney')
            ->select();
        $sql2 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        foreach ($todayPhoto as $key => $value) {
            // 渠道
            $returnData[$value['customer_channel']]['qd'] = $value['channel_info_name'];
            // 渠道 名称
            $returnData[$value['customer_channel']]['qdmc'] = $value['customer_channel'];

            // // 成长套拍摄剩余次数
            $allfc = db('c_customerorder_servicefc')->where('orderId',$value['orderId'])->value('allfc');

            // 客户欠款
            $returnData[$value['customer_channel']]['qk'] = $value['nopayment_money'];

            // 订单 + 摄影备注
            $note = '';
            if ($value['ordernote']) {
                $note .= $value['ordernote'].'--';
            }
            if ($value['photonote']) {
                $note .= $value['photonote'];
            }
            $returnData[$value['customer_channel']]['bz'] = $note;
            $returnData[$value['customer_channel']]['orderId'] = $value['orderId'];
        }
        
        $recTime .= microtime(true).'<br />';
        // 今日选片客资 
        $todaySp = db('c_customerorder')->alias('o')
            ->join('c_customerinfo c', 'c.customerid=o.customerid','left')
            ->join('c_customerphoto ph', 'ph.orderId=o.orderId','left')
            ->join('c_customersp sp', 'sp.orderId=o.orderId','left')
            ->join('crm_s_channel ch', 'ch.channel_name=c.customer_channel','left')//渠道
            ->where('o.orderId','in',$allOrderIds)
            ->where('sp.selectday','between',[$start,$end])
            ->order('sp.selectday')
            ->column($orderField.',ph.cameraman,ph.mentor_a,ph.dresser,sp.selectday,sp.selectman,sp.currentfc,sp.spremarks','o.orderId');
        $sql3 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        foreach ($todaySp as $key => $value) {
            // 渠道
            $returnData[$value['customer_channel']]['qd'] = $value['channel_info_name'];
            // 渠道 名称
            $returnData[$value['customer_channel']]['qdmc'] = $value['customer_channel'];
            // 客户欠款
            $returnData[$value['customer_channel']]['qk'] = $value['nopayment_money'];

            // 订单 + 摄影 + 选片备注
            $note = '';
            if ($value['ordernote']) {
                $note .= $value['ordernote'].'--';
            }
            if ($value['photonote']) {
                $note .= $value['photonote'].'--';
            }
            if ($value['spremarks']) {
                $note .= $value['spremarks'];
            }
            $returnData[$value['customer_channel']]['bz'] = $note;
            $returnData[$value['customer_channel']]['orderId'] = $value['orderId'];
        }
        // die;
        $recTime .= microtime(true).'<br />';
        // 今日收款客资
        $todayPay = db('c_customerorder')->alias('o')
            ->join('c_customerinfo c', 'c.customerid=o.customerid','left')
            ->join('c_paymentcontent p', 'p.orderId=o.orderId','left')
            ->join('crm_s_channel ch', 'ch.channel_name=c.customer_channel','left')//渠道
            ->where('o.orderId','in',$allOrderIds)
            ->where('p.paymentdate','between',[$start,$end])
            ->order('p.paymentdate')
            ->field($orderField.',p.paymentdate,p.payclass,p.paytype,p.isshishou,p.payment_money as pay,p.fundname,p.suoshu,p.remarks')
            ->select();
        $sql4 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        foreach ($todayPay as $key => $value) {
            // 渠道
            $returnData[$value['customer_channel']]['qd'] = $value['channel_info_name'];
            // 渠道 名称
            $returnData[$value['customer_channel']]['qdmc'] = $value['customer_channel'];

            // 客户还欠款
            if ($value['suoshu']=='前期补款' || $value['suoshu']=='后期补款') {
                $returnData[$value['customer_channel']]['hqk'] += $value['pay'];
            }
            // // 充值金额
            // if ($value['payclass']==3) {
            //     $returnData[$value['customer_channel']]['czje'] += $value['pay'];
            // }
            // // 返现金额
            // $returnData[$value['orderId']]['czfx'] = '';
            // // 客户退款(一)
            if ($value['pay']<0) {
                $returnData[$value['customer_channel']]['tk'] = $value['pay'];
            }
            // 实收 金额 包含充值
            if ($value['isshishou']=='实收') {
                $returnData[$value['customer_channel']]['ssje'] += $value['pay'];
            }
            // 付款方式
            $returnData[$value['customer_channel']][$value['paytype']] += $value['pay'];
            if ($value['paytype'] == 'VIP卡') {
                $returnData[$value['customer_channel']]['xkjine'] += $value['pay'];
            }
            // 应收金额
            $returnData[$value['customer_channel']]['ysje'] = $value['total_money'];

            // if ($allfc>1) {
            //     // 选片 成长套选片量
            //     $returnData[$value['orderId']]['czt'] = 1;
            // }else{
            //     // 选片 单套选片量
            //     $returnData[$value['orderId']]['dt'] = 1;
            // }

            // 订单 + 摄影 + 选片 + 收款备注
            $note = '';
            if ($value['ordernote']) {
                $note .= $value['ordernote'].'--';
            }
            if ($value['photonote']) {
                $note .= $value['photonote'].'--';
            }
            if ($value['spremarks']) {
                $note .= $value['spremarks'];
            }
            if ($value['remarks']) {
                $note .= $value['remarks'];
            }
            $returnData[$value['customer_channel']]['bz'] = $note;
            $returnData[$value['customer_channel']]['orderId'] = $value['orderId'];
        }
        foreach ($returnData as $key => $value) {
            // 一销 订单人均
            $returnData[$key]['yx_rj'] = $value['yxjine'] ? sprintf("%.2f",$value['yxjine']/$value['yx']) : '';
            //进店率 进店/客资量
            $returnData[$key]['jdlv'] = $value['jdl'] ? sprintf("%.2f",$value['jdl']/$value['mkz']) : '';
            
            if (intval($value['sc_lj']/3600)>0&&($value['ysczt']+$value['ysdt'])>0) {
                // 平均成交时长  （订单开始时间order_start_time  -  接入日期jr_day）(单位：小时，累加) / 订单量
                $returnData[$key]['pjcjsc'] = intval($value['sc_lj']/3600)/($value['ysczt']+$value['ysdt']);
            }

            //总计
            $returnData['合计']['qd'] = '合计';
            $returnData['合计']['mkz'] += $value['mkz'];
            $returnData['合计']['jdl'] += $value['jdl'];
            $returnData['合计']['kyu'] += $value['czje'];
            $returnData['合计']['ysje'] += $value['ysje'];
            $returnData['合计']['ssje'] += $value['ssje'];
            $returnData['合计']['qk'] += $value['qk'];
            $returnData['合计']['hqk'] += $value['hqk'];
            $returnData['合计']['tk'] += $value['tk'];
            $returnData['合计']['yxjine'] += $value['yxjine'];
            $returnData['合计']['ysczt'] += $value['ysczt'];
            $returnData['合计']['ysdt'] += $value['ysdt'];
        }
        $recTime .= microtime(true).'<br />';
        $return['sql0'] = $sql0;//查询所有订单单号
        $return['sql1'] = $sql1;//查询今日订单
        $return['sql2'] = $sql2;//查询今日拍照
        $return['sql3'] = $sql3;//查询今日选片
        $return['sql4'] = $sql4;//查询今日收款
        $return['recTime'] = $recTime;
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;

        return json($return);
    }
    //  
    public function show(){
        /*
        $did = strtolower(input('param.did'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_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();*/
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->alias('f')->join('crm_s_report_detail d','d.form_id=f.id','left')->where('f.code',$menu_code)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        $city = db('crm_s_shop_address')->where('shop_code',$info['shop_code'])->where('type',2)->select();
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        //来源渠道
        $channel = getChannelJson($info['shop_code']);
        $this->assign("channel", json_encode($channel));

        $code = $this->getCode();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('crm_s_report_form')->where('code', $code)->value('report_name');
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        // c_paymenttype
        $allPayType = db('c_paymenttype')->where("find_in_set('".$info['shop_code']."',shop_code)")->field('id,typename')->select();
        $this->assign('allPayType', $allPayType);
        $this->assign('allPayCount', count($allPayType));
        // 当前操作人的可操作店
        $yesdate = date("Y-m-d",strtotime("-7 day"))." - ".date("Y-m-d");
        $this->assign('yesdate', $yesdate);

        return $this->fetch($display);
    }

}