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

class Mkss_staff_data extends Report {

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

	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['day_type']=='dj_day') {
			$day_type = 'dj_day';
		}else if ($data['day_type']=='last_trackday') {
			$day_type = 'last_trackday';
		}else{
			$day_type = 'last_trackday';
		}

		$where['c.is_status'] = 1;
		$where['c.c_from'] = 1;
		// 消费类型
		if ($data['consultation_type']) {
			$where['c.consultation_type'] = ['in',$data['consultation_type']];
		}
		// 渠道
		if ($data['channel']) {
			$where['c.customer_channel'] = ['in',$data['channel']];
		}
		// 员工类型
		if ($data['staff_type']=='dj_staff') {
			$group = 'dj_staff_id';
			if ($data['dj_staff']) {
				$staffs = $data['dj_staff'];
			}else{
				$allStaffs = db('crm_c_customerinfo')->alias('c')
					->where('c.'.$day_type,'between',[$start,$end])
					->where($where)->where('add_shop_code',$shop_code)
					->where('dj_staff_id','>',0)
					->group('dj_staff_id')
					->field('dj_staff_id')->select();
				$staffs = [];
				foreach ($allStaffs as $key => $value) {
					array_push($staffs, $value['dj_staff_id']);
				}
			}
			$sql = 'c.dj_staff as staff,c.dj_department_name as department_name,';
			$fieldO = 'c.dj_staff as staff,c.dj_staff_id as staff_id,c.op_signinfo,o.total_money,o.bargain_money';
			$fieldP = 'c.dj_staff as staff,c.dj_staff_id as staff_id,p.payment_money';
			$where['c.dj_staff_id'] = ['in',$staffs];
			$where['c.add_shop_code'] = $shop_code;
		}else{
			$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];
			$where['c.shop_code'] = $shop_code;
		}

		$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';// 不再追踪
		$sql .= ',sum(c.'.$day_type.' between "'.$start.'" and "'.$end.'" and c.op_signinfo="进店") as jd';// 追踪标记为：进店
		// 客资基本数据
		$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')
			->join('c_consumptioncontent cc','cc.orderId=o.orderId and cc.id is not null','left')
			->where($where)->where('cc.sorting',0)->where('cc.servicenumber','1')
			// ->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]['jd']   = $info[$v]['jd'] ? $info[$v]['jd'] : 0;
			$returnData[$k]['ddl']  = $orderData[$v]['order'] ? $orderData[$v]['order'] : 0;
			$returnData[$k]['total']= $orderData[$v]['total'] ? (double)sprintf('%.2f',$orderData[$v]['total']) : '0.00';
			$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.00%';
			$returnData[$k]['wxrate'] = $info[$v]['wx'] ? sprintf('%.2f',$info[$v]['wx']/$info[$v]['mkz']*100).'%' : '0.00%';
			$returnData[$k]['ddrete'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0.00%';
			$returnData[$k]['lsrate'] = $info[$v]['bzzz'] ? sprintf('%.2f',$info[$v]['bzzz']/$info[$v]['mkz']*100).'%' : '0%';
			
			$returnData[$k]['jdddrate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$orderData[$v]['order']*100).'%' : '0.00%';
			$returnData[$k]['mkzrate']  = $orderData[$v]['inorder'] ? sprintf('%.2f',$orderData[$v]['inorder']/$info[$v]['mkz']*100).'%' : '0.00%';
			$returnData[$k]['mkddrate'] = $orderData[$v]['order'] ? sprintf('%.2f',$orderData[$v]['order']/$info[$v]['mkz']*100).'%' : '0.00%';
			$returnData[$k]['yxddrate'] = $orderData[$v]['order'] ? sprintf('%.2f',$orderData[$v]['order']/$info[$v]['yx']*100).'%' : '0.00%';
			$returnData[$k]['moneyrate']= $orderData[$v]['total'] ? (double)sprintf('%.2f',$orderData[$v]['total']/$orderData[$v]['order']) : '0.00';
			// 总计
			$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'];
		}
		$arr['department'] = '';
		$arr['staff']  = '总计';
		$arr['yxrate'] = $arr['yxkz'] ? sprintf('%.2f',$arr['yxkz']/$arr['mkz']*100).'%' : '0.00%';
		$arr['wxrate'] = $arr['wxkz'] ? sprintf('%.2f',$arr['wxkz']/$arr['mkz']*100).'%' : '0.00%';
		$arr['ddrete'] = $arr['ddkz'] ? sprintf('%.2f',$arr['ddkz']/$arr['mkz']*100).'%' : '0.00%';
		$arr['lsrate'] = $arr['lskz'] ? sprintf('%.2f',$arr['lskz']/$arr['mkz']*100).'%' : '0.00%';

		$arr['jdddrate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['ddl']*100).'%' : '0.00%';
		$arr['mkzrate']  = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0.00%';
		$arr['mkddrate'] = $arr['ddl'] ? sprintf('%.2f',$arr['ddl']/$arr['mkz']*100).'%' : '0.00%';
		$arr['yxddrate'] = $arr['ddl'] ? sprintf('%.2f',$arr['ddl']/$arr['yxkz']*100).'%' : '0.00%';
		$arr['moneyrate']= (double)$arr['total'] ? sprintf('%.2f',$arr['total']/$arr['ddl']) : '0.00';
		$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'];
				array_push($djStaffs, $djTemp);
				unset($djTemp);
				// 追踪人
				if (strstr($v['work_types'],(string)RECEIVE_WORK_TYPE)) {
					$salesTemp['staff_id'] = $v['id'];
					$salesTemp['staff_name'] = $v['staffname'];
				}
				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);
	}

}