<?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_shop_xdl_data extends Report {
    private $level=1;
    private $type =1;
    private $code ='code1593597343';

    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 = $data['start'] ? date('Y-m-d 00:00:00', strtotime($data['start'])) : date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59', strtotime($data['start']));
        $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表
        $returnData = [];
        $today = date('Ymd',strtotime($start));
        $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 = "'.$today.'"')
            ->whereOr('ph.shop_code="'.$shop_code.'" and ph.photodate = "'.$today.'"')
            ->whereOr('sp.shop_code="'.$shop_code.'" and sp.selectday = "'.$today.'"')
            ->whereOr('p.shop_code="'.$shop_code.'" and p.paymentdate = "'.$today.'"')
            // ->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';
        // 今日选片客资 
        $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',$today)
            ->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 />';
        if ($todaySp) {
            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']]['xp_zl'] += 1;

                //总选片业绩
                $spmoney = db('c_paymentcontent')->where('payclass',0)->where("currentfc",$value['currentfc'])->where("orderId",$value['orderId'])->where("suoshu","in",['后期款','后期补款'])->where("payment_money",'>',0)->sum("payment_money");
                // echo db()->getLastSql();
                // echo db('c_paymentcontent')->getLastSql();exit;db('c_paymentcontent')->where("currentfc",$value['currentfc'])->where("orderId",$value['orderId'])->where("suoshu","in",['后期款','后期补款'])->where("payment_money",'>',0)->sum("payment_money");
                $returnData[$value['customer_channel']]['xpjine'] += $spmoney;

                // 时光选片量
                $todaySgjn = db('c_consumptioncontent')//产品表
                    ->where('orderId',$value['orderId'])
                    ->where('consumption_name', 'like', '%时光胶囊%')
                    ->where('servicenumber',$value['currentfc'])
                    ->count();
                $returnData[$value['customer_channel']]['sg'] = $todaySgjn ? 1 : '';
            }
        }
        // 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',$today)
            ->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 />';
        if ($todayPay) {
            foreach ($todayPay as $key => $value) {
                // 渠道
                $returnData[$value['customer_channel']]['qd'] = $value['channel_info_name'];
                // 渠道 名称
                $returnData[$value['customer_channel']]['qdmc'] = $value['customer_channel'];
                // 总续订量
                if ($value['fundname']=='续订金额' && $value['pay'] > 0) {
                    $returnData[$value['customer_channel']]['xds'] += 1;
                }
                // 时光胶囊续订量=产品里含时光胶囊产品续订大于0的
                if ($value['fundname']=='时光胶囊续订款' && $value['pay'] > 0) {
                    $returnData[$value['customer_channel']]['sg_xds'] += 1;
                }
                // 总续订金额
                if ($value['fundname']=='续订金额') {
                    $returnData[$value['customer_channel']]['xdje'] += $value['pay'];
                }
                // 时光胶囊续订金额=取款项是“时光胶囊续订款”
                if ($value['fundname']=='时光胶囊续订款') {
                    $returnData[$value['customer_channel']]['sg_xdje'] += $value['pay'];
                }
                // 加选量
                if ($value['fundname']=='加选金额' && $value['pay'] > 0) {
                    $returnData[$value['customer_channel']]['jxs'] += 1;
                }
                // 加选金额
                if ($value['fundname']=='加选金额') {
                    $returnData[$value['customer_channel']]['jxje'] += $value['pay'];
                }
                //美团好评  手动填写
                $returnData[$value['customer_channel']]['meituan'] = '';
                //订单业绩=新开订单的实收（不含卡扣，不含充值）
                if ($value['payclass']==0) {
                    $returnData[$value['customer_channel']]['pay'] += $value['pay'];
                    //订单数量=当日新订单
                    if ($value['pay'] > 0) {
                        $returnData[$value['customer_channel']]['pay_num'] += 1;
                    }
                }
                //zyj 总业绩  =总实收
                if ($value['isshishou']=='实收') {
                    $returnData[$value['customer_channel']]['zyj'] += $value['pay'];
                }
            }
        }
        foreach ($returnData as $key => $value) {
            // 总续订率
            $returnData[$key]['xdlv'] = $value['xdje'] ? sprintf("%.2f",$value['xdje']/$value['xp_zl']) : '';
            // 续订 续订人均
            $returnData[$key]['xd_rj'] = $value['xdje'] ? sprintf("%.2f",$value['xdje']/$value['xds']) : '';
            // 时光胶囊续订率
            $returnData[$key]['sg_xdlv'] = $value['sg_xds'] ? sprintf("%.2f",$value['sg_xds']/$value['sg']) : '';
            //总计
            $returnData['合计']['qdmc'] = '合计';
            $returnData['合计']['xp_zl'] += $value['xp_zl'];
            $returnData['合计']['xds'] += $value['xds'];
            $returnData['合计']['xdje'] += $value['xdje'];
            $returnData['合计']['xdlv'] = sprintf("%.2f",$returnData['合计']['xdje']/$returnData['合计']['xp_zl']);
            $returnData['合计']['xd_rj'] = sprintf("%.2f",$returnData['合计']['xdje']/$returnData['合计']['xds']);
            $returnData['合计']['sg'] += $value['sg'];
            $returnData['合计']['sg_xds'] += $value['sg_xds'];
            $returnData['合计']['sg_xdlv'] = sprintf("%.2f",$returnData['合计']['sg_xds']/$returnData['合计']['sg']);
            $returnData['合计']['sg_xdje'] += $value['sg_xdje'];
            $returnData['合计']['jxs'] += $value['jxs'];
            $returnData['合计']['jxje'] += $value['jxje'];
            $returnData['合计']['meituan'] += $value['meituan'];
            $returnData['合计']['pay_num'] += $value['pay_num'];
            $returnData['合计']['pay'] += $value['pay'];
            $returnData['合计']['xpjine'] += $value['xpjine'];
            $returnData['合计']['zyj'] += $value['zyj'];
        }
        $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));
        // 当前操作人的可操作店
        // 今天
        $this->assign('today', date('Y-m-d'));

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

}