<?php
class pjlAction extends baseAction
{
	public $styleArr = ['pjlshop'=>'跑街令配件商入驻', 'pjlvip'=>'跑街令PC版会员', 'tixian'=>'提现'];

	/**
	 *  区域统计
	 */	
	function areaTj()
	{
		LibRule::Check('PJ00');
		$Params = mvc::$URL_PARAMS;
		//条件限制
		$dateArr=[
			'7天'=>'seven',
			'15天'=>'half',
			'30天'=>'month'
		];
		LibTpl::Set('dateArr',$dateArr);
		
		$TjDb = new LibDb (mvc::$cfg['DB']['API_TJ']);
		$OthBase = new OthBase($TjDb);
		$where = '';
		$dateCount = 0;
		if(empty($Params['range']))
		{
			switch ($Params['limit']) 
			{
				case 'half':
					$where .= sprintf(" and bar_date >= '%s'", date('Ymd', strtotime('-15 days')));
				break;
				case 'month':
					$where .= sprintf(" and bar_date >= '%s'", date('Ymd', strtotime('-30 days')));
				break;
				default:
					$Params['limit'] = 'seven';
					$where .= sprintf(" and bar_date >= '%s'", date('Ymd', strtotime('-7 days')));
				break;
			}
		}
		else
		{
			$Params['limit'] = '';
			$date=explode(' ~ ', $Params['range']);
			$where .= sprintf(" and bar_date>= '%s' and bar_date<= '%s'", date('Ymd',strtotime($date[0])), date('Ymd',strtotime($date[1])) );
		}
		
		if(!empty($Params['sys'])){
			$where .= sprintf(" and bar_sys = '%s'", LibFc::Escape($Params['sys']));
		}
		
		$lists = [];
		$res = $OthBase->get('tj_baidu_area', ['bar_area, sum(session_count_district) as scount'], $where.' group by bar_area order by sum(session_count_district) desc');
		$total = 0;
		foreach($res['data'] as $v)
		{
			$total += $v['scount'];
			$lists[] = $v;
		}
		
		foreach($lists as $k=>$v)
		{
			$v['sratio'] = sprintf("%.2f", $v['scount']/$total*100);
			$lists[$k] = $v;
		}
			
		LibTpl::Set('lists', $lists);
		LibTpl::Set('adminRule', $adminRule);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '跑街令APP统计');
		LibTpl::Put();
	}



	/**
	 * 在线公告
	 */	
	function notice()
	{
		LibRule::Check('NO01');
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		$where = '';
		$res = $PjlBase->get('pl_notice', ['*'], $where.' order by no_id desc');
		LibTpl::Set('lists', $res['data']);

		$styleArr = [
			'once'=>'仅一次',	
			'day'=>'每天提示',	
			'start'=>'启动提示',	
		];
		LibTpl::Set('styleArr', $styleArr);
		LibTpl::Set('title', '在线公告');
		LibTpl::Put();
	}


	//发布编辑公告
	function noticeSet()
	{
		LibRule::Check('NO01');
		$Params = mvc::$URL_PARAMS;
		$PjlBase = new PjlBase();
		if(!empty($_POST['no']))
		{
			$dataArr = $_POST['no'];
			$ti = explode(' ~ ', $dataArr['no_btime']);
			$dataArr['no_btime'] = strtotime($ti[0]);
			$dataArr['no_etime'] = strtotime($ti[1]);
			
			unset($dataArr['art_praise3_w']);
			if(empty($dataArr['no_id']))
			{
				unset($dataArr['no_id']);
				$dataArr['no_atime'] = time();
				$res = $PjlBase->add('pl_notice', $dataArr);
				$no_id = $res['data'];
			}
			else
			{
				$no_id = $dataArr['no_id'];
				unset($dataArr['no_atime']);
				$where .= sprintf(" and no_id=%d", $no_id);
				$PjlBase->set('pl_notice', $dataArr, $where);
			}
			LibTpl::Success('保存成功', mvc::$cfg['ADMIN_URI'].'pjl/noticeSet?no_id='.$no_id);
		}
		if(!empty($Params['no_id']))
		{
			$res = $PjlBase->get('pl_notice', ['*'], sprintf(" and no_id=%d", $Params['no_id']), true);
			$noArr = $res['data'];
			LibTpl::Set('noArr', $noArr);
		}
		$styleArr = [
			'once'=>'仅一次',	
			'day'=>'每天提示',	
			'start'=>'启动提示',	
		];
		LibTpl::Set('styleArr', $styleArr);
		LibTpl::Set('title', '编辑在线公告');
		LibTpl::Put();
	}



	/**
	 * 删除公告
	 */
	function noticeDel()
	{
		LibRule::Check('NO01');
		$PjlBase= new PjlBase();
		$Params = mvc::$URL_PARAMS;
		$res = $PjlBase->del('pl_notice', sprintf(" and no_id=%d", $Params['no_id']));
		LibFc::ajaxJsonEncode($res);
	}


	//推广历史
	function TgList()
	{
		LibRule::Check('TG03');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlBase= new PjlBase();
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and th_atime >= %d and th_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'th_txt':
				case 'tg_mobile':
					$where .= sprintf(" and %s like '%%%s%%'", $k, LibFc::Escape($v));
				break;
				case 'th_style':
				case 'th_status':
					$where .= sprintf(" and %s = '%s'", $k, LibFc::Escape($v));
				break;
            }
        }
		$table = 'tg_history join tg_user on tg_uid=th_tg_uid';
		
		$res = $PjlBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		$res = $PjlBase->get($table, ['*'], sprintf("%s  order by th_atime desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		LibTpl::Set('lists', $res['data']);

		//统计
		$statusArr = [0=>'wait', 1=>'ok', -1=>'not'];
		foreach($this->styleArr as $k=>$v)
		{
			if($k != 'tixian')
			{
				$tjArr[$k] = [
					'all'=>0, 'ok'=>0, 'wait'=>0, 'not'=>0,
					'all_money'=>'0.00', 'ok_money'=>'0.00', 'wait_money'=>'0.00', 'not_money'=>'0.00',
				];
			}
		}

		$res = $PjlBase->get($table,['th_style, th_status, COUNT(*) as count, sum(th_money) as money'] , $where.' GROUP BY th_style, th_status');
		foreach($res['data'] as $v)
		{
			$tjArr[$v['th_style']]['all'] += $v['count'];
			$tjArr[$v['th_style']]['all_money'] = sprintf('%.2f', $arr[$v['th_style']]['all_money']+ $v['money']);
			$tjArr[$v['th_style']][$statusArr[$v['th_status']]] = $v['count'];
			$tjArr[$v['th_style']][$statusArr[$v['th_status']].'_money'] = sprintf('%.2f', $v['money']);
		}
		
		foreach($tjArr as $k=>$v)
		{
			
			foreach($v as $kk=>$vv)
			{
				$tjArr['total'][$kk] += $vv;
			}
		}
		LibTpl::Set('tjArr', $tjArr);

		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		$statusArr = [
			0=>'待审核',	
			1=>'通过',
			-1=>'不通过'
		];
		LibTpl::Set('Params', $Params);
		LibTpl::Set('statusArr', $statusArr);
		LibTpl::Set('styleArr', $this->styleArr);
		LibTpl::Set('title', '推广记录');
		LibTpl::Put();
	}


	//推广统计
	function tgTj()
	{
		LibRule::Check('TG03');
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		$where = " and tml_style IN ('pjlshop', 'pjlvip')";
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'tg_mobile':
					$where .= sprintf(" and %s like '%%%s%%'", $k, LibFc::Escape($v));
				break;
            }
        }

		$where .= 'group by tml_tg_uid having count(*) > 1 order by sum(tml_change) desc';
		$table = 'tg_money_list JOIN tg_user AS a ON tg_uid = tml_tg_uid and tg_istg=1';
		$res = $PjlBase->get($table, ['a.*, count(*) as tg_count, sum(tml_change) as tml_change, 0 as tixian'], $where);
		$lists = array_column($res['data'], null, 'tg_uid');

		if(!empty($lists))
		{
			$where = sprintf(" and tml_tg_uid in (%s) and tml_style != 'tixian' group by tml_tg_uid, tml_style", implode(',', array_keys($lists)));
			$res = $PjlBase->get('tg_money_list', ['tml_tg_uid, tml_style, count(*) as tg_count, sum(tml_change) as tml_change'], $where);
			foreach($res['data'] as $v)
			{
				$lists[$v['tml_tg_uid']][$v['tml_style']] = $v;
			}
			$where = sprintf(" and tmt_status = 1 and tmt_tg_uid in (%s) group by tmt_tg_uid", implode(',', array_keys($lists)));
			$res = $PjlBase->get('tg_money_tixian', ['tmt_tg_uid, sum(tmt_moeny) as tmt_moeny'], $where);
			foreach($res['data'] as $v)
			{
				$lists[$v['tmt_tg_uid']]['tixian'] = $v['tmt_moeny'];
			}
		}
		$total = [];
		foreach($lists as $k=>$v)
		{
			$total['pjlshop_count'] += $v['pjlshop']['tg_count'];
			$total['pjlvip_count'] += $v['pjlvip']['tg_count'];
			$total['tg_count'] += $v['tg_count'];
			$total['tml_change'] += $v['tml_change'];
			$total['tixian'] += $v['tixian'];
		}
		LibTpl::Set('lists', $lists);
		LibTpl::Set('total', $total);
		LibTpl::Set('title', '推广统计');
		LibTpl::Put();
	}


	//推广提现
	function tgTixian()
	{
		LibRule::Check('TG01');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlBase= new PjlBase();
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and tmt_atime >= %d and tmt_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'th_txt':
				case 'tg_mobile':
					$where .= sprintf(" and %s like '%%%s%%'", $k, LibFc::Escape($v));
				break;
				case 'tmt_status':
					$where .= sprintf(" and %s = '%s'", $k, LibFc::Escape($v));
				break;
            }
        }
		$table = 'tg_money_tixian join tg_user on tg_uid=tmt_tg_uid';
		
		$res = $PjlBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		$res = $PjlBase->get($table, ['*'], sprintf("%s  order by tmt_id desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		LibTpl::Set('lists', $res['data']);

		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		$statusArr = [
			0=>'待处理',	
			1=>'已转账',
			-1=>'已取消'
		];
		LibTpl::Set('Params', $Params);
		LibTpl::Set('statusArr', $statusArr);
		LibTpl::Set('title', '推广提现');
		LibTpl::Put();
	}


	//提现处理
	function tgTixianSet()
	{
		LibRule::Check('TG02');
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();

		if(!empty($_POST['tmt_id']))
		{
			if(empty($_POST['tmt_txt'])) LibTpl::Error('凭证/备注不能为空');
			$setArr=[
				'tmt_pay_time'=>(!empty($_POST['tmt_pay_time'])?strtotime($_POST['tmt_pay_time']):time()),
				'tmt_txt'=>LibFc::Escape($_POST['tmt_txt']),
				'tmt_status'=>(int)$_POST['tmt_status'],
				'tmt_check'=>mvc::$cfg['LOGUSER']['urname'],
			];
			$PjlTg = new PjlTg();
			$PjlTg->checkTiXian($_POST['tmt_id'], $setArr);
			LibTpl::Success('保存成功');
		}
		$table = 'tg_money_tixian join tg_user on tg_uid=tmt_tg_uid';
		$res = $PjlBase->get($table, ['*'], sprintf(" and tmt_id=%d", $Params['tmt_id']), true);
		LibTpl::Set('txArr', $res['data']);
		$statusArr = [
			0=>'待处理',	
			1=>'已转账',
			-1=>'已取消'
		];
		LibTpl::Set('statusArr', $statusArr);
		LibTpl::Set('title', '推广提现处理');
		LibTpl::Put();
	}


	//消息推送历史
	function tsList()
	{
		LibRule::Check('TS01');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlBase= new PjlBase();
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and thi_atime >= %d and thi_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'word':
					$where .= sprintf(" and (thi_title like '%%%s%%' OR thi_txt like '%%%s%%')", LibFc::Escape($v), LibFc::Escape($v));
				break;
				case 'thi_u_id':
				case 'thi_status':
				case 'thi_style':
					$where .= sprintf(" and %s = '%s'", $k, LibFc::Escape($v));
				break;
            }
        }
		$table = 'ts_history';
		$res = $PjlBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		$res = $PjlBase->get($table, ['*'], sprintf("%s  order by thi_id desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		$listArr = [];
		foreach($res['data'] as $k=>$v)
		{
			$v['thi_style_param'] = json_decode($v['thi_style_param'] , true);
			$listArr[$k] = $v;
		}


		LibTpl::Set('lists', $listArr);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		$statusArr = [
			0=>'已提交',	
			1=>'推送完成',
			-1=>'推送失败',
			-2=>'已取消',
		];

		$checkStyleArr = [
			'pu_pro_style'=>['全车件','发动机件', '底盘件', '外观件', '电气件', '保养件'],	
			'pu_work_style'=>['工厂','贸易', '门店', '维修厂', '媒体', '个人车主', '其他'],
			'pu_work_style_search'=>['工厂','贸易', '门店', '维修厂']
		];
		LibTpl::Set('checkStyleArr', $checkStyleArr);

		//品牌
		$ComBase = new ComBase();
		$res = $ComBase->get('bc_brand', ['brand_id', 'brand_name', 'brand_code'], ' order by brand_initial');
		LibTpl::Set('brandArr', $res['data']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('statusArr', $statusArr);
		LibTpl::Set('title', '消息推送记录');
		LibTpl::Put();
	}

	//发布推送
	function tsAdd()
	{
		LibRule::Check('TS02');
		$data = [
			'style'=>$_POST['ts_style'],
			'msg'=>$_POST['msg'],
			'title'=>$_POST['title'],
			'thi_style_param'=>$_POST['uparam'],
			'thi_user'=>mvc::$cfg['LOGUSER']['urname'],
			'thi_u_id'=>mvc::$cfg['LOGUSER']['uid'],
			'thi_btime'=> $_POST['time_type'] == 1 && !empty($_POST['thi_btime']) ? strtotime($_POST['thi_btime']): 0,
		];
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('im/appPush', [], $data);
		LibFc::ajaxJsonEncode($res);
	}


	//取消或者删除推送
	function closeTs()
	{
		LibRule::Check('TS02');
		$Params = mvc::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('im/closePush', $Params);
		LibFc::ajaxJsonEncode($res);
	}

	//推送状态
	function checkPushStatus()
	{
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('im/checkPushStatus');
		LibFc::ajaxJsonEncode($res);
	}



	//需要人工完善的询价单
	function purBugLists()
	{
		LibRule::Check('JP04');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlBase= new PjlBase();
		$where = sprintf(" and pur_status = 0 and pur_pro_count = 0 and pur_atime >= %d", strtotime("-5days"));
		$table = 'pl_purchase';
		$res = $PjlBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		$res = $PjlBase->get($table, ['*'], sprintf("%s  order by pur_id desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		LibTpl::Set('lists', $res['data']);
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '待完善的询价单');
		LibTpl::Put();
	}

	//关闭询价单
    function purBugClose()
    {
        $Params = mvc::$URL_PARAMS;
        $ids = !empty($Params["purIds"])?explode(",", $Params["purIds"]):"";
        $PjlBase = new PjlBase();
        $where = sprintf(" and pur_id = %s", $ids[0]);
        $field = ['pur_status' => -1];
        $res = $PjlBase->set('pl_purchase',$field,$where);
        LibFc::ajaxJsonEncode($res);
    }

	//完善的询价单
	function purBugSet()
	{
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		if(!empty($_POST['pur_id']))
		{
			$PjlPurchase = new PjlPurchase();
			$PjlPurchase->setPurchaseProduct($_POST['pur_id'], $_POST['pro']);
			LibTpl::Success('保存成功');
		}
		$res = $PjlBase->get('pl_purchase', ['*'], sprintf(" and pur_id=%d", $Params['pur_id']), true);
		if(empty($res['data']))
			LibTpl::Success('询价单不存在！');
		LibTpl::Set('purArr', $res['data']);

		$res = $PjlBase->get('pl_purchase_product', ['*'], sprintf(" and pup_pur_id=%d", $Params['pur_id']));
		LibTpl::Set('purProArr', $res['data']);
		LibTpl::Set('title', '完善询价单');
		LibTpl::Put();
	}

	//跑街令基本统计
	function tjAny()
    {
		LibRule::Check('PJ00');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlBase= new PjlBase();
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and taa_date >= %d and taa_date <= %d", date('Ymd', strtotime($t[0])), date('Ymd', strtotime($t[1])));
				break;
				case 'taa_status':
					$where .= sprintf(" and taa_status = %d", $v);
				break;
            }
        }
		$table = 'tj_any_date';
		$res = $PjlBase->get($table, ['count(*) as count'], $where, true);
		$Page = LibPage::Show($res['data']['count'], $perPage);
		LibTpl::Set('Page', $Page);
		$res = $PjlBase->get($table, ['*'], sprintf("%s order by taa_date desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		$lists = $res['data'];
		LibTpl::Set('lists', $lists);
		
		$file = [
			'sum(taa_shop_add) as taa_shop_add',
			'sum(taa_shop_add_ok) as taa_shop_add_ok',
			'sum(taa_purchase_add) as taa_purchase_add',
			'sum(taa_offer_add) as taa_offer_add',
			'sum(taa_renmai_add) as taa_renmai_add',
			'sum(taa_purchase_call_add) as taa_purchase_call_add',
			'sum(taa_fjsy_call_add) as taa_fjsy_call_add',
		];
		$res = $PjlBase->get('tj_any_date', $file, $where, true);
		LibTpl::Set('total', $res['data']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '基本统计');
		LibTpl::Put();
    }

    //跑街令知名品牌列表
    public function famousBrandList()
    {
		LibRule::Check('ZH00');
        $Params = mvc::$URL_PARAMS;
        $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
        $where  ='';
        $keyword = !empty($Params['keyword'])?LibFc::Escape($Params['keyword']):'';
        if (!empty($keyword)) {
            $keyword = "%$keyword%";
        }
        $where .= !empty($keyword)?sprintf("and fl_show_name like '%s' or fl_database like '%s'", $keyword,$keyword):"";
        $PjlBase = new PjlBase();
        $list = $PjlBase->get("fac_lists",["*"], sprintf('%s order by fl_seq asc limit %d,%d', $where,($nowPage-1)*$perPage, $perPage ), false);
        $data = $PjlBase->get('fac_lists', ["count(*) as count"], sprintf("%s", $where), true);
        $Page = LibPage::Show($data["data"]["count"], $perPage);
        LibTpl::Set('list', $list['data']);
        LibTpl::Set('title', '知名品牌');
        LibTpl::Set("Params", $Params);
        LibTpl::Set('Page', $Page);
        LibTpl::Put();
    }

    //删除知名品牌
    public function facBrandDel()
    {
		LibRule::Check('ZH00');
        $Params = mvc::$URL_PARAMS;
        $ids = !empty($Params["fiIds"])?explode(",", $Params["fiIds"]):"";
        $fiIds = [];
        foreach ($ids as $id) {
            if (!empty($id) && is_numeric($id)) {
                $fiIds[] = $id;
            }
        }
        $PjlBase = new PjlBase();
        $res = $PjlBase->del('fac_lists', sprintf("and fl_id in (%s)", implode(",",$fiIds)));
        LibFc::ajaxJsonEncode($res);
    }

    //添加编辑知名品牌
    public function facBrandSet()
    {
		LibRule::Check('ZH00');
        $Params = mvc::$URL_PARAMS;
        $PjlBase = new PjlBase();

        //判断是否收到数据
        if (!empty($_POST))
		{
			$data = $_POST;
			$data['fl_isshow'] = (int) $data['fl_isshow'];
			$data['fl_tcd_supid'] = (int) $data['fl_tcd_supid'];
			$data['fl_shop_id'] = (int) $data['fl_shop_id'];
			$data['fl_seq'] = (int) $data['fl_seq'];
            if(!empty($data['fl_id']))
			{
                $res = $PjlBase->set('fac_lists', $data, sprintf(" and fl_id = %d", $data['fl_id']));
            }
			else
			{
				unset($data['fl_id']);
				$res = $PjlBase->add('fac_lists', $data);
				if(!empty($data['fl_tcd_supid']))
				{
					$LibYpApi = new LibYpApi();
					$LibYpApi->Get('tcd/resetFacTypLink', ['supids'=>$data['fl_tcd_supid']]);
				}
            }
            LibFc::ajaxJsonEncode($res);
        }
        if (!empty($Params["fl_id"])) {
            $res = $PjlBase->get("fac_lists", ['*'], sprintf("and fl_id = %d", LibFc::Escape($Params["fl_id"])), true);
            LibTpl::Set('facBrands', $res["data"]);
        }
        LibTpl::Put();

    }

	//重建TCD知名品牌的车型关联表
	public function resetTcdFacTypLink()
	{
		LibRule::Check('ZH00');
		$Params = mvc::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('tcd/resetFacTypLink', $Params);
		echo 'ok';
	}


	//销售明细
	function yjList()
	{
		LibRule::Check('YJ04');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlBase= new PjlBase();
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = LibFc::Escape($v);
            if($v == '') continue;
            switch($k)
            {
				case 'yl_pay_time':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and yl_pay_time >= %d and yl_pay_time < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'yl_status':
					$where .= sprintf(" and %s = %d", $k, $v);
				break;
				case 'yl_xiangmu':
					$where .= sprintf(" and %s = '%s'", $k, $v);
				break;
				case 'word':
					$where .= sprintf(" and ( yl_user like '%%%s%%' or yl_title like '%%%s%%' or yl_remark like '%%%s%%' or yl_xiangmu_des like '%%%s%%')", $v, $v, $v, $v);
				break;
				case 'yl_user':
					$where .= sprintf(" and yl_user like '%%%s%%'", $v);
				break;
				case 'remark':
					$where .= sprintf(" and yl_xiangmu_des like '%%%s%%'", $v);
				break;
            }
        }

		$table = 'bu_yeji_list';
		$res = $PjlBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		//order by FIELD(yl_status, 0, 1,-1), FROM_UNIXTIME(yl_pay_time,'%%Y%%m%%d') 
		$res = $PjlBase->get($table, ['*'], sprintf("%s order by FROM_UNIXTIME(yl_pay_time,'%%Y%%m%%d') desc, yl_id desc limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		$lists = $res['data'];
		$Page = LibPage::Show($total, $perPage);
	
		LibTpl::Set('Page', $Page);
		LibTpl::Set('yjConfig', $this->yjConfig());
		LibTpl::Set('Params', $Params);
		LibTpl::Set('lists', $lists);
		LibTpl::Set('title', '业绩列表');
		LibTpl::Put();
	}

	
	//添加或者编辑业绩明细
	function yjSet()
	{
		LibRule::Check('YJ01');
		//状态修改权限
		$chkRule = LibRule::Check('YJ02', false);
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		if(!empty($_POST['yj']['yl_title']))
		{
			$dataArr = $_POST['yj'];
			$dataArr['yl_pay_time'] = strtotime($dataArr['yl_pay_time']);
			$dataArr['yl_pay_money'] = sprintf('%.2f', $dataArr['yl_pay_money']);
			$dataArr['yl_user_money'] = sprintf('%.2f', $dataArr['yl_user_money']);
			$dataArr['yl_shui_money'] = sprintf('%.2f', $dataArr['yl_shui_money']);
			$dataArr['yl_com_money'] = sprintf('%.2f', $dataArr['yl_pay_money'] - $dataArr['yl_user_money'] - $dataArr['yl_shui_money']);
			if(!$chkRule) 
			{
				unset($dataArr['yl_status']);
				unset($dataArr['yl_check_time']);
				unset($dataArr['yl_check_user']);
			}
			if(empty($dataArr['yl_id']))
			{
				unset($dataArr['yl_id']);
				$dataArr['yl_add_time'] = time();
				$dataArr['yl_add_user'] = $_SESSION['admin_uname'];
				$res = $PjlBase->add('bu_yeji_list', $dataArr);
				$yl_id = $res['data'];
			}
			else
			{
				$yl_id = $dataArr['yl_id'];
				unset($dataArr['yl_add_time']);
				unset($dataArr['yl_add_user']);
				if($chkRule && $dataArr['yl_status'] == 1)
				{
					$dataArr['yl_check_time'] = time();
					$dataArr['yl_check_user'] = $_SESSION['admin_uname'];
				}
				$PjlBase->set('bu_yeji_list', $dataArr, sprintf(" and yl_id=%d", $yl_id));
			}
			LibTpl::Success('保存成功', mvc::$cfg['ADMIN_URI'].'pjl/yjSet?yl_id='.$yl_id);
		}
		if(!empty($Params['yl_id']))
		{
			$res = $PjlBase->get('bu_yeji_list', ['*'], sprintf("and yl_id = %d", $Params['yl_id']), true);
			$yjArr = $res['data'];
			if(!empty($yjArr) && $yjArr['yl_status'] == 1)
			{
				LibRule::Check('YJ02');
			}
			LibTpl::Set('yjArr', $yjArr);
		}
		
		LibTpl::Set('chkRule', $chkRule);
		LibTpl::Set('yjConfig', $this->yjConfig());
		LibTpl::Set('title', '业绩明细');
		LibTpl::Put();
	}

	
	//业务员的
	private function yjConfig()
	{
	    $user = (new PjlBase)->get(sprintf("bu_user"),['usr_name'],' and usr_status=1 order by usr_seq,convert(usr_name using gbk)');
	    $user = array_column($user['data'],'usr_name');
        $yjConfig = [
			'style' => [
				0=>'待审核',
				1=>'已审核',
				-1=>'无效'
			],
			'xiangmu'=>['商家入驻', 'PC会员', '广告', '联动服务', '招商加盟', '机器人', '资源包','打电话', '推送服务', '其它'],
			'user'=> $user,
			'payby'=>['现金', '银行', '支付宝', '微信']
		];
		return $yjConfig;
	}

	
	//业绩统计
	function yjTj()
	{
		LibRule::Check('YJ03');
		$Params = mvc::$URL_PARAMS;
		$fastTime = [
			'本月'=>date('Y-m-01').' ~ '.date('Y-m').'-'.date('t'),	
			'上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
			// '本年'=>date('Y-01-01').' ~ '.date('Y-m-d')
		];
		$fastYear = array_reverse(range(2010,date('Y')));
		foreach ($fastYear as $value) {
			$fastYearList[$value] = "{$value}-01-01 ~ {$value}-12-31";
		}	

		LibTpl::Set('fastYear', $fastYearList);
		LibTpl::Set('fastTime', $fastTime);

		
		$groupByArr = [
			'day'=>['日统计', '%Y-%m-%d'],	
			'month'=>['月统计', '%Y-%m'],	
			'year'=>['年统计', '%Y']
		];
		LibTpl::Set('groupByArr', $groupByArr);

		$Params['group'] = empty($groupByArr[$Params['group']]) ? 'day': $Params['group'];
		$groupBy = $groupByArr[$Params['group']][1];

		$PjlBase= new PjlBase();
		$where =' and yl_status != -1 AND yl_xiangmu_des !=\'机器人token代购费\'';
		$Params['betime'] = empty($Params['betime'])? $fastTime['本月']: $Params['betime'];
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and yl_pay_time >= %d and yl_pay_time < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
            }
        }

		$where .= sprintf(" GROUP BY yl_xiangmu, FROM_UNIXTIME(yl_pay_time, '%s') ORDER BY FROM_UNIXTIME(yl_pay_time, '%s') desc", $groupBy, $groupBy);
		$tjArr = [];
		$sum = [];

		$hongLi = ['商家入驻', 'PC会员', '广告', '招商加盟', '机器人', '资源包', '打电话', '推送服务', '其它'];

		$res = $PjlBase->get('bu_yeji_list', ["yl_xiangmu, FROM_UNIXTIME(yl_pay_time, '".$groupBy."') as pay_date, sum(yl_pay_money) as yl_pay_money, sum(yl_user_money) as yl_user_money, sum(yl_com_money) as yl_com_money, count(*) as count"], $where);
		foreach($res['data'] as $v)
		{
			$sum[$v['yl_xiangmu']]['yl_pay_money'] += $v['yl_pay_money'];
			$sum[$v['yl_xiangmu']]['yl_user_money'] += $v['yl_user_money'];
			$sum[$v['yl_xiangmu']]['yl_com_money'] += $v['yl_com_money'];
			$sum[$v['yl_xiangmu']]['count'] += $v['count'];
			$sum['yl_pay_money'] += $v['yl_pay_money'];
			$sum['yl_user_money'] += $v['yl_user_money'];
			$sum['yl_com_money'] += $v['yl_com_money'];
			if(in_array($v['yl_xiangmu'], $hongLi))
			{
				$sum['hongli']['yl_pay_money'] += $v['yl_pay_money'];
				$sum['hongli']['yl_user_money'] += $v['yl_user_money'];
				$sum['hongli']['yl_com_money'] += $v['yl_com_money'];
			}
			$tjArr[$v['pay_date']][$v['yl_xiangmu']] = $v;

			$tjArr[$v['pay_date']]['yl_pay_money'] += $v['yl_pay_money'];
			$tjArr[$v['pay_date']]['yl_user_money'] += $v['yl_user_money'];
			$tjArr[$v['pay_date']]['yl_com_money'] += $v['yl_com_money'];
		}

		krsort($tjArr);
		LibTpl::Set('typeArr', $typeArr);
		LibTpl::Set('sum',$sum);
		LibTpl::Set('tjArr',$tjArr);
		LibTpl::Set('hongLi',$hongLi);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('yjConfig', $this->yjConfig());
		LibTpl::Set('title','业绩统计');
		LibTpl::Put();
	}



	//在线交易的统计
	function onlineMoneyTj()
	{
		LibRule::Check('YJ03');
		$Params = mvc::$URL_PARAMS;
		$Params['year'] = empty($Params['year'])? date('Y'): $Params['year'];

		$MainBase = new MainBase();
		$where = " and por_status = 1 AND por_transaction_id != '' ORDER BY por_year DESC";
		$res = $MainBase->get('pa_order', ["DISTINCT FROM_UNIXTIME(por_pay_time,'%Y') AS por_year"], $where);
		LibTpl::Set('yearArr', array_column($res['data'], 'por_year'));
		
		$where = sprintf(" and FROM_UNIXTIME(por_pay_time,'%%Y') =%d and por_status = 1 AND por_transaction_id != '' GROUP BY pay_month, por_pay_method, por_account, por_style ORDER BY pay_month DESC", $Params['year']);
		$filed = ["FROM_UNIXTIME(por_pay_time,'%Y%m') AS pay_month, concat(por_pay_method, por_account) as account, por_style, SUM(por_money) as por_money, SUM(por_service_fee) as service_fee"];
		$res = $MainBase->get('pa_order', $filed, $where);
		foreach($res['data'] as $v)
		{
			$moneyArr[$v['pay_month']][$v['por_style']][$v['account']]['total'] += $v['por_money'];
			$moneyArr[$v['pay_month']][$v['por_style']][$v['account']]['fee'] += $v['service_fee'];
		}

		//退款金额
		$where = sprintf(" and FROM_UNIXTIME(pre_atime,'%%Y') =%d and pre_status = 1 AND pre_refund_id != '' GROUP BY pay_month, por_pay_method, por_account, por_style ORDER BY pay_month DESC", $Params['year']);
		$filed = ["FROM_UNIXTIME(pre_atime,'%Y%m') AS pay_month, concat(por_pay_method, por_account) as account, por_style, SUM(pre_refund_money) as por_money, SUM(pre_service_fee) as service_fee"];
		$res = $MainBase->get('pa_refund JOIN pa_order ON por_id = pre_por_id', $filed, $where);
		foreach($res['data'] as $v)
		{
			$moneyArr[$v['pay_month']][$v['por_style']][$v['account']]['total'] -= $v['por_money'];
			$moneyArr[$v['pay_month']][$v['por_style']][$v['account']]['fee'] += $v['service_fee'];
		}

		$tjArr = [];
		foreach($moneyArr as $ym=>$v)
		{
			foreach($v as $style=>$vv)
			{
				foreach($vv as $account=>$mArr)
				{
					//PJLCZ:跑街令充值 PJLVIP:跑街令VIP PJLPAC:跑街令资源包 PJLORD:跑街令订单 PJDORD:商城订单 YPING:宜配网积分 QIPERIS:汽配搜
					switch($style)
					{
						case 'PJLCZ':
						case 'PJLVIP':
						case 'PJLPAC':
							$tjArr[$ym]['pjl'][$account]['total'] += $mArr['total'];
							$tjArr[$ym]['pjl'][$account]['fee'] += $mArr['fee'];
						break;
						case 'PJLORD':
							$tjArr[$ym]['shop'][$account]['total'] += $mArr['total'];
							//交易费由跑街承担
							$tjArr[$ym]['pjl'][$account]['fee'] += $mArr['fee'];
						break;
						case 'PJDORD':
							//交易费由跑街承担
							$tjArr[$ym]['pjl'][$account]['fee'] += $mArr['fee'];

							//佣金8%
							$yj = sprintf('%.2f', $mArr['total']*0.08);
							$tjArr[$ym]['pjl'][$account]['total'] += $yj;
							$tjArr[$ym]['shop'][$account]['total'] += $mArr['total']-$yj;

						break;
						case 'YPING':
						case 'QIPERIS':
							$tjArr[$ym]['yp'][$account]['total'] += $mArr['total'];
							$tjArr[$ym]['yp'][$account]['fee'] += $mArr['fee'];
						break;
					}
				}
			}
		}
		$allTj = [];
		foreach($tjArr as $ym=>$v)
		{
			foreach($v as $styl=>$vv)
			{
				foreach($vv as $account=>$vvv)
				{
					foreach($vvv as $kkkk=>$vvvv)
					{
						$tjArr[$ym][$styl]['total'][$kkkk] += $vvvv;
						$allTj[$styl]['total'][$kkkk] += $vvvv;
						$allTj[$styl][$account][$kkkk] += $vvvv;
					}
				}
			}
		}
		LibTpl::Set('allTj', $allTj);
		LibTpl::Set('tjArr', $tjArr);


		//按账户统计
		$tjAcArr = [];
		foreach($moneyArr as $ym=>$v)
		{
			foreach($v as $style=>$vv)
			{
				foreach($vv as $account=>$mArr)
				{
					$tjAcArr[$ym][$account]['total'] += $mArr['total'];
					$tjAcArr[$ym][$account]['fee'] += $mArr['fee'];
					$tjAcAllArr[$ym]['total'] += $mArr['total'];
					$tjAcAllArr[$ym]['fee'] += $mArr['fee'];
					$tjAcAllArr['all']['total'] += $mArr['total'];
					$tjAcAllArr['all']['fee'] += $mArr['fee'];
					$tjAcAllArr[$account]['total'] += $mArr['total'];
					$tjAcAllArr[$account]['fee'] += $mArr['fee'];
				}
			}
		}
		LibTpl::Set('tjAcArr', $tjAcArr);
		LibTpl::Set('tjAcAllArr', $tjAcAllArr);

		LibTpl::Set('title','在线交易的统计');
		LibTpl::Put();
	}



	//凭证明细
	function voucherList()
	{
		LibRule::Check('CW01');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage = isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$MainBase= new MainBase();
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'vol_time':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and vol_time >= %d and vol_time < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'vol_pay_method':
				case 'acc_code':
				case 'vok_code':
					$where .= sprintf(" and %s = '%s'", $k, LibFc::Escape($v));
				break;
				case 'word':
					$where .= sprintf(" and (vol_title like '%%%s%%' or acc_name like '%%%s%%' or vok_name like '%%%s%%')", LibFc::Escape($v), LibFc::Escape($v), LibFc::Escape($v));
				break;
            }
        }

		$table = 'cw_voucher_list
		join cw_voucher_kemu on vok_code = vol_vok_code 
		join cw_account on vok_acc_code = acc_code';
		$res = $MainBase->get($table, ['count(*) as count'], $where, true);
		$total = $res['data']['count']; 
		$res = $MainBase->get($table, ['*'], sprintf("%s ORDER BY vol_time DESC, vok_seq limit %d,%d", $where, ($nowPage-1)*$perPage, $perPage));
		$lists = $res['data'];
	
		$Page = LibPage::Show($total, $perPage);

		$res = $MainBase->get('cw_account', ['acc_code, acc_name']);
		LibTpl::Set('accArr', array_column($res['data'], null, 'acc_code'));

		$res = $MainBase->get('cw_voucher_kemu join cw_account on vok_acc_code = acc_code', ['vok_code, acc_name, vok_name'], ' order by vok_seq');
		LibTpl::Set('kmArr', array_column($res['data'], null, 'vok_code'));

		LibTpl::Set('payArr', ['weixin'=>'微信', 'alipay'=>'支付宝']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('lists', $lists);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title', '凭证列表');
		LibTpl::Put();
	}

	//添加或者编辑凭证
	function voucherSet()
	{
		LibRule::Check('CW02');
		$Params = mvc::$URL_PARAMS;
		$MainBase= new MainBase();
		if(!empty($_POST['vo']['vol_title']) && !empty($_POST['vo']['vol_vok_code']))
		{
			$dataArr = $_POST['vo'];
			$dataArr['vol_time'] = strtotime($dataArr['vol_time']);
			$dataArr['vol_jiefang'] = sprintf('%.2f', $dataArr['vol_jiefang']);
			$dataArr['vol_daifang'] = sprintf('%.2f', $dataArr['vol_daifang']);
			
			if(empty($dataArr['vol_id']))
			{
				unset($dataArr['vol_id']);
				$dataArr['vol_add_time'] = time();
				$dataArr['vol_add_by'] = $_SESSION['admin_uname'];
				$res = $MainBase->add('cw_voucher_list', $dataArr);
				$vol_id = $res['data'];
			}
			else
			{
				$vol_id = $dataArr['vol_id'];
				unset($dataArr['vol_add_time']);
				unset($dataArr['vol_add_by']);
				$dataArr['vol_set_time'] = time();
				$dataArr['vol_set_by'] = $_SESSION['admin_uname'];
				$MainBase->set('cw_voucher_list', $dataArr, sprintf(" and vol_id=%d", $vol_id));
			}
			LibTpl::Success('保存成功', mvc::$cfg['ADMIN_URI'].'pjl/voucherSet?vol_id='.$vol_id);
		}
		if(!empty($Params['vol_id']))
		{
			$table = 'cw_voucher_list
			join cw_voucher_kemu on vok_code = vol_vok_code 
			join cw_account on vok_acc_code = acc_code';
			$res = $MainBase->get($table, ['*'], sprintf("and vol_id = %d", $Params['vol_id']), true);
			LibTpl::Set('voArr', $res['data']);
		}
		
		$res = $MainBase->get('cw_voucher_kemu join cw_account on vok_acc_code = acc_code', ['vok_code, acc_name, vok_name'], ' order by vok_seq');
		LibTpl::Set('kmArr', array_column($res['data'], null, 'vok_code'));

		LibTpl::Set('payArr', ['weixin'=>'微信', 'alipay'=>'支付宝']);
		LibTpl::Set('title', '凭证管理');
		LibTpl::Put();
	}

	//删除凭证
	function voucherDel()
	{
		LibRule::Check('CW02');
		$Params = mvc::$URL_PARAMS;
		$MainBase= new MainBase();
		$res = $MainBase->del('cw_voucher_list', sprintf("and vol_id = %d", $Params['vol_id']));
		LibFc::ajaxJsonEncode($res);
	}

	//凭证统计
	function voucherTj()
	{
		LibRule::Check('CW03');
		$Params = mvc::$URL_PARAMS;
		$fastTime = [
			'本月'=>date('Y-m-01').' ~ '.date('Y-m').'-'.date('t'),	
			'上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
			'本年'=>date('Y-01-01').' ~ '.date('Y-m-d')
		];
		LibTpl::Set('fastTime', $fastTime);

		$groupByArr = [
			'month'=>['月统计', '%Y-%m'],	
			'year'=>['年统计', '%Y'],
			'day'=>['日统计', '%Y-%m-%d']
		];
		LibTpl::Set('groupByArr', $groupByArr);

		$Params['group'] = empty($groupByArr[$Params['group']]) ? 'month': $Params['group'];
		$groupBy = $groupByArr[$Params['group']][1];

		$MainBase= new MainBase();
		$where =' and vol_time >= 0';
		$Params['betime'] = empty($Params['betime'])? $fastTime['本月']: $Params['betime'];
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and vol_time >= %d and vol_time < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
            }
        }

		
		$sum = [];
		$table = 'cw_voucher_list
		join cw_voucher_kemu on vok_code = vol_vok_code 
		join cw_account on vok_acc_code = acc_code';
	

		$whereArr = [
			'PJL'=>['total'=>'', 'weixin'=>'weixin', 'alipay'=>'alipay'],	
			'YP'=>['total'=>'', 'weixin'=>'weixin']
		];
		$sum = [];
		foreach($whereArr as $acc=>$gv)
		{
			foreach($gv as $gkk=>$gvv)
			{
				$pay = $gvv == '' ? '': sprintf(" and vol_pay_method ='%s'", $gvv);
				$twhere = $where.$pay.sprintf(" and acc_code='%s' GROUP BY vok_name, FROM_UNIXTIME(vol_time, '%s') ORDER BY FROM_UNIXTIME(vol_time, '%s') desc, vok_seq",$acc, $groupBy, $groupBy);
				$res = $MainBase->get($table, ["vok_code, vok_name, FROM_UNIXTIME(vol_time, '".$groupBy."') as vol_date, sum(vol_jiefang) as vol_jiefang, sum(vol_daifang) as vol_daifang"], $twhere);
				$sum[$acc][$gkk] = $res['data'];
				foreach($res['data'] as $gvvv)
				{
					$tj[$acc][$gkk]['vol_jiefang'] += $gvvv['vol_jiefang'];
					$tj[$acc][$gkk]['vol_daifang'] += $gvvv['vol_daifang'];
				}
			}
		}

		$res = $MainBase->get('cw_account', ['acc_code, acc_name']);
		LibTpl::Set('accArr', array_column($res['data'], null, 'acc_code'));

		LibTpl::Set('payArr', ['weixin'=>'微信', 'alipay'=>'支付宝']);
		LibTpl::Set('sum',$sum);
		LibTpl::Set('tj',$tj);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','凭证统计');
		LibTpl::Put();
	}

    //支付记录
	public function paymentRecords()
	{
        LibRule::Check('CW04');
        $param = mvc::$URL_PARAMS;
        $mainBase = new MainBase();
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = LibFc::Int($param['page']) ? LibFc::Int($param['page']) : 1;
        $where = '';
        if($param['por_id']){
            $where .= sprintf(" and por_id=%d", (int) trim($param['por_id']));
        }
        if($param['por_account']){
            $where .= sprintf(" and por_account like '%%%s%%'",trim($param['por_account']));
        }
        if($param['por_orderids']){
            $where .= sprintf(" and por_orderids like '%s'",trim($param['por_orderids']));
        }
        if($param['por_title']){
            $where .= sprintf(" and por_title like '%%%s%%'",trim($param['por_title']));
        }
        if(is_numeric($param['por_status'])){
            $where .= sprintf(" and por_status=%d",trim($param['por_status']));
        }
        if($param['por_pay_method']){
            $where .= sprintf(" and por_pay_method ='%s'",trim($param['por_pay_method']));
        }
        if($param['por_atime']){
            $temp = explode(" ~ ",$param['por_atime']);
            $temp = array_map(function ($value){
                return strtotime($value);
            },$temp);
            $where .= sprintf(" and por_atime >= '%s' and por_atime <= '%s'",$temp['0'],$temp['1']);
        }
        $count = $mainBase->Get('pa_order',['count(*) as count'],$where,true);
        $count = $count['data']['count'] ?: 0;
        if($count > 0){
            $where .= sprintf(" order by por_atime desc limit %s,%s",($page-1)*$pageSize,$pageSize);
            $list = $mainBase->Get('pa_order',['*'],$where,false);
            if(!empty($list['data'])){
                LibTpl::Set('user',$this->getUserInfo(array_column($list['data'],'por_u_id')));
            }
            LibTpl::Set('list',$list['data']);
        }
	    $pages = LibPage::Show($count, $pageSize);
	    LibTpl::Set('type',$this->getPayType());
	    LibTpl::Set('page', $pages);
	    LibTpl::Set('Params',$param);
	    LibTpl::Set('title', '支付记录');
	    LibTpl::Put();
	}

	//退款记录
	public function refundRecords()
	{
        LibRule::Check('CW04');
        $param = mvc::$URL_PARAMS;
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = LibFc::Int($param['page']) ? LibFc::Int($param['page']) : 1;
        $mainBase = new MainBase();
        $where = '';
        if($param['pre_id']){
            $where .= sprintf(" and pre_id=%d", (int) trim($param['pre_id']));
        }
        if($param['pre_por_id']){
            $where .= sprintf(" and pre_por_id=%d", (int) trim($param['pre_por_id']));
        }

        if($param['pre_status']){
            $where .= sprintf(" and pre_status = '%s'",trim($param['pre_status']));
        }
        if($param['pre_des']){
            $where .= sprintf(" and pre_des like '%%%s%%'",trim($param['pre_des']));
        }
        if($param['pre_atime']){
            $temp = explode(" ~ ",$param['pre_atime']);
            $temp = array_map(function ($value){
                return strtotime($value);
            },$temp);
            $where .= sprintf(" and pre_atime >= '%s' and pre_atime <= '%s'",$temp['0'],$temp['1']);
        }

        $count = $mainBase->Get('pa_refund',['count(*) as count'],$where,true);
        $count = $count['data']['count'] ?: 0;
        if($count > 0){
            $where .= sprintf(" order by pre_atime desc limit %s,%s",($page-1)*$pageSize,$pageSize);
            $list = $mainBase->Get('pa_refund',['*'],$where,false);
            LibTpl::Set('list',$list['data']);
        }
	    $pages = LibPage::Show($count, $pageSize);
        LibTpl::Set('type',$this->getRecordsStatus());
        LibTpl::Set('Params',$param);
	    LibTpl::Set('page', $pages);
	    LibTpl::Set('title', '退款记录');
	    LibTpl::Put();
	}

    //转账记录
	public function transferRecords()
	{
        LibRule::Check('CW04');
        $param = mvc::$URL_PARAMS;
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = LibFc::Int($param['page']) ? LibFc::Int($param['page']) : 1;
        $mainBase = new MainBase();
        $where = '';
        if($param['pmc_u_id']){
            $uId = (new YpwBase)->get('yp_user',['u_id'],sprintf(" and (u_mobile like '%%%s%%' or u_name like '%%%s%%')",trim($param['pmc_u_id']),trim($param['pmc_u_id'])),true);
            if(isset($uId['data']['u_id']) && $uId['data']['u_id'] > 0 ){
                $where .= sprintf(" and pmc_u_id=%d", (int) $uId['data']['u_id']);
            }else{
                $where .= sprintf(" and pmc_u_id < 0");
            }
        }
        if($param['pmc_pay_by']){
            $where .= sprintf(" and pmc_pay_by='%s'", trim($param['pmc_pay_by']));
        }
        if(is_numeric($param['pmc_status'])){
            $where .= sprintf(" and pmc_status = '%s'",trim($param['pmc_status']));
        }
        if($param['pmc_des']){
            $where .= sprintf(" and pmc_des like '%%%s%%'",trim($param['pmc_des']));
        }
        if($param['pmc_account']){
            $where .= sprintf(" and pmc_account like '%%%s%%'",trim($param['pmc_account']));
        }
        if($param['pmc_partner_trade_no']){
            $where .= sprintf(" and pmc_partner_trade_no like '%%%s%%'",trim($param['pmc_partner_trade_no']));
        }
        if($param['pmc_atime']){
            $temp = explode(" ~ ",$param['pmc_atime']);
            $temp = array_map(function ($value){
                return strtotime($value);
            },$temp);
            $where .= sprintf(" and pmc_atime >= '%s' and pmc_atime <= '%s'",$temp['0'],$temp['1']);
        }

        $count = $mainBase->Get('pa_mchpay',['count(*) as count'],$where,true);
        $count = $count['data']['count'] ?: 0;
        if($count > 0){
            $where .= sprintf(" order by pmc_atime desc limit %s,%s",($page-1)*$pageSize,$pageSize);
            $list = $mainBase->Get('pa_mchpay',['*'],$where,false);
            if(!empty($list['data'])){
                LibTpl::Set('user',$this->getUserInfo(array_column($list['data'],'pmc_u_id')));
            }
            LibTpl::Set('list',$list['data']);
        }
        $pages = LibPage::Show($count, $pageSize);
        LibTpl::Set('type',$this->getTransferStatus());
        LibTpl::Set('Params',$param);
        LibTpl::Set('page', $pages);
        LibTpl::Set('title', '退款记录');
        LibTpl::Put();
	}

    /**
     * 获取用户信息
     * @param array $uids uid 的一维数组
     * @return array|mixed
     */
    private function getUserInfo(array $uids)
    {
        if(empty($uids)){
            return [];
        }
        $userInfo = (new YpwBase)->get('yp_user',['u_id,u_name'],sprintf(" and u_id in (%s)",implode(',',$uids)));
        return $userInfo['data'] ? array_column($userInfo['data'],'u_name','u_id'): [];
    }

    /**
     * 获取转账记录需要的select
     * @return string[][]
     */
    private function getTransferStatus()
    {
        return [
            'pmc_status' => [
                '-1' => '已关闭',
                '0' => '已提交',
                '1' => '转账完成'
            ],
            'pmc_pay_by' => [
                'weixin' => '微信',
                'alipay' => '支付宝',
            ]
        ];
    }

    /**
     * 获取退款需要的select
     * @return string[][]
     */
    private function getRecordsStatus()
    {
        return [
            'pre_status' => [
                '-1' => '已关闭' ,
                '0'  => '退款中',
                '1' => '退款完成'
            ],
            'pre_zhangdan' => [
                '0' => '否',
                '1' => '是'
            ]
        ];
    }

    /**
     * 获取支付记录需要的select
     * @return string[][]
     */
    private function getPayType()
    {
        return [
            'por_status' => [
                '-1' => '已关闭',
                '0' => '待支付',
                '1' => '支付完成',
                '2' => '异常'
            ],
            'por_pay_method' => [
                'weixin' => '微信',
                'alipay' => '支付宝'
            ],
            'por_pay_type' => [
                'pc' => '扫码',
                'app' => 'APP',
                'wap' => '手机网',
                'gzh' => '公众号'
            ],
            'por_style' => [
                'PJLCZ' => '跑街令充值',
                'PJLVIP' => '跑街令VIP',
                'PJLPAC' => '跑街令资源包',
                'PJLORD' => '跑街令订单',
                'PJDORD' => '商城订单',
                'YPING' => '宜配网积分',
                'QIPERIS' => '汽配搜',
                'YPYQSYS' => '宜配搜搜',
            ],
            'por_zhangdan' => [
                '0' => '否',
                '1' => '是'
            ]
        ];
    }


    public function businessStatistics()
    {
        LibRule::Check('YJ03');
        $Params = mvc::$URL_PARAMS;
        $fastTime = [
            '本月'=>date('Y-m-01').' ~ '.date('Y-m').'-'.date('t'),
            '上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
            // '本年'=>date('Y-01-01').' ~ '.date('Y-m-d')
        ];
		$fastYear = array_reverse(range(2010,date('Y')));
		foreach ($fastYear as $value) {
			$fastYearList[$value] = "{$value}-01-01 ~ {$value}-12-31";
		}	
		$isSameYear = false;
		$lastYearWhere = '';
        $Params['betime'] = empty($Params['betime']) ? $fastTime['本月'] : $Params['betime'];
        $where = ' and yl_status != -1 and yl_xiangmu not in ("联动服务") and locate("token代购费",yl_xiangmu_des)=0';
        if($Params['betime']){
            $temp = explode(" ~ ",$Params['betime']);

			$firstYear = date('Y',strtotime($temp['0']));
			$secondYear = date('Y',strtotime($temp['1']));
			if($firstYear == $secondYear)
			{
				$isSameYear = true;
				$lastYearstart = strtotime('-1 year',strtotime($temp['0']));
				$lastYearend = strtotime('-1 year',strtotime($temp['1'].' 23:59:59'));
				$lastYearWhere = $where.sprintf(" and yl_pay_time >= %d and yl_pay_time <= %d",$lastYearstart,$lastYearend);
			}

            $where .= sprintf(" and yl_pay_time >= %d and yl_pay_time <= %d",strtotime($temp['0']),strtotime($temp['1'].' 23:59:59'));
            foreach ($temp as &$value)
            {
                $value = date('Ym',strtotime($value));
            }
        }
        $wheres = '';
        if(isset($Params['is_on'])){
            $wheres = sprintf(" and usr_istar=1");
        }
        $db = new PjlBase();
        $monthList = $db->get('bu_com_target',['sum(bct_money) as money'],sprintf(" and bct_month >= '%s' and bct_month <= '%s'",$temp['0'],$temp['1']),true);
        $mbCount = $monthList['data']['money'] ?: 0 ;
        $xm = $db->get('bu_xiangmu',['xm_name'],' and xm_name not in ("联动服务") order by xm_seq,convert(xm_name using gbk)');
        $xm = array_column($xm['data'],'xm_name');
        $name = $db->get(sprintf("bu_user left join bu_user_target on usr_name=but_name and but_month >= '%s' and but_month <= '%s' ",$temp['0'],$temp['1']),['usr_name','sum(but_money) as but_money','but_name','usr_istar'],$wheres.' and usr_status=1 group by usr_name order by usr_seq,convert(usr_name using gbk)');
        $name = $name['data'];
        $list = $db->get('bu_yeji_list',['yl_xiangmu','sum(yl_pay_money) as yl_pay_money','yl_user'],$where .' group by yl_xiangmu,yl_user');
        $list = $list['data'];
        $array = [];
        $xms = array_unique(array_column($list,'yl_xiangmu'));

        foreach ($list as $value)
        {
            $array[$value['yl_user']][$value['yl_xiangmu']] += $value['yl_pay_money'];
        }
        $total = [];
        $s = 0;
		if($isSameYear)
		{
			$list = $db->get('bu_yeji_list',['yl_xiangmu','sum(yl_pay_money) as yl_pay_money','yl_user'],$lastYearWhere .' group by yl_xiangmu,yl_user');
       		$list = $list['data'];
			$lastTotalArr = [];
			foreach ($list as $value)
			{
				$lastTotalArr[$value['yl_user']] += $value['yl_pay_money'];
			}
			$lastTotal = array_sum($lastTotalArr);
		}
	
		//有业绩记录但不在bu_user的业务员
		$nameList = array_unique(array_column($name,'usr_name'));
		foreach ($array as $key => $value) {
			if(!in_array($key,$nameList)){
				$name[]  = [
					'usr_name'=>$key,
					'but_money'=>0,
					'but_name'=>'',
					'usr_istar'=>0
				];
			}
		}
        foreach ($name as $key => &$value)
        {
            $value['xm_total'] = 0;
            if(isset($array[$value['usr_name']])){
                $value['xm_total'] = array_sum($array[$value['usr_name']]);
                $s += $value['xm_total'];

				if($isSameYear)
				{
					if(isset($lastTotalArr[$value['usr_name']]) && !empty($lastTotalArr[$value['usr_name']]))
					{	
						$value['last_xm_total'] = $lastTotalArr[$value['usr_name']];
						$value['rate'] = round(($value['xm_total']-$value['last_xm_total'])/$value['last_xm_total'],4)*100;
					}
				}
	
                foreach ($xm as $v)
                {
                    if(isset($array[$value['usr_name']][$v])){
                        $total[$v] += $array[$value['usr_name']][$v];
                        $value['xm_list'][$v] = $array[$value['usr_name']][$v];
                    }else{
                        $total[$v] += 0;
                        $value['xm_list'][$v] = 0;
                    }
                }
                continue;
            }elseif ($value['but_money'] > 0) {
                foreach ($xm as $v)
                {
                    $value['xm_list'][$v] = '';
                }
                continue;
            }
            unset($name[$key]);
        }
        if(!empty($name)){
			$totalArr = [
				'usr_name' => '汇总',
				'but_month' => null,
				'but_name' => null,
				'usr_istar' => 0,
				'xm_total' => $s,
				'xm_list' => $total
			];
			if($isSameYear)
			{	
				
				if($lastTotal!=0)
				{	
					$totalArr['last_xm_total'] = $lastTotal;
					$totalArr['rate']= round(($s-$lastTotal)/$lastTotal,4) *100;
				}
				 
			} 
            array_unshift($name,$totalArr);
        }
        array_multisort(array_column($name,'xm_total'),SORT_DESC,$name);

		LibTpl::Set('isSameYear',$isSameYear);
		LibTpl::Set('fastYear', $fastYearList);
        LibTpl::Set('xm',$xm);
        LibTpl::Set('sjCount',$s);
        LibTpl::Set('mbCount',$mbCount);
        LibTpl::Set('list',$name);
        LibTpl::Set('fastTime',$fastTime);
        LibTpl::Set('Params',$Params);
        LibTpl::Set('title','业务统计');
        LibTpl::Put();
    }


    public function addYjmbPage()
    {
        LibRule::Check('YJ05');
        $Params = mvc::$URL_PARAMS;
        if(!$Params['but_month']){
            $Params['but_month'] = date('Ym',time());
        }

        $db = new PjlBase;
        $list = $db->get(sprintf("bu_user left join bu_user_target on usr_name=but_name and but_month ='%s' ",$Params['but_month']),['usr_name','sum(but_money) as but_money','but_name','usr_istar'],' and usr_status=1 and usr_istar=1 group by usr_name order by usr_seq,convert(usr_name using gbk)');
        LibTpl::Set('list' ,$list['data']);
        LibTpl::Set('Params',$Params);
        LibTpl::Put();
    }

    //获取列表页
    public function getYjmbList()
    {
        LibRule::Check('YJ05');
        $Params = mvc::$URL_PARAMS;
        $db = new PjlBase;
        $where = '';
        if($Params['but_month']){
            $where .= sprintf(" and but_month ='%s'",$Params['but_month']);
        }
        $list = $db->get(sprintf("bu_user left join bu_user_target on usr_name=but_name and but_month ='%s' ",$Params['but_month']),['usr_name','sum(but_money) as but_money','but_name','usr_istar'],' and usr_status=1 and usr_istar=1 group by usr_name order by usr_seq,convert(usr_name using gbk)');
        $list['code'] = 0;
        LibFc::ajaxJsonEncode($list);
    }

    //添加业务员每月目标
    public function addYjmb()
    {
        LibRule::Check('YJ05');
        $month = $_POST['but_month'];
        $db = new PjlBase;
        unset($_POST['but_month']);
        $result = $db->del("bu_user_target",sprintf(" and but_month='%s'",$month));
        //把目标金额为空或者小于0的删除掉
        foreach ($_POST as $key => $value)
        {
            if((float) $value['but_money'] <= 0) continue;
            $value['but_money'] = round($value['but_money'],2);
            if($value['but_money'] > 99999999.99) LibFc::ajaxJsonEncode(['status' => false,'data' => '目标金额超出最大限制(99999999.99)']);
            $value['but_month'] = $month;
            $result = $db->add('bu_user_target',$value);
        }
        LibFc::ajaxJsonEncode($result);
    }

    public function addComPage()
    {
        LibRule::Check('YJ05');
        $param = mvc::$URL_PARAMS;
        $db = new PjlBase;
        $result = $db->get('bu_yeji_list',['min(yl_pay_time) as year'],'',true);
        $year = (int) date('Y',$result['data']['year']) ?: (int) date('Y',time());
        $yearList = [];
        $maxYear = (int) date('Y');
        $maxYear += 2;
        while ($year <= $maxYear)
        {
            $yearList[] = $year;
            $year+=1;
        }
        if(empty($param['year'])) $param['year'] = (int) date('Y');
        $where = sprintf(" and bct_month >= %d and bct_month <= %d",(int) ($param['year']).'01', (int)$param['year'].'12');
        $mb = $db->get('bu_com_target',['*'],$where);
        $mb = !empty($mb['data']) ? array_column($mb['data'],'bct_money','bct_month') : [];
        $yjList = $db->get('bu_yeji_list',['sum(yl_pay_money) as money','from_unixtime(yl_pay_time,"%Y%m") day'],sprintf(" and yl_pay_time >= %d and yl_pay_time <= %d group by day",strtotime(($param['year'] - 1).'-01-01 00:00:00'),strtotime(($param['year']-1).'-12-31'.' 23:59:59')));
        $yjList = !empty($yjList['data']) ? array_column($yjList['data'],'money','day') : [];

        $temp = array_slice($yearList,array_search($param['year']-2,$yearList),3);
        $list = [];
        $s = 0;
        $year = $param['year'] -1 ;
        for ($i = 1; $i <= 12 ;$i++)
        {

            $a = (int) ($year.($i < 10 ? '0'.$i : $i));
            $list[$i]['zmb'] = isset($mb[$a+100]) ? $mb[$a+100] : '';
            $list[$i]['money'] = isset($yjList[$a]) ? $yjList[$a] : 0; //去年的
            $list[$i]['zzl'] = '';
            if($list[$i]['zmb'] > 0 && $list[$i]['money'] > 0){
                $list[$i]['zzl'] = (round(($list[$i]['zmb'] - $list[$i]['money']) / $list[$i]['money'] ,4) * 100).'%';
            }
            $s += $list[$i]['money'];
        }

        $arr['count'] = array_sum(array_column($list,'zmb')) ?: '';
        $arr['zxs'] = $s ?: '';
        $arr['zzl'] = $arr['count'] > 0 && $arr['zxs'] > 0 ? (round(($arr['count'] - $arr['zxs']) / $arr['zxs'],4) * 100 ).'%' : '';
        unset($yjList,$mb);
        LibTpl::Set('arr',$arr);
        LibTpl::Set('param',$param);
        LibTpl::Set('list',$list);
        LibTpl::Set('year_list',$yearList);
        LibTpl::Set('title','公司目标添加');
        LibTpl::Put();
    }

    //添加公司目标
    public function addComMb()
    {
        LibRule::Check('YJ05');
        $monthList = array_column($_POST,'bct_month');
        foreach ($monthList as &$value) $value = sprintf("'%s'",(int) $value);
        $db = new PjlBase;
        $result = $db->del('bu_com_target',sprintf(' and bct_month in (%s)',implode(',',$monthList)));
        foreach ($_POST as $value)
        {
            if((float) $value['bct_money'] > 0)
            {
                $value['bct_money'] = floatval($value['bct_money']);
                if($value['bct_money'] > 99999999.99) LibFc::ajaxJsonEncode(['status' => false,'data' => $value['bct_money'].'目标金额超过了最大MySql数值的最大限制']);
                $result = $db->add('bu_com_target',$value);
            }
        }
        LibFc::ajaxJsonEncode($result);
    }

    //业务公司统计
    public function comStatistics()
    {
        LibRule::Check('YJ05');
        $param = mvc::$URL_PARAMS;
        $db = new PjlBase();

        if(empty($param['betime'])){
            $param['betime'] = date('Y');
        }
        $monthList = [];
        for ($i = 1 ; $i <= 12 ; $i++)
        {
            $monthList[] = sprintf("'%s'",$param['betime'].($i < 10 ? '0'.$i : $i));
        }
        $list = $db->get('bu_yeji_list',['sum(yl_pay_money) as yl_pay_money','from_unixtime(yl_pay_time,"%Y%m") days'],' group by days');
        $mb = $db->get("bu_com_target",['*'],sprintf(" and bct_month in (%s)",implode(',',$monthList)));
        $mb = $mb['data'];

        $totalList = [];
        $totalList['mb_count'] = 0;
        $totalList['max_last_count'] = 0;
        $totalList['max_mb_count'] = 0;
        if(!empty($mb)){
            $mb = array_column($mb,'bct_money','bct_month');
            $tem = $param['betime'].date('m');
            foreach ($mb as $k => $v)
            {
                //if($tem >= $k) 
				$totalList['max_mb_count'] += $v;
            }
            $totalList['mb_count'] = array_sum($mb);
        }
        $list = $list['data'];
        if(!empty($list)) $list = array_column($list,'yl_pay_money','days');
        $arr = [];
        $currentMonth = $param['betime'] == date('Y')? (int) date('m',time()): 12;

        $totalList['last_count'] = 0;
        $totalList['current_count'] = 0;
        for ($i = 01; $i <= 12; $i++)
        {
            $s =  $i < 10 ? '0'.$i : $i;
            $a = (int) ($param['betime'].$s); // 今年
            $b = (int) (($param['betime']-1).$s); //去年
            $arr[$s][$a]['money'] = isset($list[$a]) ? $list[$a] : 0; //今年总销售

            if(isset($list[$b])){ //去年的总销售
                $arr[$s][$b]['money'] = $list[$b];
                $totalList['max_last_count'] += $list[$b];
            }else{
                $arr[$s][$b]['money'] = 0;
            }
            if($i <= $currentMonth ){
                $totalList['last_count'] += $arr[$s][$b]['money']; //去年的总销售
                $totalList['current_count'] += $arr[$s][$a]['money'];   //今年的总销售
            }
	
            $arr[$s][$a]['mb'] = isset($mb[$a]) ? $mb[$a] : 0; //今年的目标

            $arr[$s][$a]['wcl'] = ''; //今年的完成率 ==> 总销售/总目标
            if($arr[$s][$a]['mb'] > 0 && $arr[$s][$a]['money']  > 0) $arr[$s][$a]['wcl'] = round($arr[$s][$a]['money'] / $arr[$s][$a]['mb'],4) * 100 .'%';

            $arr[$s][$a]['zzl'] = ''; //增长率 = 今年-去年 / 去年
            if($arr[$s][$a]['money'] > 0 && $arr[$s][$b]['money'] > 0)
            {
                $arr[$s][$a]['zzl'] = round(($arr[$s][$a]['money'] - $arr[$s][$b]['money']) / $arr[$s][$b]['money'],4) * 100 . '%';
            }
        }

        $result = $db->get('bu_yeji_list',['min(yl_pay_time) as year'],'',true);
        $year = (int) date('Y',$result['data']['year']) ?: (int) date('Y',time());
        $yearList = [];
        $maxYear = (int) date('Y');
        while ($year <= $maxYear)
        {
            $yearList[] = $year;
            $year+=1;
        }

        LibTpl::Set('total_list',$totalList);
        LibTpl::Set('title','公司销售统计');
        LibTpl::Set('year_list',$yearList);
        LibTpl::Set('param',$param);
        LibTpl::Set('list',$arr);
        LibTpl::Put();
    }

	/**
	 * @method 新业绩统计
	 * @author zhengweihua 
	 * @copyright 2023-04-03
	 */
	public function newYjTj()
	{
		LibRule::Check('YJ03');
		$Params = mvc::$URL_PARAMS;
		$fastTime = [
			'本月'=>date('Y-m-01').' ~ '.date('Y-m').'-'.date('t'),	
			'上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
		];
		$fastYear = array_reverse(range(2010,date('Y')));
		foreach ($fastYear as $value) {
			$fastYearList[$value] = "{$value}-01-01 ~ {$value}-12-31";
		}	

		LibTpl::Set('fastYear', $fastYearList);
		LibTpl::Set('fastTime', $fastTime);

		
		$groupByArr = [
			'day'=>['日统计', '%Y-%m-%d'],	
			'month'=>['月统计', '%Y-%m'],	
			'year'=>['年统计', '%Y']
		];
		LibTpl::Set('groupByArr', $groupByArr);

		$Params['group'] = empty($groupByArr[$Params['group']]) ? 'day': $Params['group'];
		$groupBy = $groupByArr[$Params['group']][1];

		$CrmsBase = new BaseDb(mvc::$cfg['DB']['CRMS']);
		$where ='';
		$Params['betime'] = empty($Params['betime'])? $fastTime['本月']: $Params['betime'];
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and mon_date >= %d and mon_date < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
            }
        }
		$newYjConfig = $this->newYjaService();
		$where .= sprintf(" ORDER BY FROM_UNIXTIME(mon_date, '%s') desc",  $groupBy);
		$tjArr = [];
		$sum = [];

		$hongLi = ['商家入驻', 'PC会员', '广告', '招商加盟', '机器人', '资源包', '打电话', '推送服务', '其它'];
		$table = 'yja_money 
		join yja_money_ser on mon_id =mos_mon_id 
		join yja_service on ser_id=mos_ser_id and ser_tj_site2=1';
		$res = $CrmsBase->get($table, ["*,FROM_UNIXTIME(mon_date, '".$groupBy."') as pay_date"], $where);

		foreach($res['data'] as $v)
		{
			$temp =	$newYjConfig[$v['mos_ser_id']];
			if(!$temp) continue;
			$v['count'] =1;
			$sum[$temp]['mos_pay_money'] += $v['mos_pay_money'];
			$sum[$temp]['mos_user_money'] += $v['mos_user_money'];
			$sum[$temp]['mos_com_money'] += $v['mos_com_money'];
			$sum[$temp]['count'] += $v['count'];
			$sum['mos_pay_money'] += $v['mos_pay_money'];
			$sum['mos_user_money'] += $v['mos_user_money'];
			$sum['mos_com_money'] += $v['mos_com_money'];
			if(in_array($temp, $hongLi))
			{
				$sum['hongli']['mos_pay_money'] += $v['mos_pay_money'];
				$sum['hongli']['mos_user_money'] += $v['mos_user_money'];
				$sum['hongli']['mos_com_money'] += $v['mos_com_money'];
			}
			$tjArr[$v['pay_date']][$temp]['mos_pay_money'] += $v['mos_pay_money'];
			$tjArr[$v['pay_date']][$temp]['mos_user_money'] += $v['mos_user_money'];
			$tjArr[$v['pay_date']][$temp]['mos_com_money'] += $v['mos_com_money'];
			$tjArr[$v['pay_date']][$temp]['count'] += $v['count'];

			$tjArr[$v['pay_date']]['mos_pay_money'] += $v['mos_pay_money'];
			$tjArr[$v['pay_date']]['mos_user_money'] += $v['mos_user_money'];
			$tjArr[$v['pay_date']]['mos_com_money'] += $v['mos_com_money'];
		}
		//机器人token费用
		$table = 'yja_money 
		join yja_money_ser on mon_id =mos_mon_id 
		join yja_service on ser_id=mos_ser_id and ser_tj_site2=1 and mos_ser_id = 39';
		$tokenMon = $CrmsBase->get($table, ["SUM(mos_pay_money) as mos_token_money"], $where,true);
		$sum['mos_token_money'] = $tokenMon['data']['mos_token_money']?$tokenMon['data']['mos_token_money']:0;
		$sum['mos_all_money'] = $sum['mos_token_money']+$sum['mos_pay_money'];
		krsort($tjArr);
		LibTpl::Set('sum',$sum);
		LibTpl::Set('tjArr',$tjArr);
		LibTpl::Set('hongLi',$hongLi);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('yjConfig', $this->yjConfig());
		LibTpl::Set('title','业绩统计');
		LibTpl::Put();
	}

	/**
	 * @method 新个人统计
	 * @author zhengweihua 
	 * @copyright 2023-04-03
	 */
	public function newBusinessStatistics()
    {
        LibRule::Check('YJ03');
        $Params = mvc::$URL_PARAMS;
        $fastTime = [
            '本月'=>date('Y-m-01').' ~ '.date('Y-m').'-'.date('t'),
            '上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
        ];
		$fastYear = array_reverse(range(2010,date('Y')));
		foreach ($fastYear as $value) {
			$fastYearList[$value] = "{$value}-01-01 ~ {$value}-12-31";
		}	
		$isSameYear = false;
		$lastYearWhere = '';
        $Params['betime'] = empty($Params['betime']) ? $fastTime['本月'] : $Params['betime'];
        $where = ' and mos_ser_id not in (28)';
        if($Params['betime']){
            $temp = explode(" ~ ",$Params['betime']);

			$firstYear = date('Y',strtotime($temp['0']));
			$secondYear = date('Y',strtotime($temp['1']));
			if($firstYear == $secondYear)
			{
				$isSameYear = true;
				$lastYearstart = strtotime('-1 year',strtotime($temp['0']));
				$lastYearend = strtotime('-1 year',strtotime($temp['1'].' 23:59:59'));
				$lastYearWhere = $where.sprintf(" and mon_date >= %d and mon_date <= %d",$lastYearstart,$lastYearend);
			}

            $where .= sprintf(" and mon_date >= %d and mon_date <= %d",strtotime($temp['0']),strtotime($temp['1'].' 23:59:59'));
            foreach ($temp as &$value)
            {
                $value = date('Ym',strtotime($value));
            }
        }
        $wheres = '';
        if(isset($Params['is_on'])){
            $wheres = sprintf(" and usr_istar=1");
        }
        $db = new PjlBase();
        $monthList = $db->get('bu_com_target',['sum(bct_money) as money'],sprintf(" and bct_month >= '%s' and bct_month <= '%s'",$temp['0'],$temp['1']),true);
        $mbCount = $monthList['data']['money'] ?: 0 ;
        $xm = $db->get('bu_xiangmu',['xm_name'],' and xm_name not in ("联动服务") order by xm_seq,convert(xm_name using gbk)');
        $xm = array_column($xm['data'],'xm_name');
        $name = $db->get(sprintf("bu_user left join bu_user_target on usr_name=but_name and but_month >= '%s' and but_month <= '%s' ",$temp['0'],$temp['1']),['usr_name','sum(but_money) as but_money','but_name','usr_istar'],$wheres.' and usr_status=1 group by usr_name order by usr_seq,convert(usr_name using gbk)');
        $name = $name['data'];
       
		$CrmsBase = new BaseDb(mvc::$cfg['DB']['CRMS']);
		$table = 'yja_money 
		join yja_money_ser on mon_id =mos_mon_id 
		join yja_service on ser_id=mos_ser_id and ser_tj_site2=1';
		$list = $CrmsBase->get($table, ["*"], $where);
		$list = $list['data'];
        $array = [];
		$newYjConfig = $this->newYjaService();
        foreach ($list as $value)
        {	
			if(!$newYjConfig[$value['mos_ser_id']]) continue;
            $array[$value['mon_u_name']][$newYjConfig[$value['mos_ser_id']]] += $value['mos_pay_money'];
        }
        $total = [];
        $s = 0;
		if($isSameYear)
		{
			$list = $CrmsBase->get($table, ["*"], $lastYearWhere);
			
       		$list = $list['data'];
			$lastTotalArr = [];
			foreach ($list as $value)
			{
				if(!$newYjConfig[$value['mos_ser_id']]) continue;
				$lastTotalArr[$value['mon_u_name']] += $value['mos_pay_money'];
			}
			$lastTotal = array_sum($lastTotalArr);
		}
	
		//有业绩记录但不在bu_user的业务员
		$nameList = array_unique(array_column($name,'usr_name'));
		foreach ($array as $key => $value) {
			if(!in_array($key,$nameList)){
				$name[]  = [
					'usr_name'=>$key,
					'but_money'=>0,
					'but_name'=>'',
					'usr_istar'=>0
				];
			}
		}
        foreach ($name as $key => &$value)
        {
            $value['xm_total'] = 0;
            if(isset($array[$value['usr_name']])){
                $value['xm_total'] = array_sum($array[$value['usr_name']]);
                $s += $value['xm_total'];

				if($isSameYear)
				{
					if(isset($lastTotalArr[$value['usr_name']]) && !empty($lastTotalArr[$value['usr_name']]))
					{	
						$value['last_xm_total'] = $lastTotalArr[$value['usr_name']];
						$value['rate'] = round(($value['xm_total']-$value['last_xm_total'])/$value['last_xm_total'],4)*100;
					}
				}
	
                foreach ($xm as $v)
                {
                    if(isset($array[$value['usr_name']][$v])){
                        $total[$v] += $array[$value['usr_name']][$v];
                        $value['xm_list'][$v] = $array[$value['usr_name']][$v];
                    }else{
                        $total[$v] += 0;
                        $value['xm_list'][$v] = 0;
                    }
                }
                continue;
            }elseif ($value['but_money'] > 0) {
                foreach ($xm as $v)
                {
                    $value['xm_list'][$v] = '';
                }
                continue;
            }
            unset($name[$key]);
        }
        if(!empty($name)){
			$totalArr = [
				'usr_name' => '汇总',
				'but_month' => null,
				'but_name' => null,
				'usr_istar' => 0,
				'xm_total' => $s,
				'xm_list' => $total
			];
			if($isSameYear)
			{	
				
				if($lastTotal!=0)
				{	
					$totalArr['last_xm_total'] = $lastTotal;
					$totalArr['rate']= round(($s-$lastTotal)/$lastTotal,4) *100;
				}
				 
			} 
            array_unshift($name,$totalArr);
        }
        array_multisort(array_column($name,'xm_total'),SORT_DESC,$name);

		LibTpl::Set('isSameYear',$isSameYear);
		LibTpl::Set('fastYear', $fastYearList);
        LibTpl::Set('xm',$xm);
        LibTpl::Set('sjCount',$s);
        LibTpl::Set('mbCount',$mbCount);
        LibTpl::Set('list',$name);
        LibTpl::Set('fastTime',$fastTime);
        LibTpl::Set('Params',$Params);
        LibTpl::Set('title','业务统计');
        LibTpl::Put();
    }

	/**
	 * @method 新业务公司统计
	 * @author zhengweihua 
	 * @copyright 2023-04-03
	 */
	public function newComStatistics()
	{
		LibRule::Check('YJ05');
        $param = mvc::$URL_PARAMS;
        $db = new PjlBase();

        if(empty($param['betime'])){
            $param['betime'] = date('Y');
        }
        $monthList = [];
        for ($i = 1 ; $i <= 12 ; $i++)
        {
            $monthList[] = sprintf("'%s'",$param['betime'].($i < 10 ? '0'.$i : $i));
        }
		$CrmsBase = new BaseDb(mvc::$cfg['DB']['CRMS']);
		$table = 'yja_money 
		join yja_money_ser on mon_id =mos_mon_id 
		join yja_service on ser_id=mos_ser_id and ser_tj_site2=1';
        $list = $CrmsBase->get($table,['sum(mos_pay_money) as mos_pay_money','from_unixtime(mon_date,"%Y%m") days'],' group by days');
        $mb = $db->get("bu_com_target",['*'],sprintf(" and bct_month in (%s)",implode(',',$monthList)));
        $mb = $mb['data'];

        $totalList = [];
        $totalList['mb_count'] = 0;
        $totalList['max_last_count'] = 0;
        $totalList['max_mb_count'] = 0;
        if(!empty($mb)){
            $mb = array_column($mb,'bct_money','bct_month');
            $tem = $param['betime'].date('m');
            foreach ($mb as $k => $v)
            {
				$totalList['max_mb_count'] += $v;
            }
            $totalList['mb_count'] = array_sum($mb);
        }
        $list = $list['data'];
        if(!empty($list)) $list = array_column($list,'mos_pay_money','days');
        $arr = [];
         $currentMonth = $param['betime'] == date('Y')? (int) date('m',time()): 12;

        $totalList['last_count'] = 0;
        $totalList['current_count'] = 0;
        for ($i = 01; $i <= 12; $i++)
        {
            $s =  $i < 10 ? '0'.$i : $i;
            $a = (int) ($param['betime'].$s); // 今年
            $b = (int) (($param['betime']-1).$s); //去年
            $arr[$s][$a]['money'] = isset($list[$a]) ? $list[$a] : 0; //今年总销售

            if(isset($list[$b])){ //去年的总销售
                $arr[$s][$b]['money'] = $list[$b];
                $totalList['max_last_count'] += $list[$b];
            }else{
                $arr[$s][$b]['money'] = 0;
            }
			if($i <= $currentMonth ){
				$totalList['last_count'] += $arr[$s][$b]['money']; //去年的总销售
				$totalList['current_count'] += $arr[$s][$a]['money'];   //今年的总销售
			}
            $arr[$s][$a]['mb'] = isset($mb[$a]) ? $mb[$a] : ''; //今年的目标

            $arr[$s][$a]['wcl'] = ''; //今年的完成率 ==> 总销售/总目标
            if($arr[$s][$a]['mb'] > 0 && $arr[$s][$a]['money']  > 0) $arr[$s][$a]['wcl'] = round($arr[$s][$a]['money'] / $arr[$s][$a]['mb'],4) * 100 .'%';

            $arr[$s][$a]['zzl'] = ''; //增长率 = 今年-去年 / 去年
            if($arr[$s][$a]['money'] > 0 && $arr[$s][$b]['money'] > 0)
            {
                $arr[$s][$a]['zzl'] = round(($arr[$s][$a]['money'] - $arr[$s][$b]['money']) / $arr[$s][$b]['money'],4) * 100 . '%';
            }
        }
		$CrmsBase = new BaseDb(mvc::$cfg['DB']['CRMS']);
		$table = 'yja_money 
		join yja_money_ser on mon_id =mos_mon_id 
		join yja_service on ser_id=mos_ser_id and ser_tj_site2=1';
        $result = $CrmsBase->get($table,['min(mon_date) as year'],'',true);
        $year = (int) date('Y',$result['data']['year']) ?: (int) date('Y',time());
        $yearList = [];
        $maxYear = (int) date('Y');
        while ($year <= $maxYear)
        {
            $yearList[] = $year;
            $year+=1;
        }

        LibTpl::Set('total_list',$totalList);
        LibTpl::Set('title','公司销售统计');
        LibTpl::Set('year_list',$yearList);
        LibTpl::Set('param',$param);
        LibTpl::Set('list',$arr);
        LibTpl::Put();
	}

	/**
	 * @method 新业绩项目与旧项目对应关系，数组为yja_service的id
	 * @author zhengweihua 
	 * @copyright 2023-04-03
	 */
	public function newYjaService()
	{
		$newYjConfig = [
			'xiangmu' => [
				'商家入驻' => [26],
				'PC会员' => [27],
				'广告' => [25],
				'联动服务' => [28],
				'招商加盟' => [30],
				'机器人' => [32, 38],
				'资源包' => [33],
				'打电话' => [34],
				'推送服务' => [31],
				'其它' => [35]
			],
		];
		$arr = [];
		foreach ($newYjConfig['xiangmu'] as $key => $valArr) {
			
			foreach ($valArr as $val) {
				$arr[$val] = $key;
			}
		}
		return $arr;
	}

}

