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

class Hs_customer_data extends Report {

    private $level=1;
    private $type=1;
    private $code='code﻿1592535420';

    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);
        $param = input();

      	//医拍摄影师
      	if($param['club_name']){
      		$where['i.club_name'] = $param['club_name'];
            $clubWhere['club_name'] = $param['club_name'];
      	}

      	$start = date('Y-m-d 00:00:00', $param['start']?strtotime($param['start']):time());
        $end = date('Y-m-d 23:59:59', $param['end']?strtotime($param['end']):time());
        /*
        $sql = "";
		$sql.= " sum(i.is_status = 1 and i.c_from = 1) as mkz ";
		$sql.= ",sum(i.is_status = 1 and i.c_from = 1 and `l`.`status` in (2,4) and `l`.`status` in (1,3)) as yyl ";

        $mkz = db('crm_c_customerinfo')->alias("i")
        		->join("crm_l_pc_log l","i.id=l.cid","left")
        		->where("i.dj_day between '$start' and '$end'")
		        ->where("i.add_shop_code",$param['shop_code'])
		        //->where("is_status=1 and c_from = 1")
		        ->where($where)
		        ->group('i.club_name')
		        ->column($sql,'i.club_name');
        $querysql['mkz'] = db()->getLastSql();
		//实收金额 是否去 c_payment_content 表 类型 payclass = 0 门市的 payment_money 总金额
		// $psql = " ";
		// $psql.= " sum(c.id) as psl,";
		// $psql.= " sum(p.payment_money and payclass=0) as ss";
		// $list = db('crm_c_customerinfo')->alias("i")
		// 		->join("crm_l_pc_log l","i.id=l.cid","left")
		// 		->join("c_customerorder c","l.id=c.crm_visit_id","left")
        //   	->where("i.dj_day between '$start' and '$end'")
		//         ->where("i.add_shop_code",$param['shop_code'])
		//         //->where("is_status=1 and c_from = 1")
		//         ->where($where)
		//         ->group('i.club_name')
		//         ->column($sql,'i.club_name');
		$psql = " ";
		$psql.= " sum(i.is_status = 1 and i.c_from = 1 and `l`.`status` in (2,3)) as psl ";
		$psql.= ",sum(l.status = 2) as cjl ";
		$psql.= ",sum(c.payment_money) as ss";
		$list = db('crm_c_customerinfo')->alias("i")
        		->join("crm_l_pc_log l","i.id=l.cid","left")
        		->join("c_customerorder c","l.id=c.crm_visit_id","left")
        		->where("i.dj_day between '$start' and '$end'")
		        ->where("i.add_shop_code",$param['shop_code'])
		        //->where("is_status=1 and c_from = 1")
		        ->where($where)
		        ->group('i.club_name')
		        ->column($psql,'i.club_name');
        $querysql['list'] = db()->getLastSql();
        //*/


        $newlist = db('crm_c_customerinfo')->alias("i")
                ->join("crm_l_pc_log l","i.id=l.cid","left")
                ->join("c_customerorder o","l.id=o.crm_visit_id","left")
                ->join("c_paymentcontent p","p.orderId = o.orderId and p.currentfc = 1","left")
                ->field('i.id,i.club_name,l.id pc_id,l.status pc_status,o.orderId,o.bargain_money,o.yixiaoshishou,o.payment_money order_payment_money,p.payclass,p.payment_money,p.currentfc,p.isshishou')
                ->where("i.dj_day between '$start' and '$end'")
                ->where("i.add_shop_code",$param['shop_code'])
                //->where("is_status=1 and c_from = 1")
                ->where($where)
                ->where("length(ifnull(i.club_name,'')) > 0")
                ->where('i.dj_day',['between',[$start,$end]])
                ->where('i.is_status = 1 and i.c_from = 1')
                ->select();
        $querysql['new'] = db()->getLastSql();
        //*/
        $mkz1 = [];//毛客资 该渠道获取的客资总数量
        $yyl1 = [];//预约量 提报预约上门的客户量
        $psl1 = [];//拍摄量 实际上门拍摄量
        $cjl1 = [];//成交量 一销为零且储值为零的客户量
        $ddl1 = [];//订单量 一销不为零的客户量
        $ddyxze1 = [];//订单一销总额
        $czl1 = [];//储值量
        $czze1 = [];//储值总额
        $zss1 = [];//总实收
        foreach ($newlist as $key => $value) {
            if(!in_array($value['id'], $mkz1[$value['club_name']])){
                $mkz1[$value['club_name']][] = $value['id'];
            }
            if($value['pc_status'] != 99 && !in_array($value['pc_id'], $yyl1[$value['club_name']])){
                $yyl1[$value['club_name']][] = $value['pc_id'];
            }
            if(in_array($value['pc_status'], [2,3])&& !in_array($value['pc_id'], $psl1[$value['club_name']])){
                $psl1[$value['club_name']][] = $value['pc_id'];
            }
            if(
                $value['orderId'] 
                && ($value['yixiaoshishou'] > 0 || ($value['payclass'] == 3 && $value['payment_money'] > 0))
                && !in_array($value['orderId'], $cjl1[$value['club_name']])
            ){
                $cjl1[$value['club_name']][] = $value['orderId'];
            }
            if(
                $value['orderId'] 
                && $value['yixiaoshishou'] > 0
                && !in_array($value['orderId'], $ddl1[$value['club_name']])
            ){
                $ddl1[$value['club_name']][] = $value['orderId'];
            }

            if(
                $value['orderId'] 
                && !array_key_exists($value['orderId'], $ddyxze1[$value['club_name']])
            ){
                $ddyxze1[$value['club_name']][$value['orderId']] = $value['bargain_money'];
            }

            if(
                $value['orderId'] 
                && ($value['payclass'] == 3 && $value['payment_money'] > 0)
                && !in_array($value['orderId'], $czl1[$value['club_name']])
            ){
                $czl1[$value['club_name']][] = $value['orderId'];
            }

            if(
                $value['orderId'] 
                && ($value['payclass'] == 3 && $value['payment_money'] > 0)
                // && !array_key_exists($value['orderId'], $czze1[$value['club_name']])
            ){
                $czze1[$value['club_name']][$value['orderId']] += $value['payment_money'];
            }

            if(
                $value['orderId'] 
                && ($value['isshishou'] == '实收' && $value['payment_money'] > 0)
                // && !array_key_exists($value['orderId'], $zss1[$value['club_name']])
            ){
                $zss1[$value['club_name']][$value['orderId']] += $value['payment_money'];
            }
        }
        unset($newlist);
		$club_data = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->where($clubWhere)->select();
		$data = [];
		foreach($club_data as $key=>$value){
			//$data[$key] = array_merge($mkz[$value['club_name']],$list[$value['club_name']]);
            $data[$key]['club_name'] = $value['club_name']?$value['club_name']:'';
            /*
			
            $data[$key]['mkz'] = $mkz[$value['club_name']]['mkz']?$mkz[$value['club_name']]['mkz']:0;
            $data[$key]['yyl'] = $mkz[$value['club_name']]['yyl']?$mkz[$value['club_name']]['yyl']:0;
            $data[$key]['psl'] = $list[$value['club_name']]['psl']?$list[$value['club_name']]['psl']:0;
            $data[$key]['cjl'] = $list[$value['club_name']]['cjl']?$list[$value['club_name']]['cjl']:0;
            $data[$key]['ss'] = $list[$value['club_name']]['ss']?$list[$value['club_name']]['ss']:0;
            */
            $data[$key]['cjl'] = count($cjl1[$value['club_name']]);
            $data[$key]['psl'] = count($psl1[$value['club_name']]);
            $data[$key]['yyl'] = count($yyl1[$value['club_name']]);
            $data[$key]['mkz'] = count($mkz1[$value['club_name']]);
            $data[$key]['ddl'] = count($ddl1[$value['club_name']]);
            $data[$key]['ddyxze'] = 0;
            foreach ($ddyxze1[$value['club_name']] as $v) {
                $data[$key]['ddyxze'] += $v;
            }
            $data[$key]['czl'] = count($czl1[$value['club_name']]);
            $data[$key]['ss'] = 0;
            $data[$key]['czze'] = 0;
            foreach ($zss1[$value['club_name']] as $v) {
                $data[$key]['ss'] += $v;
            }
            foreach ($czze1[$value['club_name']] as $v) {
                $data[$key]['czze'] += $v;
            }
		}
        $arr = [];
        $arr['club_name'] = '总计';
        foreach($data as $key=>$value){

            $arr['mkz'] += $value['mkz'];
            $arr['yyl'] += $value['yyl'];
            $arr['psl'] += $value['psl'];
            $arr['cjl'] += $value['cjl'];
            $arr['ddl'] += $value['ddl'];
            $arr['ddyxze'] += $value['ddyxze'];
            $arr['czl'] += $value['czl'];
            $arr['ss'] += $value['ss'];
            $arr['czze'] += $value['czze'];
        }

        array_push($data,$arr);

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($data);
        $return['data'] = $data;
        $return['sql'] = $querysql;
        // $return['czl'] = $czl1;
        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();

        $this->assign('yestoday',date("Y-m-d",time()));

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

        $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']);
        $this->assign('shop_code',$info['shop_code']);
        return $this->fetch($display);
    }

}