<?php
/**
 * 报表实现类 石家庄-时光qqbaby定制 进店客资明细统计
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: yuanweibo 2021-07-12 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;
use app\common\lib\mcInterface;
class Sgbabt_customer_enter extends Report {

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

    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 = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));

        $starts = date('Ymd', strtotime($data['start']));
        $ends = date('Ymd', 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'=>'请选择店面');
        }

        $where['ci.consulation_shop_code'] = $shop_code;
        $where['ci.status'] = 1;
        $where['ci.is_success'] = ['<>',4];
        $where["`ci`.`".$data['type']."`"] = ['between',[$start,$end]];

        if ($data['staff_id']) {
            $where["ci.operate_id|ci.reception_id"] = $data['staff_id'];
        }

        $list = db("crm_c_customer_intostore ci")
                ->join("crm_c_customerinfo c","ci.cid=c.id",'left')
                ->join("c_customerorder o","ci.id=o.crm_into_id",'left')
                ->join('c_customerorder_servicefc fc','o.orderId=fc.orderId and fc.currentfc=1','left')
                ->join('c_paymentcontent p',"p.orderId=o.orderId","left")
                ->where($where)
                ->field("ci.*,c.baby_name,c.customer_tel,c.baby_sex,c.baby_birthday,c.ready_baby_day,c.customer_channel,c.op_signinfo,c.huoqu_num,o.orderId,o.package_name,p.isshishou,o.bargain_money")
                ->order("id desc")
                ->select();
        $return['sql'] = db()->getlastsql();
        $sum = [];
        $orderId = [];
        foreach($list as $k => $v){
            $list[$k]['age'] = $v['baby_birthday'] ? date("Y")-substr($v['baby_birthday'],0,4) : '';
            $list[$k]['ready_baby_day'] = $v['ready_baby_day'] ? substr($v['ready_baby_day'],0,10) : '';
            $list[$k]['baby_birthday'] = $v['baby_birthday'] ? substr($v['baby_birthday'],0,10) : '';

            //进店状态
            $list[$k]['is_intostores]'] = getIsIntostore($v['is_intostore']);

            $orderId[] = $v['orderId'];

            $sum['bargain_money'] += $v['bargain_money'];
            if ($v['syjd_day']) {
                $sum['sjjd'] += 1;
            }
            if ($v['orderId']) {
                $sum['ddl'] += 1;
            }
        }

        //收款表
        $pay = db('c_paymentcontent')->where("orderId","in",$orderId)->where("isshishou","实收")->where("suoshu","in","前期款','前期补款'")->group("orderId")->column("count(payment_money) as payment_money","orderId");
        $return['sql_pay'] = db()->getlastsql();

        foreach($list as $k => $v){
            $list[$k]['payment_money'] = $pay[$v['orderId']];
            $sum['payment_money'] += $pay[$v['orderId']];
        }

        //总实收业绩
        $zongyejis = 0.00;
        if (count($orderId) > 0) {
            $orderId_zyj = "'".implode(",",$orderId)."'";
            $sql_zyj = "select a.orderId,a.currentfc,a.shop_name,a.shop_code,a.paymentdate,a.payment_money,case a.payclass when 0 then '门市' when 3 then 'VIP卡充值' end as payclass,a.paytype,a.suoshu,a.isshishou,a.fundname,b.shop_name as ddshop_name,b.shop_code as ddshop_code,case b.crm_order_type when 2 then '实体' else '网络' end as crm_order_type,c.customer_channel from c_paymentcontent a join c_customerorder b on a.orderId = b.orderId join c_customerinfo c on b.customerid = c.customerid where a.paymentdate between '$starts' and '$ends' and a.shop_code in ('$shop_code') and a.isshishou='实收' and suoshu in ('前期款','前期补款') and b.crm_order_type!='2' and a.orderId in($orderId_zyj)";
            $return['sql_zyj'] = $sql_zyj;
            $zongyeji = db()->query($sql_zyj);
            foreach ($zongyeji as $key => $value) {
                if ($value['shop_code'] == $shop_code && $value['ddshop_code'] != $shop_code) {
                    $zongyejis += $value['payment_money'];
                }
            }
        }

        //并汇总总邀约进店量、总实际进店量、总成交订单量、总成交金额、总实收业绩（总实收业绩根据财务报表总进店业绩，计算规则一致，提醒门店收款分单业绩）
        $sums = "总邀约进店量:".count($list).";总实际进店量".($sum['sjjd']?:0).";总成交订单量:".($sum['ddl']?:0).";总成交金额:".($sum['total_money']?:0.00).";总实收业绩:".$zongyejis;

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($list);
        $return['data'] = $list;
        $return['sum'] = $sums;

        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,f.report_name')->find();

        $shop_code = $info['shop_code']?:session('shop_code');
        
        // 当前操作人的可操作店
        // $mc = new \app\common\lib\mcInterface;
        // $shopList = $mc->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
        // print_r($shopList);exit;

        $staff = getShopStaffs(['shop_code'=>$shop_code,'work_type'=>RECEIVE_WORK_TYPE]);
        $this->assign("staff", $staff);

        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';

        $this->assign('title', $info['report_name']);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}