<?php
/**
 * 报表实现类 郑州babypastel CBD 业绩日报表
 *
 * ============================================================================
 * 版权所有 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_yeji_day_data extends Report {
    private $level=1;
    private $type =1;
    private $code ='code1593597312';

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

        $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['end']));
        $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();

        //可操作店
        if($data['shop_code']){
            $shop_code = $data['shop_code'];
        }elseif($det['shop_code']){
            $shop_code = $det['shop_code'];
        }else{
            $shop_code = session('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.targetdate="'.$today.'" and o.shop_code="'.$shop_code.'"')
            ->whereOr('ph.photodate="'.$today.'" and ph.shop_code="'.$shop_code.'"')
            ->whereOr('sp.selectday="'.$today.'" and sp.shop_code="'.$shop_code.'"')
            ->whereOr('p.paymentdate="'.$today.'" and p.shop_code="'.$shop_code.'"')
            // ->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,o.total_money,o.storeconsuitant1,o.storeconsuitant2';
        $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')
            ->where('o.orderId','in',$allOrderIds)->where('o.targetdate',$today)
            ->order('o.targetdate')
            ->group('o.orderId')
            ->column($orderField.',fc.allfc,fc.fcguanjia','o.orderId');
        $sql1 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        // echo $sql1;die;
        foreach ($todayOrder as $key => $value) {
            $noIds .= $value['orderId'].',';
            // 计算宝宝年龄
            $age = $this->babyAge('',$value['bbithdate']);
            // 订单 日期
            $returnData[$key]['day'] = date('m-d',strtotime($value['targetdate'])).'-d';
            // 渠道
            $returnData[$key]['qd'] = $value['customer_channel'];
            // 妈妈姓名
            $returnData[$key]['name'] = $value['wname'];
            // 宝宝年龄
            $returnData[$key]['age'] = $age;
            // 妈妈电话
            $returnData[$key]['tel'] = $value['wphone'];
            if ($value['old_bargain_money']) {
                // 原套餐金额
                $returnData[$key]['ytcje'] = $value['old_bargain_money'];
                // 升级套餐金额
                $returnData[$key]['sjtcje']= $value['bargain_money']+$value['shengjimoney'];
            }else{
                $returnData[$key]['ytcje'] = $value['bargain_money'];
                $returnData[$key]['sjtcje']= '';
            }
            // 成长套拍摄剩余次数
            if ($value['allfc']>1) {
                $returnData[$key]['cztsycs'] = $value['allfc'];
            }else{
                $returnData[$key]['cztsycs'] = '';
            }
            // 新订单金额
            $returnData[$key]['xddje'] = $value['bargain_money'];
            // 客户欠款
            $returnData[$key]['qk'] = $value['nopayment_money'];
            // 订单管家  =网销门市，没有网销门市为销售门市
            $returnData[$key]['ddgj'] = $value['storeconsuitant2'] ? $value['storeconsuitant2'] : $value['storeconsuitant1'];
            // 服务管家  待提供对应的字段
            $returnData[$key]['fwgj'] = $value['fcguanjia'];
            // 订单备注
            $returnData[$key]['bz'] = $value['ordernote'];
        }
        $recTime .= microtime(true).'<br />';
        // 今日拍照客资 同一天 有可能拍照两次 所以不能使用 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')
            ->where('o.orderId','in',$allOrderIds)->where('ph.photodate',$today)
            ->order('ph.photodate')
            ->field($orderField.',ph.photodate,ph.cameraman,ph.mentor_a,ph.dresser,ph.currentfc,ph.photonote')
            ->select();
        $sql2 = db()->getLastSql();
        $recTime .= microtime(true).'<br />';
        foreach ($todayPhoto as $key => $value) {
            // 计算宝宝年龄
            $age = $this->babyAge('',$value['bbithdate']);
            // 订单 日期
            $returnData[$value['orderId']]['day'] = date('m-d',strtotime($value['photodate']));
            // 渠道
            $returnData[$value['orderId']]['qd'] = $value['customer_channel'];
            // 妈妈姓名
            $returnData[$value['orderId']]['name'] = $value['wname'];
            // 宝宝年龄
            $returnData[$value['orderId']]['age'] = $age;
            // 妈妈电话
            $returnData[$value['orderId']]['tel'] = $value['wphone'];
            if ($value['old_bargain_money']) {
                // 原套餐金额
                $returnData[$value['orderId']]['ytcje'] = $value['old_bargain_money'];
                // 升级套餐金额
                $returnData[$value['orderId']]['sjtcje']= $value['bargain_money']+$value['shengjimoney'];
            }else{
                $returnData[$value['orderId']]['ytcje'] = $value['bargain_money'];
                $returnData[$value['orderId']]['sjtcje']= '';
            }
            // 成长套拍摄剩余次数
            $allfc = db('c_customerorder_servicefc')->where('orderId',$value['orderId'])->value('allfc');
            if ($allfc>1) {
                $returnData[$value['orderId']]['cztsycs'] = $allfc-$value['currentfc'];
            }else{
                $returnData[$value['orderId']]['cztsycs'] = '';
            }
            if ($allfc>1) {
                // 成长套拍摄量
                $returnData[$value['orderId']]['cztpsl'] = 1;
            }else{
                // 单套拍摄量
                $returnData[$value['orderId']]['dtpsl'] = 1;
            }
            if ($value['phototype']=='重拍') {
                // 重拍量
                $returnData[$value['orderId']]['cpl'] = 1;
            }
            if ($value['phototype']=='补拍') {
                // 补拍量
                $returnData[$value['orderId']]['bpl'] = 1;
            }
            // 新订单金额
            $returnData[$value['orderId']]['xddje'] = $value['bargain_money'];
            // 客户欠款
            $returnData[$value['orderId']]['qk'] = $value['nopayment_money'];
            // 订单管家   =网销门市，没有网销门市为销售门市
            $returnData[$value['orderId']]['ddgj'] = $value['storeconsuitant2'] ? $value['storeconsuitant2'] : $value['storeconsuitant1'];
            // 摄影
            $returnData[$value['orderId']]['sy'] = $value['cameraman'];
            // 化妆
            $returnData[$value['orderId']]['hz'] = $value['dresser'];
            // 引导
            $returnData[$value['orderId']]['yd'] = $value['mentor_a'];
            // 服务管家
            // $returnData[$value['orderId']]['fwgj'] = '';
            // 订单 + 摄影备注
            $note = '';
            if ($value['ordernote']) {
                $note .= $value['ordernote'].'--';
            }
            if ($value['photonote']) {
                $note .= $value['photonote'];
            }
            $returnData[$value['orderId']]['bz'] = $note;
        }
        $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')
            ->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 />';
        foreach ($todaySp as $key => $value) {
            $noIds .= $value['orderId'].',';
            // 计算宝宝年龄
            $age = $this->babyAge('',$value['bbithdate']);
            // 订单 日期
            $returnData[$key]['day'] = date('m-d',strtotime($value['selectday'])).'-sp';
            // 渠道
            $returnData[$key]['qd'] = $value['customer_channel'];
            // 妈妈姓名
            $returnData[$key]['name'] = $value['wname'];
            // 宝宝年龄
            $returnData[$key]['age'] = $age;
            // 妈妈电话
            $returnData[$key]['tel'] = $value['wphone'];
            if ($value['old_bargain_money']) {
                // 原套餐金额
                $returnData[$value['orderId']]['ytcje'] = $value['old_bargain_money'];
                // 升级套餐金额
                $returnData[$value['orderId']]['sjtcje']= $value['bargain_money']+$value['shengjimoney'];
            }else{
                $returnData[$value['orderId']]['ytcje'] = $value['bargain_money'];
                $returnData[$value['orderId']]['sjtcje']= '';
            }
            // 成长套拍摄剩余次数
            $allfc = db('c_customerorder_servicefc')->where('orderId',$key)->value('allfc');
            if ($allfc>1) {
                $returnData[$key]['cztsycs'] = $allfc-$value['currentfc'];
            }else{
                $returnData[$key]['cztsycs'] = '';
            }
            // if ($allfc>1) {
            //     // 成长套拍摄量
            //     $returnData[$key]['cztpsl'] = 1;
            // }else{
            //     // 单套拍摄量
            //     $returnData[$key]['dtpsl'] = 1;
            // }
            // if ($value['phototype']=='重拍') {
            //     // 重拍量
            //     $returnData[$key]['cpl'] = 1;
            // }else if ($value['phototype']=='补拍') {
            //     // 补拍量
            //     $returnData[$key]['bpl'] = 1;
            // }
            // 新订单金额
            $returnData[$key]['xddje'] = $value['bargain_money'];
            // 客户欠款
            $returnData[$key]['qk'] = $value['nopayment_money'];

            if ($allfc>1) {
                // 选片 成长套选片量
                $returnData[$key]['czt'] = 1;
            }else{
                // 选片 单套选片量
                $returnData[$key]['dt'] = 1;
            }
            // 时光选片量
            $todaySgjn = db('c_consumptioncontent')//产品表
                ->where('orderId',$value['orderId'])
                ->where('consumption_name', 'like', '%时光胶囊%')
                ->where('servicenumber',$value['currentfc'])
                ->count();
            $returnData[$key]['sg'] = $todaySgjn ? 1 : '';
            // 返现金额 =赠送金额
            $returnData[$key]['czfx'] = db('c_consumptioncontent')//产品表
                ->where('orderId',$value['orderId'])
                ->where('servicenumber',$value['currentfc'])
                ->sum('zsmoney');
            // 选片师
            $returnData[$key]['xps'] = $value['selectman'];
            // 服务管家
            // $returnData[$key]['fwgj'] = '';
            // 订单 + 摄影 + 选片备注
            $note = '';
            if ($value['ordernote']) {
                $note .= $value['ordernote'].'--';
            }
            if ($value['photonote']) {
                $note .= $value['photonote'].'--';
            }
            if ($value['spremarks']) {
                $note .= $value['spremarks'];
            }
            $returnData[$value['orderId']]['bz'] = $note;
        }
        $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')
            ->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 />';
        foreach ($todayPay as $key => $value) {
            // 计算宝宝年龄
            $age = $this->babyAge('',$value['bbithdate']);
            // 订单 日期
            $returnData[$value['orderId']]['day'] = date('m-d',strtotime($value['paymentdate'])).'-pay';
            // 渠道
            $returnData[$value['orderId']]['qd'] = $value['customer_channel'];
            // 妈妈姓名
            $returnData[$value['orderId']]['name'] = $value['wname'];
            // 宝宝年龄
            $returnData[$value['orderId']]['age'] = $age;
            // 妈妈电话
            $returnData[$value['orderId']]['tel'] = $value['wphone'];
            if ($value['old_bargain_money']) {
                // 原套餐金额
                $returnData[$value['orderId']]['ytcje'] = $value['old_bargain_money'];
                // 升级套餐金额
                $returnData[$value['orderId']]['sjtcje']= $value['bargain_money']+$value['shengjimoney'];
            }else{
                $returnData[$value['orderId']]['ytcje'] = $value['bargain_money'];
                $returnData[$value['orderId']]['sjtcje']= '';
            }
            // 成长套拍摄剩余次数
            $allfc = db('c_customerorder_servicefc')->where('orderId',$value['orderId'])->value('allfc');
            if ($allfc>1) {
                $returnData[$value['orderId']]['cztsycs'] = $allfc;
            }else{
                $returnData[$value['orderId']]['cztsycs'] = '';
            }
            // 新订单金额
            $returnData[$value['orderId']]['xddje'] = $value['bargain_money'];
            // 客户欠款
            $returnData[$value['orderId']]['qk'] = $value['nopayment_money'];
            // 加服装金额
            if ($value['fundname']=='加服装金额') {
                $returnData[$value['orderId']]['jfzje'] += $value['pay'];
            }
            // 续订金额
            if ($value['fundname']=='续订金额') {
                $returnData[$value['orderId']]['xdje'] += $value['pay'];
            }
            // 加选金额
            if ($value['fundname']=='加选金额') {
                $returnData[$value['orderId']]['jxje'] += $value['pay'];
            }
            // 时光金额
            if ($value['fundname']=='时光金额') {
                $returnData[$value['orderId']]['sgje'] += $value['pay'];
            }
            // 客户还欠款
            if ($value['suoshu']=='前期补款' || $value['suoshu']=='后期补款') {
                $returnData[$value['orderId']]['hqk'] += $value['pay'];
            }
            // 充值金额
            if ($value['payclass']==3) {
                $returnData[$value['orderId']]['czje'] += $value['pay'];
            }
            // 客户退款(一)
            if ($value['pay']<0) {
                $returnData[$value['orderId']]['tk'] = $value['pay'];
            }
            // 实收 金额 包含充值
            if ($value['isshishou']=='实收') {
                $returnData[$value['orderId']]['ssje'] += $value['pay'];
            }
            // 付款方式
            $returnData[$value['orderId']][$value['paytype']] += $value['pay'];
            $returnData['合计'][$value['paytype']] += $value['pay'];

            // 应收金额  =订单金额
            $returnData[$value['orderId']]['ysje'] = $value['total_money'];

            // if ($allfc>1) {
            //     // 选片 成长套选片量
            //     $returnData[$value['orderId']]['czt'] = 1;
            // }else{
            //     // 选片 单套选片量
            //     $returnData[$value['orderId']]['dt'] = 1;
            // }
            /*
            // 订单管家
            $returnData[$value['orderId']]['ddgj'] = '';
            // 选片师
            $returnData[$value['orderId']]['xps'] = $todayPayOther[$value['orderId']]['selectman'];
            // 摄影
            $returnData[$value['orderId']]['sy'] = $todayPayOther[$value['orderId']]['cameraman'];
            // 化妆
            $returnData[$value['orderId']]['hz'] = $todayPayOther[$value['orderId']]['dresser'];
            // 引导
            $returnData[$value['orderId']]['yd'] = $todayPayOther[$value['orderId']]['mentor_a'];
            // 服务管家
            $returnData[$value['orderId']]['fwgj'] = '';
            */
            // 订单 + 摄影 + 选片 + 收款备注
            $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['orderId']]['bz'] = $note;
        }
        $recTime .= microtime(true).'<br />';
        foreach ($returnData as $key => $value) {
            $returnData['合计']['day'] = '合计';
            $returnData['合计']['xdje'] += $value['xdje'];
            $returnData['合计']['xddje'] += $value['xddje'];
            $returnData['合计']['jfzje'] += $value['jfzje'];
            $returnData['合计']['cztsycs'] += $value['cztsycs'];
            $returnData['合计']['sjtcje'] += $value['sjtcje'];
            $returnData['合计']['ytcje'] += $value['ytcje'];

            $returnData['合计']['ysje'] += $value['ysje'];
            $returnData['合计']['czje'] += $value['czje'];
            $returnData['合计']['czfx'] += $value['czfx'];
            $returnData['合计']['ssje'] += $value['ssje'];
            $returnData['合计']['cztpsl'] += $value['cztpsl'];
            $returnData['合计']['dtpsl'] += $value['dtpsl'];
            $returnData['合计']['cpl'] += $value['cpl'];
            $returnData['合计']['bpl'] += $value['bpl'];
            $returnData['合计']['czt'] += $value['czt'];
            $returnData['合计']['dt'] += $value['dt'];
            $returnData['合计']['sg'] += $value['sg'];
            $returnData['合计']['jxje'] += $value['jxje'];
            $returnData['合计']['sgje'] += $value['sgje'];
            $returnData['合计']['qk'] += $value['qk'];
            $returnData['合计']['hqk'] += $value['hqk'];
            $returnData['合计']['tk'] += $value['tk'];
        }
        $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)")
            // ->where('typecode','实收')
            ->field('id,typename')->select();
        // echo db()->getLastSql();die;
        $this->assign('allPayType', $allPayType);
        $this->assign('allPayCount', count($allPayType));
        //事业部下店面
        $mc = new \app\common\lib\mcInterface;
        $shopList = $mc->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
        $this->assign('shopList',$shopList);
        $this->assign("shop_code", $info['shop_code']?$info['shop_code']:session('shop_code'));
        // 今天
        $this->assign('today', date('Y-m-d'));
        return $this->fetch($display);
    }
    // 计算宝宝年龄
    public function babyAge($today,$baby_birthday){
        $age = '';
        if (!$today) {
            $today = date('Y-m-d',time());
        }
        if ($baby_birthday) {
            $birthdayY = date('Y',strtotime($baby_birthday));
            $todayY = date('Y',strtotime($today) );
            if ( $todayY>$birthdayY ) {
                $age = $todayY-$birthdayY.'岁';
            }else{
                $birthdayM = date('m',strtotime($baby_birthday));
                $todayM = date('m',strtotime($today) );
                if ($todayM>$birthdayM) {
                    $age = $todayM-$birthdayM.'个月';
                }else{
                    $birthdayD = date('d',strtotime($baby_birthday));
                    $todayD = date('d',strtotime($today) );
                    $age = $todayD-$birthdayD.'天';
                }
            }
        }
        return $age;
    }

}