<?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_wxstaff_cj_detail extends Report {

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

	public function getLevel(){
		return $this->level;
	}
	public function getType(){
		return $this->type;
	}
	public function getCode(){
		return $this->code;
	}
	public function data(){
		$param = input();

        $info = db('crm_s_report_form')->where('code', $param['code'])->field('code,report_name,report_class_name')->find();
        if (!$info || empty($param['code'])) {
            $this->error('没有此报表。');
        }
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');

		$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'";
		$yjStart = date('Ymd',strtotime($start));
		$yjEnd = date('Ymd',strtotime($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' ";
		if (!empty($param['order_sn'])) {
			$order_sn = $param['order_sn'];
			$whereSql .= " AND j.orderId='$order_sn'";
		}else if (!empty($param['customer_tel'])) {
			$customer_tel = $param['customer_tel'];
			$whereSql .= " AND c.customer_tel='$customer_tel'";
		}else{
			$whereSql .= " AND j.yj_paymentdate BETWEEN '$yjStart' AND '$yjEnd' ";
			//品牌
			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;
		// 先取单号 
		//$orderIdSql = 'SELECT o.orderId 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 LEFT JOIN c_jobscore j ON co.order_sn=j.orderId AND c.sales_staff=j.staffname WHERE o.id IS NOT NULL '.$whereSql.' GROUP BY j.orderId ORDER BY j.yj_paymentdate DESC LIMIT '.$pStart.', '.$limit;
		$orderIdSql = 'SELECT o.orderId FROM crm_c_customerinfo c  LEFT JOIN c_customerorder o ON c.id = o.crm_customer_id LEFT JOIN c_jobscore j ON o.orderId=j.orderId AND c.sales_staff=j.staffname WHERE o.id IS NOT NULL '.$whereSql.' GROUP BY j.orderId ORDER BY j.yj_paymentdate DESC LIMIT '.$pStart.', '.$limit;
		$allId = db()->query($orderIdSql);
		$orderIds = '';
		if (!$allId) {
			$return['orderSql'] = $orderIdSql;
			$return['msg']  = '';
			$return['code'] = 0;
			$return['data'] = [];
			$return['count']= 0;
			return json($return);
		}
		foreach ($allId as $key => $value) {
			$orderIds .= "'".$value['orderId']."',";
		}
		$orderIds = trim($orderIds,',');
		// $field='c.id,c.dj_day,c.customer_name,c.customer_tel,c.customer_wechat,c.b_name,c.consultation_type,sc.channel_info_name,c.customer_channel,c.dj_staff,c.sales_staff,co.order_sn,co.target_time,co.create_time,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,p.shop_name as pay_shop_name,j.staffname,j.yj_money,j.yj_paymentdate,t.typename';
		// $sql = 'SELECT '.$field.' FROM crm_c_customerinfo c LEFT JOIN crm_s_channel sc ON c.customer_channel_id=sc.id LEFT JOIN crm_c_customer_order co ON c.id=co.customer_id LEFT JOIN c_customerorder o ON co.order_sn = o.orderId LEFT JOIN c_paymentcontent p ON p.orderId = o.orderId LEFT JOIN c_jobscore j ON co.order_sn=j.orderId AND c.sales_staff=j.staffname AND p.id=j.yj_pyid LEFT JOIN c_paymenttype t ON t.typecode=j.yj_paytype WHERE j.orderId IN ('.$orderIds.') AND p.paymentdate BETWEEN "'.$yjStart.'" AND "'.$yjEnd.'" ORDER BY p.paymentdate DESC';

		$field='c.id,c.dj_day,c.customer_name,c.customer_tel,c.customer_wechat,c.b_name,c.consultation_type,sc.channel_info_name,c.customer_channel,c.dj_staff,c.sales_staff,o.orderId,o.targetdate,o.create_time,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,p.shop_name as pay_shop_name,j.staffname,j.yj_money,j.yj_paymentdate,t.typename,p.paytype,p.isshishou';
		$sql = 'SELECT '.$field.' FROM crm_c_customerinfo c LEFT JOIN crm_s_channel sc ON c.customer_channel_id=sc.id LEFT JOIN c_customerorder o ON c.id = o.crm_customer_id LEFT JOIN c_paymentcontent p ON p.orderId = o.orderId LEFT JOIN c_jobscore j ON o.orderId=j.orderId AND c.sales_staff=j.staffname AND p.id=j.yj_pyid LEFT JOIN c_paymenttype t ON t.typecode=j.yj_paytype WHERE o.orderId IN ('.$orderIds.') AND p.paymentdate BETWEEN "'.$yjStart.'" AND "'.$yjEnd.'" ORDER BY p.paymentdate DESC';

		$allData = db()->query($sql);
		$infoData=[];

		foreach ($allData as $k => $v) {
			$infoData[$v['orderId']]['orderId'] = $v['orderId'];
			$infoData[$v['orderId']]['customer_name'] = $v['customer_name'];
			$infoData[$v['orderId']]['customer_tel'] = $v['customer_tel'];
			$infoData[$v['orderId']]['customer_wechat'] = $v['customer_wechat'];
			$infoData[$v['orderId']]['b_name'] = $v['b_name'];
			$infoData[$v['orderId']]['consultation_type'] = $v['consultation_type'];
			$infoData[$v['orderId']]['channel_info_name'] = $v['channel_info_name'];
			$infoData[$v['orderId']]['customer_channel'] = $v['customer_channel'];
			$infoData[$v['orderId']]['order_shop_name'] = $v['order_shop_name'];
			$infoData[$v['orderId']]['pay_shop_name'] = $v['pay_shop_name'];
			$infoData[$v['orderId']]['dj_staff'] = $v['dj_staff'];
			$infoData[$v['orderId']]['sales_staff'] = $v['sales_staff'];
			$infoData[$v['orderId']]['storeconsuitant1'] = $v['storeconsuitant1'];
			$infoData[$v['orderId']]['package_name'] = $v['package_name'];

			// if ($v['typename'] == '刷卡') {
			// 	$infoData[$v['orderId']]['ddss'] += $v['yj_money'];
			// }
			// if ($v['typename'] == '现金') {
			// 	$infoData[$v['orderId']]['ddss'] += $v['yj_money'];
			// }
			// if ($v['typename'] == '网络付款') {
			// 	$infoData[$v['orderId']]['ddss'] += $v['yj_money'];
			// }
			// if ($v['typename'] == '免单') {
			// 	$infoData[$v['orderId']]['ddss'] += $v['yj_money'];
			// }
			// if ($v['typename'] == 'VIP卡') {
			// 	$infoData[$v['orderId']]['vip'] += $v['yj_money'];
			// }

			if ($v['paytype'] == 'VIP卡') {
        		$infoData[$v['orderId']]['vip'] += $v['yj_money'];
        	}

        	if ($v['isshishou'] == '实收') {
                $infoData[$v['orderId']]['ddss'] += $v['yj_money'];
            }

			$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']]['dj_day'] = date('Y-m-d',strtotime($v['dj_day']));
			$infoData[$v['orderId']]['order_start_time'] = date('Y-m-d',strtotime($v['targetdate']));
			$infoData[$v['orderId']]['o_create_time'] = $v['create_time'];
			$infoData[$v['orderId']]['pay_time'] = date('Y-m-d',strtotime($v['yj_paymentdate']));
		}
		$infoData = array_values($infoData);
		foreach ($infoData as $k => $v) {
			$infoData[$k]['key'] = $k+1;
		}

		$countSql = 'SELECT o.orderId FROM crm_c_customerinfo c LEFT JOIN c_customerorder o ON c.id = o.crm_customer_id LEFT JOIN c_jobscore j ON o.orderId=j.orderId AND c.sales_staff=j.staffname WHERE o.id IS NOT NULL '.$whereSql.' GROUP BY j.orderId';
		$infoCount = db()->query($countSql);
		$return['countSql'] = $countSql;
		$return['orderIdSql'] = $orderIdSql;
		$return['sql']  = $sql;
		$return['msg']  = '';
		$return['code'] = 0;
		$return['data'] = $infoData;
		$return['count']= count($infoCount);
		return json($return);
	}

	public function show(){
        $menu_code = strtolower(input('param.menu_code'));
        $info = db('crm_s_report_form')->where('code', $menu_code)->field('code,report_name,report_class_name')->find();
        if (!$info) {
            $this->error('没有此报表。');
        }

        $shop_code = session('shop_code');
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
		/*/ 事业部下所有可操作店
		$shopParam['staff_id'] = session('staff_id');
		$shopParam['brandclass_id'] = session('brandclass_id');
		$myShops = getShops($shopParam);
		$this->assign("myShops", $myShops);*/
		$myShops = db('c_customerorder')->field("shop_code,shop_name")->GROUP('shop_code')->select();
		$this->assign("myShops", $myShops);
		// var_dump($myShops);die;
	   	// 来源渠道
		$channel = getChannelJson($shop_code);
		$this->assign("channel", json_encode($channel));
		// crm城市	列表
		$data['type'] = 2;
		$data['shop_code']= $shop_code;
		$staCity = controller("crm/Customer", "lib")->address($data);
		$this->assign("staCity",$staCity);

		// 品牌
		$brandArr = db('crm_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();
		// 部门
		$departmentList = $mc->getDepartmentByShopcode($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->getStaffByDepartment($staffParam);
		$this->assign("djStaffList",$djStaffList);
		// 追踪人
		$salesStaffList = $mc->getStaffByDepartment($staffParam);
		$this->assign("salesStaffList",$salesStaffList);

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

        $this->assign('title', $shop[0]['shop_name'].'-'.$info['report_name']);
        $this->assign('code', $info['code']);
		$this->assign('start', date('Y-m-01'));
		$this->assign('end', date('Y-m-d'));
		return $this->fetch($display);
	}
}