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

class Qqbaby_cj_detail_data extends Report {

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

	public function getLevel(){
		return $this->level;
	}
	public function getType(){
		return $this->type;
	}
	public function getCode(){
		return $this->code;
	}
	public function data(){
		/*
		if($ipnut){
			input();
		}
		if(empty($data['brandclass_id'])){
			if(!in_array(session('staff_id'),explode(',',config('show_all_ids')))){
				$return = ['code' => 200, 'msg' => '没有查看集团权限', 'count' => 0, 'data' => ''];
				return json($return);
			}
		}
		set_time_limit(0);
		*/
		$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();
		$shop_code = $info['shop_code'] ? $info['shop_code'] : session('shop_code');

		$param = input();

		$page = input("page")?input("page"):1;
		$limit = input("limit")?input("limit"):20;
		//-------查询条件---------//
		//时间 
		$start = $param['start'] ? $param['start'] : date('Y-m-d',strtotime());
		$end = $param['end'] ? $param['end'] : date('Y-m-d',strtotime());
		// $whereSql = " AND c.c_from=1 AND c.is_status=1 AND c.shop_code='$shop_code' AND c.dj_day BETWEEN '$start' AND '$end'";
		$whereSql = " AND c.c_from=1 AND c.is_status=1 AND c.dj_staff_id IS NOT NULL AND c.sales_staff_id IS NOT NULL AND c.shop_code='$shop_code' AND co.target_time BETWEEN '$start' AND '$end'";
		if ($param['order_sn']) {
			$order_sn = $param['order_sn'];
			$whereSql .= " AND co.order_sn='$order_sn'";
		}else if ($param['customer_tel']) {
			$order_sn = $param['customer_tel'];
			$whereSql .= " AND c.customer_tel='$customer_tel'";
		}else{
			//品牌
			if($param['b_id']){
				$bid = $param['b_id'];
				$whereSql .= " AND c.b_id=$bid";
			}
			//消费类型
			if($param['consultation_type_id']){
				// $where['c.consultation_type_id'] = $param['consultation_type_id'];
				$consultation_type_id = $param['consultation_type_id'];
				$whereSql .= " AND c.consultation_type_id=$consultation_type_id";
			}
			//市
			if($param['city']){
				// $where['c.city_id'] = $param['city'];
				$city_id = $param['city'];
				$whereSql .= " AND c.city_id=$city_id";
			}
			//渠道
			if($param['channel']){
				// $where['c.customer_channel'] = ['in', $param['channel']];
				$channelArr = explode(',',$param['channel']);
				$channelstr = '';
				foreach ($channelArr as $k => $v) {
					$channelstr .= "'".$v."',";
				}
				$channelstr = trim($channelstr,',');
				$whereSql .= " AND c.customer_channel IN ($channelstr)";
			}
			//推广
			if($param['dj_staff']){
				// $where['c.dj_staff_id'] = ['in',$param['dj_staff']];
				$djStaffArr = $param['dj_staff'];
				$djStaffStr = '';
				foreach ($djStaffArr as $k => $v) {
					$djStaffStr .= $v.',';
				}
				$djStaffStr = trim($djStaffStr,',');
				$whereSql .= " AND c.dj_staff_id IN ($djStaffStr)";
			}
			//网销
			if($param['sales_staff']){
				// $where['c.sales_staff_id'] = ['in',$param['sales_staff']];
				$salesStaffArr = $param['sales_staff'];
				$salesStaffStr = '';
				foreach ($salesStaffArr as $k => $v) {
					$salesStaffStr .= $v.',';
				}
				$salesStaffStr = trim($salesStaffStr,',');
				$whereSql .= " AND c.sales_staff_id IN ($salesStaffStr)";
			}
			// 订单店面
			if ($param['order_shop_code']) {
				// $where['o.order_shop_code'] = $param['order_shop_code'];
				$shop_code = $param['order_shop_code'];
				$whereSql .= " AND o.shop_code='$shop_code'";
			}
		}
		
		// 
		$pStart = $page*$limit-$limit;
		$field='c.id,c.dj_day,c.customer_name,c.customer_tel,c.customer_wechat,c.b_name,c.consultation_type,c.customer_channel,c.dj_staff,c.sales_staff,c.order_start_time,co.order_sn,o.orderId,o.shop_name as order_shop_name,o.storeconsuitant1,o.package_name,o.total_money,o.payment_money,o.nopayment_money,o.bargain_money,o.yixiaokakou,o.yixiaoshishou';
		$sql = 'SELECT '.$field.' FROM crm_c_customerinfo c LEFT JOIN crm_c_customer_order co ON c.id=co.customer_id LEFT JOIN nnqq_sx_erp.c_customerorder o ON co.order_sn = o.orderId WHERE o.id IS NOT NULL '.$whereSql.' LIMIT '.$pStart.', '.$limit;
		$allData = db()->query($sql);
		$infoData=[];
		$orderIds = '';
		foreach ($allData as $k => $v) {
			$infoData[$v['orderId']] = $v;
			$infoData[$v['orderId']]['key'] = $k+1;
			$orderIds .= $v['orderId'].',';
		}
		$orderIds = trim($orderIds,',');
		$orderInfos = db('c_paymentcontent')->alias('p')
			->join('c_paymenttype t', 't.typecode=p.paytype','left')
			->where('p.orderId','in',$orderIds)
			->field('p.orderId,p.payment_money,t.typename')
			->select();
		foreach ($orderInfos as $key => $v) {
			if ($v['typename'] == '刷卡') {
				$infoData[$v['orderId']]['sk'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == '现金') {
				$infoData[$v['orderId']]['xj'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == '网络付款') {
				$infoData[$v['orderId']]['wlfk'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == '免单') {
				$infoData[$v['orderId']]['md'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == 'VIP卡') {
				$infoData[$v['orderId']]['vip'] += $v['payment_money'];
			}
			if ($v['typename'] == '优惠券') {
				$infoData[$v['orderId']]['yhq'] += $v['payment_money'];
			}
		}
		$countSql = 'SELECT count(*) AS num FROM crm_c_customerinfo c LEFT JOIN crm_c_customer_order co ON c.id=co.customer_id LEFT JOIN c_customerorder o ON co.order_sn = o.orderId WHERE o.id IS NOT NULL '.$whereSql;
		$infoCount = db()->query($countSql);
		$return['countSql'] = $countSql;
		$return['sql']  = $sql;
		$return['msg']  = '';
		$return['code'] = 0;
		$return['data'] = array_values($infoData);
		$return['count']= $infoCount[0]['num'];
		return json($return);
		/*
		// 订单
		$infoData = db('c_customerinfo')->alias('c')
			->join('c_customer_order o','c.id=o.customer_id','left')
			->where($where)
			->where('o.order_sn', 'not null')
			->page($page,$limit)->order($order)
			->column('c.*,o.order_sn,o.order_amount','o.order_sn');
			// ->select();
		// echo db()->getLastSql();die;
		$orderIds = '';
		foreach ($infoData as $key => $value) {
			if($value['baby_birthday']){
				$infoData[$key]['baby_birthday'] = date('Y-m-d',strtotime($value['baby_birthday']));
			}
			$orderIds .= $value['order_sn'].',';
		}
		$orderIds = trim($orderIds,',');
		$orderInfos = db('c_customerorder','sx_erp_et')->alias('o')
			->join('c_paymentcontent p', 'p.orderId=o.orderId','left')
			->join('c_paymenttype t', 't.typecode=p.paytype','left')
			->where('o.orderId','in',$orderIds)
			->field('o.orderId,o.shop_name as order_shop_name,o.storeconsuitant1,o.package_name,o.total_money,o.payment_money,o.nopayment_money,o.bargain_money,o.yixiaokakou,yixiaoshishou,p.payment_money,t.typename')
			->select();

		foreach ($orderInfos as $k => $v) {
			$infoData[$v['orderId']]['order_shop_name'] = $v['order_shop_name'];
			$infoData[$v['orderId']]['storeconsuitant1'] = $v['storeconsuitant1'];
			$infoData[$v['orderId']]['package_name'] = $v['package_name'];
			$infoData[$v['orderId']]['total_money'] = $v['total_money'];
			$infoData[$v['orderId']]['payment_money'] = $v['payment_money'];
			$infoData[$v['orderId']]['nopayment_money'] = $v['nopayment_money'];
			$infoData[$v['orderId']]['bargain_money'] = $v['bargain_money'];
			$infoData[$v['orderId']]['yixiaoshishou'] = $v['yixiaoshishou'];
			if ($v['typename'] == '刷卡') {
				$infoData[$v['orderId']]['sk'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == '现金') {
				$infoData[$v['orderId']]['xj'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == '网络付款') {
				$infoData[$v['orderId']]['wlfk'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == '免单') {
				$infoData[$v['orderId']]['md'] += $v['payment_money'];
				$infoData[$v['orderId']]['ddss'] += $v['payment_money'];
			}
			if ($v['typename'] == 'VIP卡') {
				$infoData[$v['orderId']]['vip'] += $v['payment_money'];
			}
			if ($v['typename'] == '优惠券') {
				$infoData[$v['orderId']]['yhq'] += $v['payment_money'];
			}
		}
		
		$infoCount = db('c_customerinfo')->alias('c')
			->join('c_customer_order o','c.id=o.customer_id','left')
			// ->where($where)
			->where('o.order_sn', 'not null')
			->count();
		
		$return['code'] = 0;
		$return['msg'] = '';
		$return['count'] = $count;
		$return['data'] = $infoData;
		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();
		$shop= controller('crm/Customer','lib')->getBrands(['brandclass_id'=>$info['brandclass_id']]);
		// 事业部下所有可操作店
		$shopParam['staff_id'] = session('staff_id');
		$shopParam['brandclass_id'] = $info['brandclass_id'];
		$myShops = getShops($shopParam);
		$this->assign("myShops", $myShops);
		// var_dump($myShops);die;
	   	// 来源渠道
		$channel = getChannelJson($info['shop_code']);
		$this->assign("channel", json_encode($channel));
		// crm省	列表
		$data['type']=1;
		$data['shop_code']= $info['shop_code'] ? $info['shop_code'] : session('shop_code');
		$province=controller("crm/Customer","lib")->address($data);
		$this->assign("province",$province);
		// 只有一个省 查这个省下的城市
		if (count($province)==1) {
			$data['type'] = 2;
			$data['pid']  = $province[0]['id'];
			$staCity = controller("crm/Customer", "lib")->address($data);
			$this->assign("staCity",$staCity);
		}
		// 品牌
		$brandArr = db('s_brandset')->select();
		$this->assign('brandArr',$brandArr);
		// 消费类型
		$consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
		$this->assign("consumptionType", $consumptionType);

		$mc = new \app\common\lib\mcInterface();
		$data['shop_code']= $info['shop_code'] ? $info['shop_code'] : session('shop_code');
		// 部门
		$departmentList = $mc->getDepartmentByShopcode($data['shop_code']);
		foreach ($departmentList as $key => $value) {
			if ($value['department_name']==session('department_name')) {
				$departmentList[$key]['selected']=1;
				$departmentId = $value['id'];
			}
		}
		$this->assign("departmentList",$departmentList);
		$staffParam['department_id'] = $departmentId;
		$staffParam['get_main'] = 1;
		// 登记人
		$djStaffList = $mc->getDepartmentStaffs($staffParam);
		$this->assign("djStaffList",$djStaffList);
		// 追踪人
		$salesStaffList = $mc->getDepartmentStaffs($staffParam);
		$this->assign("salesStaffList",$salesStaffList);

		$code = $this->getCode();
		$display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
		$title = db('s_report_form')->where('code', $code)->value('report_name');
		$this->assign('title', $shop[0]['brandclass'].'-'.$title);
		$this->assign('did', $info['id']);
		$this->assign('start', date('Y-m-01'));
		$this->assign('end', date('Y-m-d'));
		return $this->fetch($display);
	}
}