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

class Xaf_channel_fact_data extends Report {

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

    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();
        $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,f.report_name')->find();
        $shop_code = $det['shop_code'];
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        if($data['club_name']){
            $club = [
                0=>['club_name'=>$data['club_name']]
            ];
            $where['c.club_name'] = $data['club_name'];
            $clubext = '';
        }else{
            $club = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
            $clubext = 'c.club_name is not null or c.club_name <> \'\'';
        }

        $where['c_from'] = 1;
        $where['is_status'] = 1;
        $where['c.shop_code'] = $shop_code;
        $where['p.paytype'] = ['<>','VIP卡'];
        /*
        if($data['channel_name']){
            $channel = [
                0=>['channel_name'=>trim($data['channel_name'])]
            ];
            $where['c.customer_channel'] = trim($data['channel_name']);
        }else{
            $findSql = ' FIND_IN_SET("'.$shop_code.'",share_shops) ';
            $channel = db('crm_s_channel')->where($findSql)->where('sign_name','会所类')->order('order_sort')->select();
            $where['c.customer_channel'] = ['in',array_column($channel,'channel_name')];
        }*/


        $day = '';
        if(!$data['month']){
            return array('code'=>99,'msg'=>'请选择月份');
        }else{
            $month = getthemonth($data['month']);
            $where['p.paymentdate'] = ['between',[date('Ymd',strtotime($month[0])),date('Ymd',strtotime($month[1]))]];
            $day = getDates($month[0],$month[1]);
        }
        $info= db('crm_c_customerinfo')->alias('c')->join('c_customerorder o','c.customer_number=o.crm_customer_number','left')
            ->join('c_paymentcontent p','o.orderId=p.orderId','left')
            ->where('p.shop_name','in',["爱婴总部","爱婴一部","爱婴二部","爱婴三部"])
            ->where($where)
            ->where($clubext)
            ->field('c.club_name,p.paymentdate,sum(p.payment_money)as fact')
            ->group('c.club_name,p.paymentdate')
            ->select();
        $sqllog['huisuo'] = db()->getLastSql();
        $ret = [];
        foreach($info as $k=>$v){
            $ret[$v['club_name']][$v['paymentdate']] = $v['fact'];
        }

        $title = [];
        $m = date('n',strtotime($data['month']));
        array_unshift($title,'会所',$m.'月全月');
        $new_days = [];
        foreach($day as $k=>$v){
            array_push($title,date('j',strtotime($v)));
            array_push($new_days,date('Ymd',strtotime($v)));
        }
        $return = [];
        array_push($return,$title);
        $hos_total = [];
        $hos_total[] = '会所类实收合计';
        $hos_total_fact = '';
        $day_total = [];
        foreach($club as $k=>$v){
            $arr = [];
            $arr[] = $v['club_name'];
            $arr[] = '';
            $total = '';
            $hos_total[1] = '';
            foreach($new_days as $kk=>$vv){
                $arr[] = $ret[$v['club_name']][$vv] ? $ret[$v['club_name']][$vv] : '';
                $total += $ret[$v['club_name']][$vv];
                $day_total[$vv] += $ret[$v['club_name']][$vv];
            };

            $arr[1] = $total ? $total : '';
            $hos_total_fact += $total;
            //会所类分组
            array_push($return,$arr);
        }


        $hos_total[1] = $hos_total_fact;
        foreach($new_days as $k=>$v){
            $hos_total[] = $day_total[$v] ? $day_total[$v] : '';
        }
        //会所类合计
        array_push($return,$hos_total);
        /**----------------其他实收统计----------------------*/
        $club_name = '';
        foreach($club as $k=>$v){
            $club_name .= '"'.$v['club_name'].'",';
        }
        $sql = 'c.club_name is null or c.club_name not in ('.trim($club_name,',').')';
        $other= db('crm_c_customerinfo')->alias('c')->join('c_customerorder o','c.customer_number=o.crm_customer_number','left')
            ->join('c_paymentcontent p','o.orderId=p.orderId','left')
            ->where('c.c_from',1)
            ->where('p.paytype','<>','VIP卡')
            ->where('p.shop_name','in',["爱婴总部","爱婴一部","爱婴二部","爱婴三部"])
            ->where('c.is_status',1)
            ->where('c.shop_code',$shop_code)
            ->where('p.paymentdate','between',[date('Ymd',strtotime($month[0])),date('Ymd',strtotime($month[1]))])
            ->where($sql)
            ->group('p.paymentdate')
            ->column('sum(p.payment_money)as fact,c.club_name','p.paymentdate');
        $sqllog['qita'] = db()->getLastSql();
        $other_total[] = '其它实收统计';
        $other_total[] = array_sum(array_column($other,'fact'));
        foreach($new_days as $k=>$v){
            $other_total[] = $other[$v]['fact'] ? $other[$v]['fact'] : '';
        }
        array_push($return,$other_total);
        /**----------------其他实收统计----------------------*/
        //剃发
        /*$tifa[] = '剃发实收';
        $tifa[] = '';
        foreach($new_days as $k=>$v){
            $tifa[] = '';
        }
        array_push($return,$tifa);*/
        //实收总计
        $fact[] = '实收总计';
        $fact[] = $hos_total_fact+array_sum(array_column($other,'fact'));
        foreach($new_days as $k=>$v){
            $fact[] = $other[$v]['fact']+$day_total[$v]>0 ? $other[$v]['fact']+$day_total[$v] : '';
        }
        array_push($return,$fact);

        //老卡消费合计
        $ka[] = 'VIP卡';
        $vip= db('crm_c_customerinfo')->alias('c')->join('c_customerorder o','c.customer_number=o.crm_customer_number','left')
            ->join('c_paymentcontent p','o.orderId=p.orderId','left')
            ->where('c.c_from',1)
            ->where('p.paytype','VIP卡')
            ->where('p.shop_name','in',["爱婴总部","爱婴一部","爱婴二部","爱婴三部"])
            ->where('c.is_status',1)
            ->where('c.shop_code',$shop_code)
            ->where('p.paymentdate','between',[date('Ymd',strtotime($month[0])),date('Ymd',strtotime($month[1]))])
            ->group('p.paymentdate')
            ->column('sum(p.payment_money)as fact,c.club_name','p.paymentdate');
        $sqllog['vip'] = db()->getLastSql();
        $ka[] = array_sum(array_column($vip,'fact'));
        foreach($new_days as $k=>$v){
            $ka[] = $vip[$v]['fact'] ? $vip[$v]['fact'] : '';
        }
        array_push($return,$ka);
        $returnData['code'] = 0;
        $returnData['msg'] = '';
        $returnData['count'] = count($return);
        $returnData['data'] = $return;
        $returnData['len'] = count($title);
        $returnData['sql'] = $sqllog;
        return json($returnData);
    }

    public function show(){
        $code = $this->getCode();
        /*
        $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();

        $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');
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        /*
        $findSql = ' FIND_IN_SET("'.$info['shop_code'].'",share_shops) ';
        $channel = db('crm_s_channel')->where($findSql)->where('sign_name','会所类')->order('order_sort')->select();
        $this->assign('channel', $channel);
        */

        $club_data = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
        $this->assign('club_data',$club_data);

        $this->assign('shop_code', $info['shop_code']);
        $this->assign('title', $shop[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}