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

class Mkss_wx_track_data extends Report {

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

	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']));

		//可操作店
		if($data['shop_code']){
			$shop_code = $data['shop_code'];
		}else{
			$shop_code = session('shop_code');
		}
		if(empty($shop_code)){
			return array('code'=>100,'msg'=>'请选择店面');
		}
		if ($data['getSign']=='getSign') {
			return $this->getsign($shop_code);
		}

		$where['c.is_status'] = 1;
		$where['c.c_from'] = 1;
		// 消费类型
		if ($data['consultation_type']) {
			$where['c.consultation_type'] = ['in',$data['consultation_type']];
		}
		if ($data['day_type']=='dj_day') {
			$day_type = 'dj_day';
		}else if ($data['day_type']=='last_trackday') {
			$day_type = 'last_trackday';
		}else{
			$day_type = 'last_trackday';
		}
		
		$group = 'sales_staff_id';
		if ($data['sales_staff']) {
			$staffs = $data['sales_staff'];
		}else{
			$allStaffs = db('crm_c_customerinfo')->alias('c')
				// ->where('c.'.$day_type,'between',[$start,$end])
				->where($where)->where('shop_code',$shop_code)
				->where('sales_staff_id','>',0)
				->group('sales_staff_id')
				->field('sales_staff_id')->select();
			$staffs = [];
			foreach ($allStaffs as $key => $value) {
				array_push($staffs, $value['sales_staff_id']);
			}
		}
		$sql  = 'c.sales_staff as staff,c.sales_department_name as department_name,';
		$fieldO = 'c.sales_staff as staff,c.sales_staff_id as staff_id,c.op_signinfo,o.total_money,o.bargain_money';
		$fieldP = 'c.sales_staff as staff,c.sales_staff_id as staff_id,p.payment_money';
		$where['c.sales_staff_id'] = ['in',$staffs];

		$yxconfig = db_config('yx_config') ? db_config('yx_config') : '1,5';
		$wxconfig = db_config('wx_config') ? db_config('wx_config') : '3,4';
		$ddconfig = db_config('dd_config') ? db_config('dd_config') : '2';

		$sql .= 'sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'") as mkz';
		$sql .= ',sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$yxconfig.')) as yx';
		$sql .= ',sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$wxconfig.')) as wx';
		$sql .= ',sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$ddconfig.')) as dd';
		$sql .= ',sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'" and c.is_loss=1) as bzzz';// 不再追踪
		// 客资标记
		$sign = $this->getsign($shop_code);
		if (!empty($sign)) {
			$signName = array_column($sign,'tracksign');
			foreach ($signName as $k => $v) {
				$sql .= ',sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'" and c.sign_name="'.$v.'") as '.$v;
			}
		}
		// 客资基本数据
		$info = db('crm_c_customerinfo')->alias('c')
			->where($where)
			->group($group)->column($sql, $group);
		$sql1 = db()->getLastSql();
		// 客资订单数据
		$order = db('crm_c_customerinfo')->alias('c')
			->join('c_customerorder o','c.id=o.crm_customer_id','left')
			->where($where)
			// ->where('c.'.$day_type,'between',[$start,$end])
			->where('o.targetdate','between',[date('Ymd',strtotime($start)),date('Ymd',strtotime($end))])
			->where('o.crm_customer_id','not null')->where('o.blankoutannal',0)
			->field($fieldO)->select();
		$sql2 = db()->getLastSql();
		$orderData = [];
		foreach ($order as $k => $v) {
			$orderData[$v['staff_id']]['order'] += 1;
			$orderData[$v['staff_id']]['total'] += $v['bargain_money'];
		}
		// echo $sql2;die;
		// 收款数据
		$payInfo = db('crm_c_customerinfo')->alias('c')
			->join('c_customerorder o','c.id=o.crm_customer_id','left')
			->join('c_paymentcontent p','p.orderId=o.orderId','left')
			->where($where)
			// ->where('c.'.$day_type,'between',[$start,$end])
			->where('p.paymentdate','between',[date('Ymd',strtotime($start)),date('Ymd',strtotime($end))])
			->where('o.crm_customer_id','not null')->where('o.blankoutannal',0)
			->where('p.suoshu','in',['前期款','前期补款'])
			->field($fieldP)->select();
		$payData = [];
		foreach ($payInfo as $k => $v) {
			$payData[$v['staff_id']]['fact'] += $v['payment_money'];
		}
		$sql3 = db()->getLastSql();
		foreach ($staffs as $k => $v) {
			if (!$info[$v]['staff']) {
				$newstaff = getStaffInfoById($v);
				$returnData[$k]['staff'] = $newstaff['staffname'];
				$returnData[$k]['department'] = $newstaff['department_name'];
				unset($newstaff);
			}else{
				$returnData[$k]['staff'] = $info[$v]['staff'];
				$returnData[$k]['department'] = $info[$v]['department_name'];
			}
			$returnData[$k]['mkz'] = $info[$v]['mkz'] ? $info[$v]['mkz'] : 0;
			$returnData[$k]['yxkz']= $info[$v]['yx'] ? $info[$v]['yx'] : 0;
			$returnData[$k]['wxkz']= $info[$v]['wx'] ? $info[$v]['wx'] : 0;
			$returnData[$k]['ddkz']= $info[$v]['dd'] ? $info[$v]['dd'] : 0;
			$returnData[$k]['lskz']= $info[$v]['bzzz'] ? $info[$v]['bzzz'] : 0;
			$returnData[$k]['ddl'] = $orderData[$v]['order'] ? $orderData[$v]['order'] : 0;
			$returnData[$k]['total']= $orderData[$v]['total'] ? (double)sprintf('%.2f',$orderData[$v]['total']) : '0';
			$returnData[$k]['fact'] = $payData[$v]['fact'] ? (double)sprintf('%.2f',$payData[$v]['fact']) : '0';

			$returnData[$k]['yxrate'] = $info[$v]['yx'] ? sprintf('%.2f',$info[$v]['yx']/$info[$v]['mkz']*100).'%' : '0%';
			$returnData[$k]['wxrate'] = $info[$v]['wx'] ? sprintf('%.2f',$info[$v]['wx']/$info[$v]['mkz']*100).'%' : '0%';
			$returnData[$k]['ddrete'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
			$returnData[$k]['lsrate'] = $info[$v]['bzzz'] ? sprintf('%.2f',$info[$v]['bzzz']/$info[$v]['mkz']*100).'%' : '0%';
			
			$returnData[$k]['yxddrate'] = $orderData[$v]['order'] ? sprintf('%.2f',$orderData[$v]['order']/$info[$v]['yx']*100).'%' : '0%';
			$returnData[$k]['moneyrate']= $orderData[$v]['total'] ? (double)sprintf('%.2f',$orderData[$v]['total']/$orderData[$v]['order']) : '0';

			// 总计
			$arr['mkz']   += $returnData[$k]['mkz'];
			$arr['yxkz']  += $returnData[$k]['yxkz'];
			$arr['wxkz']  += $returnData[$k]['wxkz'];
			$arr['ddkz']  += $returnData[$k]['ddkz'];
			$arr['lskz']  += $returnData[$k]['lskz'];
			$arr['ddl']   += $returnData[$k]['ddl'];
			$arr['jd']	+= $returnData[$k]['jd'];
			$arr['total'] += (double)$returnData[$k]['total'];
			$arr['fact']  += (double)$returnData[$k]['fact'];
			// 客资标记
			foreach ($signName as $key => $val) {
				$returnData[$k][$val] = $info[$v][$val];
				$arr[$val] += $returnData[$k][$val];
			}
		}
		$arr['department'] = '';
		$arr['staff']  = '总计';
		$arr['yxrate'] = $arr['yxkz'] ? sprintf('%.2f',$arr['yxkz']/$arr['mkz']*100).'%' : '0%';
		$arr['wxrate'] = $arr['wxkz'] ? sprintf('%.2f',$arr['wxkz']/$arr['mkz']*100).'%' : '0%';
		$arr['ddrete'] = $arr['ddkz'] ? sprintf('%.2f',$arr['ddkz']/$arr['mkz']*100).'%' : '0%';
		$arr['lsrate'] = $arr['lskz'] ? sprintf('%.2f',$arr['lskz']/$arr['mkz']*100).'%' : '0%';

		$arr['yxddrate'] = $arr['ddl'] ? sprintf('%.2f',$arr['ddl']/$arr['yxkz']*100).'%' : '0%';
		$arr['moneyrate']= $arr['total'] ? (double)sprintf('%.2f',$arr['total']/$arr['ddl']) : '0';
		$returnData[] = $arr;

		$return['sql1'] = $sql1;
		$return['sql2'] = $sql2;
		$return['sql3'] = $sql3;
		$return['code'] = 0;
		$return['msg'] = '';
		$return['count'] = count($returnData);
		$return['data'] = $returnData;
		return json($return);
	}

	public function show(){
		$menu_code = strtolower(input('param.menu_code'));
		$info = db('crm_s_report_form')->alias('f')->where('f.code',$menu_code)->field('f.report_class_name')->find();
		$shop_code = session('shop_code');
		// 可操作店 
		$mc = new \app\common\lib\mcInterface();
		$tempShop = $mc->getWorkShop(['staff_id'=>session('staff_id'),'brandclass_id'=>session('brandclass_id')]);
		$shopData = [];
		foreach ($tempShop as $key => $v) {
			$temp['shop_code'] = $v['shop_code'];
			$temp['shop_name'] = $v['shop_name'];
			if ($v['shop_code']==$shop_code) {
				$temp['selected'] = 1;
			}
			array_push($shopData, $temp);
			unset($temp);
		}
		$this->assign('shopData',$shopData);
		if ($shop_code) {
			$tempStaffs = $mc->getStaffInfo(['shop_code'=>$shop_code]);
			$djStaffs = [];
			$salesStaffs = [];
			foreach ($tempStaffs as $k => $v) {
				$djTemp['staff_id'] = $v['id'];
				$djTemp['staff_name'] = $v['staffname'];
				if (strstr($v['work_types'],(string)RECEIVE_WORK_TYPE)) {
					$salesTemp['staff_id'] = $v['id'];
					$salesTemp['staff_name'] = $v['staffname'];
				}
				array_push($djStaffs, $djTemp);
				unset($djTemp);
				if ($salesTemp) {
					array_push($salesStaffs, $salesTemp);
					unset($salesTemp);
				}
			}
			$this->assign('djStaffs',$djStaffs);
			$this->assign('salesStaffs',$salesStaffs);
		}

		//来源渠道
		$channel = getChannelJson($info['shop_code']);
		$this->assign("channel", json_encode($channel));
		// 消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);

		$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');
		$this->assign('title', $title);

		return $this->fetch($display);
	}
	// 客资标记(ABC) 设定
	public function getSign($param){
		$cusSign = db('crm_s_tracksign')->where('shop_code',$param)->select();
		return $cusSign;
	}
}