<?php

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class dailiAction extends baseAction
{

	function clientList()
	{
		$Params = mvc::$URL_PARAMS;
		$PjlDaili = new PjlDaili();
		$rule = LibFc::checkDlRule('DL05', false);
		$uid = $rule? 0: $_SESSION['_userid'];
		$res = $PjlDaili->getDcoWorkers($_SESSION['_dcoid'], $uid);
		LibTpl::Set('workerArr', $res['data']);

		LibTpl::Set('rule', $rule);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '客户管理');
		LibTpl::Put();
	}

	public function exportSelfUser()
	{
		$params = mvc::$URL_PARAMS;
		$params['type'] = 2;
		$params = array_map("trim", $params);

        /**
         * [$time 当前时间]
         * @var [type|Int]
         */
	    $time = time();

	    /**
	     * [$dcoId 供应商ID]
	     * @var [type|Int]
	     */

	    $dcoId = (int) $_SESSION['_dcoid'];
	    if(empty($dcoId) || (int) $dcoId <= 0)
	    {
	    	echo "找不到需要导出的记录";exit();
	    }

		/**
		 * [$pjlBaseModel  数据库操作类]
		 * @var PjlBase
		 */
		$pjlBaseModel = new PjlBase();

		/**
		 * 把是否是YP放Session里面
		 * [$isYp 是否是YP用户]
		 * @var [type]
		 */
		if(isset($_SESSION['is_yp']))
		{
			$isYp = $_SESSION['isYp'];
		}
		else
		{
		   $isYp =  $pjlBaseModel->get("dl_company",['dco_isyp'],sprintf(" and dco_isyp=1 and dco_id=%d",$dcoId),true);

		   if($isYp['data']['dco_isyp'] == 1)
		   {
		   	  $_SESSION['isYp'] = 1;
		   	  $isYp = 1;
		   }
		   else
		   {
		   	  $_SESSION['isYp'] = 0;
		   	  $isYp = 0;
		   }
		}

		/**
		 * [$where 查询条件开始]
		 * @var string
		 */
		$where = '';

		/**
		 * 根据是否是YP获取不同的pcId并放入where 条件中
		 * [$pcId 代理城市的城市ID(省)]
		 * @var [type]
		 */

		if($isYp)
		{
            $pcId = $pjlBaseModel->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_end >'%s' and dco_status=1",$time));
            $pcId = array_column($pcId['data'],'dctp_pc_id');
            if(empty($pcId)){
                echo "找不到需要导出的记录";exit();
            }
            $where .= sprintf(" and ui_province not in (%s)",implode(',', $pcId));
		}
		else
		{
		    $pcId = $pjlBaseModel->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_end >'%s' and dco_status=1 and dco_id=%d",$time,$dcoId));
		    if(empty($pcId['data'])){
                echo "找不到需要导出的记录";exit();
            }
		    $where .= sprintf(" and ui_province in (%s)",implode(',', array_column($pcId['data'],'dctp_pc_id')));
			$uidArr = $pjlBaseModel->get('dl_order_list',['dml_dwo_uid'],sprintf(" and dml_dco_id in (%s)",$dcoId));

			if(!empty($uidArr['data']))
			{
				$uidArr = array_column($uidArr['data'],'dml_dwo_uid');

				$where .= sprintf("  and (ua_pjl_shop_etime < %d OR ua_uid IN (%s))",$time,implode(',', $uidArr));
			}
			else
			{
				$where .= sprintf("  and (ua_pjl_shop_etime < %d)",$time);

			}
		}

		/**
		 * [$ypwModel 数据库]
		 * @var YpwBase
		 */
		$ypwModel = new YpwBase();

		$page = (int) $params['page'];

		$page = $page < 1 ? 1: $page;

		$limit = empty($params['limit'])? 15: (int) $params['limit'];

		if($params['user'])
		{
			$where .= sprintf(" and concat(ua_com_name,ua_link_name,ua_link_tel) like '%%%s%%'",trim($params['user']));
		}

		if($params['province'])
		{
			$where .= sprintf(" and find_in_set('%s',u_pct_ids)",$params['province']);
		}

		if($params['city'])
		{
			$where .= sprintf(" and find_in_set('%s',u_pct_ids)",$params['city']);
		}

		if($params['status'])
		{
            /**
             * 未申请 ua_pjl_shop_id = 0
             *使用中 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime > TIME()
             *已过期 ua_pjl_shop_id >0  ua_pjl_shop_status = 1 ua_pjl_shop_etime >0 a_pjl_shop_etime < TIME()
             *未缴费 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime =0
             *已停用 ua_pjl_shop_id >0  ua_pjl_shop_status = 0
             */
			switch ($params['status'])
			 {
				case '1': //使用中
					$where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=1 and ua_pjl_shop_etime > '%d'",$time);
					break;
				case '2': //已过期
					$where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=1 and ua_pjl_shop_etime <= '%s' and ua_pjl_shop_etime!=0",$time);
					break;
				case '3': //未缴费
				    $where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=1 and ua_pjl_shop_etime=0");
					break;
                case '4':
                    $where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=0");
			}
		}

		if($params['ua_score'])
		{
			$where .= sprintf(" and ua_score > '%d'",$params['ua_score']);
		}

		if($params['ua_pjl_shop_etime'])
		{
			//直接取区间就行了
			if($params['ua_pjl_shop_etime'] < 0)
			{
			    //查询要过期时间
				$end = time();
				$start = strtotime($params['ua_pjl_shop_etime'].'day');

			}
			else
			{ //查询已经过期的时间
				$end = strtotime($params['ua_pjl_shop_etime'].'day');
				$start = time();
			}
			$where .= sprintf(" and ua_pjl_shop_etime between %d and %d",$start,$end);
		}

		//剔除状态和crm保护的数据
		$where .= sprintf(" and u_status=1 and ua_crm_protect=0");

		//1.活跃TOP100（最多显示100条，按活跃度出一个月内无任何人跟进过的)
		if($params['type'] == 1)
		{
			$where .= sprintf(" and ua_uid not in (select uf_to_uid from yp_user_follow where uf_atime between %s and %s group by uf_to_uid )",strtotime('-1 month'),$time);
		}

		//已申请入驻
		if($params['type'] == 3)
		{
			$where .= sprintf(" AND ua_pjl_shop_id > 0");
		}

		//我跟进的（最多显示100条，按照自己跟进时间倒序）
		if($params['type'] == 2)
		{
			$where .= sprintf(" and ua_uid in (select uf_to_uid from yp_user_follow where uf_uid=%d group by uf_to_uid order by uf_atime)",$_SESSION['_userid']);
		}

		$filed = "ua_pjl_shop_id,ua_uid,u_name,ua_pjl_shop_status,ua_score,ua_pjl_shop_etime,ua_pjd_shop_id,ua_pjd_shop_status,ua_com_name,ua_com_style,ua_link_name,ua_link_tel,ui_province,ui_city";
		$order = 'ua_pv';

		$count = $ypwModel->YpwDb->One(sprintf("select count(*) from yp_user_act join yp_user on u_id=ua_uid join yp_user_ext on ui_uid = ua_uid where 1=1 %s",$where));
		if($params['sort']){
			switch ($params['sort']) {
				case 'ua_score':
					$order = 'ua_score';
					break;
				case 'shop_apply_time':
				    $shopId = $ypwModel->YpwDb->Table(sprintf("select ua_pjl_shop_id from yp_user_act join yp_user on u_id=ua_uid join yp_user_ext on ui_uid = ua_uid where 1=1 %s and ua_pjl_shop_id>0 order by null",$where));
				    if(empty($shopId)){
				    	echo "找不到需要导出的记录";exit();
				    }
				    $apply_time = $pjlBaseModel->get("pl_shop",['shop_id','shop_apply_time'],sprintf(" and shop_id in(%s) order by shop_apply_time desc limit %s,%s",implode(',', array_column($shopId,'ua_pjl_shop_id')),($page-1)*$limit,$limit));
				    if(!empty($apply_time)){
				    	  $page = 1;
				    	  $apply_time = array_column($apply_time['data'],'shop_apply_time','shop_id');
				           $temp = array_keys($apply_time);
				           array_push($temp, 0);
				           $where .= sprintf(" and ua_pjl_shop_id in (%s)",implode(',', $temp));
				    }else{
				    	$apply_time = [];
				    }
				    break;
				default:
					$order = 'ua_pv';
			}
		}



		$sql = sprintf("select %s from yp_user_act join yp_user on u_id=ua_uid join yp_user_ext on ui_uid = ua_uid where 1=1 %s order by %s desc",$filed,$where,$order);
		//echo $sql;exit();
		if($count <= 0)
		{
			echo "找不到需要导出的记录";exit();
		}

		/**
		 * [$listArr 最终查询数据]
		 * @var [type]
		 */
		$listArr = $ypwModel->YpwDb->Table(sprintf("%s limit %s,%s",$sql,($page-1)*$limit,$limit));

		if($params['sort'] != 'shop_apply_time'){
			$apply_time = $pjlBaseModel->get("pl_shop",['shop_id','shop_apply_time'],sprintf(" and shop_id in(%s) order by shop_apply_time desc",implode(',', array_column($listArr,'ua_pjl_shop_id'))),false);
			if(!empty($apply_time)){
				$apply_time = array_column($apply_time['data'],'shop_apply_time','shop_id');
			}else{
				$apply_time = [];
			}
		}

		/**
		 * [$uId Uid]
		 * @var [type|string]
		 */
		$uId = implode(',', array_unique(array_column($listArr,'ua_uid')));

		/**
		 * [$selfFollow 我跟进]
		 * @var [type|array]
		 */
		$selfFollow = $ypwModel->YpwDb->Table(sprintf("select b.uf_atime, b.uf_to_uid, b.uf_uname from ( select uf_to_uid, max(uf_atime) as uf_atime from yp_user_follow where uf_uid =%d group by uf_to_uid ) as a inner join yp_user_follow as b on a.uf_atime = b.uf_atime and a.uf_to_uid = b.uf_to_uid",$_SESSION['_userid']));

		if(!empty($selfFollow))
		{
			$selfFollow = array_column($selfFollow,null,'uf_to_uid');
		}
		else
		{
			$selfFollow = [];
		}
		/**
		 * [$lastFollow 最后跟进人]
		 * @var [type|array]
		 */
		$lastFollow = $ypwModel->YpwDb->Table(sprintf("select b.uf_atime, b.uf_to_uid, b.uf_uname from ( select uf_to_uid, max(uf_atime) as uf_atime from yp_user_follow where uf_to_uid in (%s) group by uf_to_uid ) as a inner join yp_user_follow as b on a.uf_atime = b.uf_atime and a.uf_to_uid = b.uf_to_uid",$uId));
		if(!empty($lastFollow))
		{
			$lastFollow = array_column($lastFollow,null,'uf_to_uid');
		}
		else
		{
			$lastFollow = [];
		}

		/**
		 * [$brand 品牌排行榜]
		 * @var [type|array]
		 */
		$brand = $ypwModel->YpwDb->Table(sprintf("select * from yp_user_act_brand where uab_uid in (%s)",$uId));

		/**
		 * [$parts 零件排行榜]
		 * @var [type|array]
		 */
		$parts = $ypwModel->YpwDb->Table(sprintf("select * from yp_user_act_part where uap_uid in (%s)",$uId));

		/**
		 * [$getUid 电话加密今天是否可以解开]
		 * @var [type|array]
		 */
		$getUid = $ypwModel->YpwDb->Table("select at_get_uid from yp_user_act_tjtel where date_format(from_unixtime(at_time),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d') and at_uid=".$_SESSION['_userid']." and at_get_uid in ('.$uId.')");

		$getUid = array_column($getUid,'at_get_uid');

		$brandTemp = [];
		//如果个数大于了三个，那么我就直接排序(倒叙)去掉最后
		foreach ($brand as $v)
		{
			$brandTemp[$v['uab_uid']][] = $v;

			if(count($brandTemp[$v['uab_uid']]) > 3)
			{
				array_multisort(array_column($brandTemp[$v['uab_uid']],'uab_count'),SORT_DESC,$brandTemp[$v['uab_uid']]);

				array_pop($brandTemp[$v['uab_uid']]);
			}
		}

		unset($brand);

		$partsTemp = [];

		foreach ($parts as  $item)
		{
			$partsTemp[$item['uap_uid']][] = $item;

			if(count($partsTemp[$item['uap_uid']]) > 3)
			{
				array_multisort(array_column($partsTemp[$item['uap_uid']],'uap_count'),SORT_DESC,$partsTemp[$item['uap_uid']]);

				array_pop($partsTemp[$item['uap_uid']]);
			}
		}

		unset($parts);

		/**
		 * [$address key=>城市,value=>省份]
		 * @var array
		 */
		$address = array_column($listArr,'ui_province','ui_city');

		$addressId = array_unique(array_merge(array_keys($address),array_values($address)));

		$addressData = $ypwModel->YpwDb->Table(sprintf("select pc_id,pc_name from yp_province_city where pc_id in (%s)",implode(',', $addressId)));

		$addressData = array_column($addressData,'pc_name','pc_id');
		if($params['type'] == 3){
			$shopId = array_column($listArr,'ua_pjl_shop_id');
		  if(!empty($shopId)){
			//XXX:wwww
			$end = date('Ymd',time());
            $start = date('Ymd',strtotime("-3 month"));
			$showCount = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get('tj_pjl_shop_date',['tpsd_shop_id','sum(tpsd_pv_count) as show_count'],sprintf(" and tpsd_shop_id in (%s) and tpsd_date between '%s' and '%s' group by tpsd_shop_id",implode(',',$shopId),$start,$end));
			if(!empty($showCount['data'])){
				$showCount = array_column($showCount['data'],'show_count','tpsd_shop_id');
			}else{
				$showCount = [];
			}
		  }
		}else{
			$shopId = [];
		}


		foreach ($listArr as $index => &$item)
		{

			/**
             * 未申请 ua_pjl_shop_id = 0
             *使用中 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime > TIME()
             *已过期 ua_pjl_shop_id >0  ua_pjl_shop_status = 1 ua_pjl_shop_etime >0 a_pjl_shop_etime < TIME()
             *未缴费 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime =0
             *已停用 ua_pjl_shop_id >0  ua_pjl_shop_status = 0
			 */
			$item['exp_time'] = '';

			if($item['ua_pjl_shop_id'] <= 0){
			    $item['status'] = '未申请'; //未申请
            }else if($item['ua_pjl_shop_id'] > 0){
			    if($item['ua_pjl_shop_status'] == 1){
			        if($item['ua_pjl_shop_etime']  <= 0){
                        $item['status'] = '未缴费'; //未缴费
                    }else{
                    	// $item['status'] = ''
                     //    $item['status'] = 2;
                        $item['exp_time'] = ceil((($item['ua_pjl_shop_etime'] - $time) / 86400));
                        if($item['exp_time'] > 0)
                        {
                        	$item['status'] = '使用中'.$item['exp_time'].'天';
                        }else{
                        	$item['status'] = '已过期'.$item['exp_time'].'天';
                        }
                    }
                }else{
			        $item['status'] = '已停用'; //已停用
                }
            }

            //处理展示总数
            if(isset($showCount[$item['ua_pjl_shop_id']]))
            {
            	$item['show_count'] = $showCount[$item['ua_pjl_shop_id']];
            }else{
            	$item['show_count'] = null;
            }

			//处理关注零件
			$item['parts'] = isset($partsTemp[$item['ua_uid']]) ? implode(',',array_column($partsTemp[$item['ua_uid']],'uap_part')) : '';

			//处理关注品牌
			$item['brand'] = isset($brandTemp[$item['ua_uid']]) ? implode(',',array_column($brandTemp[$item['ua_uid']],'uab_brand')) : '';

			$item['address'] = '';



			// if(!in_array($item['ua_uid'], $getUid))
			// {
			// 	//处理联系人
			// 	if(!empty($item['ua_link_name']))
			// 	{
			// 		$item['ua_link_name'] = $this->userNameCut($item['ua_link_name']);
			// 	}
			// 	$item['ua_link_tel'] = !empty($item['ua_link_tel']) ? substr_replace($item['ua_link_tel'], '****', 3, 4) : '';
			// }

			//处理城市
			if(!empty($item['ui_province']))
			{
				$item['address'] = $addressData[$item['ui_province']];
				if(!empty($item['ui_city']))
				{
					$item['address'] .= $addressData[$item['ui_city']];
				}
			}

			//处理最后跟进
			$item['last_follow'] = '';
			if(isset($lastFollow) && $lastFollow[$item['ua_uid']])
			{
				$item['last_follow'] = date('Y-m-d',$lastFollow[$item['ua_uid']]['uf_atime']).'/'.$this->userNameCut($lastFollow[$item['ua_uid']]['uf_uname']);
			}
			//var_dump($item['ua_pjl_shop_id']);
			if(!empty($apply_time) && isset($apply_time[$item['ua_pjl_shop_id']]))
			{
				$item['app_time'] = date('Y-m-d',$apply_time[$item['ua_pjl_shop_id']]);
			}

			//处理我跟进
			$item['self_follow'] = '';
			if(isset($selfFollow) && $selfFollow[$item['ua_uid']])
			{
				$item['self_follow'] = date('Y-m-d',$selfFollow[$item['ua_uid']]['uf_atime']);
			}
			if(!empty($item['ua_link_name'])){
                $item['ua_link_name']  = $item['u_name'] .'('.$item['ua_link_name']. ')';
            }else{
                $item['ua_link_name']  = $item['u_name'];
            }
		}
		if($params['sort'] == 'shop_apply_time'){
			array_multisort(array_column($listArr,'app_time'),SORT_DESC,$listArr);
		}
		unset($addressData);

		if(empty($listArr)){
			echo "找不到需要导出的记录";exit();
		}
		require mvc::$cfg['PATH_ROOT'].'vendor/'.'autoload.php';

        $newExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('我跟进');  //设置当前sheet的标题

        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setWidth(35);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setWidth(35);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setWidth(55);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
        $newExcel->getActiveSheet()->getColumnDimension('I')->setWidth(12);
        $newExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);

        //设置第一栏的标题
        $objSheet->setCellValue('A1', '活跃度')
                 ->setCellValue('B1', '公司名称')
                 ->setCellValue('C1', '联系人')
                 ->setCellValue('D1', '联系电话')
                 ->setCellValue('E1', '商铺到期')
                 ->setCellValue('F1', '关注品牌')
                 ->setCellValue('G1', '关注分类')
                 ->setCellValue('H1', '省市')
                 ->setCellValue('I1', '我跟进')
                 ->setCellValue('J1', '最后跟进');

        foreach ($listArr as $key => $value) {
        	//var_dump($value);exit();
        	$k = $key+2;
        	$objSheet->setCellValueExplicit('A' . $k, $value['ua_score'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('B' . $k, $value['ua_com_name'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('C' . $k, $value['ua_link_name'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('D' . $k, $value['ua_link_tel'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('E' . $k, $value['status'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('F' . $k, $value['brand'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('G' . $k, $value['parts'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('H' . $k, $value['address'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('I' . $k, $value['self_follow'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                     ->setCellValueExplicit('J' . $k, $value['last_follow'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
        }

        $this->downloadExcel($newExcel, '我跟进'.date('Y-m-d H:i:'), 'Xls');
	}

	/**
	 * [exportClientList description]
	 * @Author   Yangxing
	 * @DateTime 2020-06-09T13:51:24+0800
	 * @param    [type]                   $startTime [description]
	 * @param    [type]                   $endTime   [description]
	 * @return   [type]                              [description]
	 */
	public function exportClientList()
    {
    	require mvc::$cfg['PATH_ROOT'].'vendor/'.'autoload.php';
    	$adminList = [];

    	$rule = LibFc::checkDlRule('DL05', false);
		$Params = mvc::$URL_PARAMS;

		$PjlDaili = new PjlDaili();
		$uid = $rule? 0: $_SESSION['_userid'];
		$res = $PjlDaili->getDcoWorkers($_SESSION['_dcoid'], $uid);
		$workerArr = $res['data'];

		$PjlBase = new PjlBase();
		$table = 'pl_user JOIN pl_user_vip_list ON uvl_uid = pu_uid
		LEFT JOIN pl_shop ON shop_id = pu_uid
		LEFT JOIN dl_worker_invcode ON uvl_dwi_invcode = dwi_invcode
		LEFT JOIN dl_order_list ON pu_uid = dml_order_uid';
		if(!$rule)
		{
			$where = sprintf(' and ((dwi_dco_id = %d and dwi_dwo_uid = %d) OR (dml_dco_id = %d and dml_dwo_uid=%d))', $_SESSION['_dcoid'], $_SESSION['_userid'], $_SESSION['_dcoid'], $_SESSION['_userid']);
		}
		else if(!empty($Params['dwo_uid']))
		{
			$where = sprintf(' and ((dwi_dco_id = %d and dwi_dwo_uid = %d) OR (dml_dco_id = %d and dml_dwo_uid=%d))', $_SESSION['_dcoid'], $Params['dwo_uid'], $_SESSION['_dcoid'], $Params['dwo_uid']);
		}
		else
		{
			$where = sprintf(' and (dwi_dco_id = %d OR dml_dco_id = %d)', $_SESSION['_dcoid'], $_SESSION['_dcoid']);
		}

		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'pu_uid':
					$where .= sprintf(" and %s=%d", $filed, $val);
				break;
				case 'dml_style':
				case 'dml_dwi_invcode':
					$where .= sprintf(" and %s='%s'", $filed, $val);
				break;
				case 'user':
					$LibYpApi = new LibYpApi();
					$dataArr = [
						'filed'=>['u_id'],
						'where'=>sprintf("and (u_name like '%%%s%%' or (u_mobile ='%s' and u_mobile_check='Y'))", $val, $val)
					];
					$res = $LibYpApi->Get('user/getUser', [], $dataArr);
					if(!empty($res['data']))
					{
						$where .= sprintf(" and (shop_name like '%%%s%%' or pu_uid in (%s))", $val, implode(',', array_column($res['data'], 'u_id')));
					}
					else
					{
						$where .= sprintf(" and shop_name like '%%%s%%'", $val);
					}
				break;
			}
		}
		$where .=' GROUP BY pu_uid';
		//$res = $PjlBase->get($table, ['count(distinct pu_uid) count'], $where);
		$filed = ['pu_uid, shop_id, CASE WHEN shop_style IS NOT NULL THEN shop_style ELSE pu_work_style END AS user_style, CASE WHEN shop_pct_ids IS NOT NULL THEN shop_pct_ids ELSE pu_pct_ids END AS pct_ids, shop_vip_etime AS shop_end_time, shop_name, shop_status, MAX(uvl_dwi_invcode) as uvl_dwi_invcode, shop_addr, CASE WHEN dml_dwo_uid IS NOT NULL THEN dml_dwo_uid ELSE dwi_dwo_uid END AS pu_dwo_uid'];
			$res = $PjlBase->get($table, $filed,sprintf('%s ORDER BY shop_end_time, pu_pct_ids, shop_pct_ids', $where));
			if(empty($res['data'])){
				echo '不存在导出记录';exit();
			}
			$listArr = $res['data'];
				$YpwAddr = new YpwAddr();

				$LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name', 'u_mobile'],
					'where'=>sprintf("and u_id in(%s)", implode(',', array_column($listArr, 'pu_uid')))
				];
				$res = $LibYpApi->Get('user/getUser', [], $dataArr);
				$userArr = array_column($res['data'], null, 'u_id');
				foreach($listArr as $k=>$v)
				{
					$res = $YpwAddr->getAddrByIds($v['pct_ids']);
					$v['addr'] = implode('', $res['data']).$v['shop_addr'];
					if(!empty($userArr[$v['pu_uid']])) $v = array_merge($v, $userArr[$v['pu_uid']]);
					if(!empty($workerArr[$v['pu_dwo_uid']])) $v = array_merge($v, $workerArr[$v['pu_dwo_uid']]);
					$v['shop_end_date'] = $v['shop_end_time'] > 0? date('Y-m-d', $v['shop_end_time']): '';
					$v['shop_end_count'] = $v['shop_end_time'] > 0 ? round(($v['shop_end_time']-time())/3600/24): '';
					if($v['shop_end_date'] == '' && $v['shop_id'] > 0){
						$v['status'] = '送商铺体验';
					}else{
						if($v['shop_end_count'] > 0 && $v['shop_end_count'] < 30){
							$v['status'] = '【'.$v['shop_end_count'].'天】';
						}else{
							$v['status'] = '已过期';
						}
					}
					$listArr[$k] = $v;
				}
        $newExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $newExcel->getProperties()
                     ->setCreator("Helloweba")    //作者
                     ->setLastModifiedBy("Yuegg") //最后修改者
                     ->setTitle("Office 2007 XLSX Test Document")  //标题
                     ->setSubject("Office 2007 XLSX Test Document") //副标题
                     ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes."      )  //描述
                     ->setKeywords("office 2007 openxml php") //关键字
                     ->setCategory("Test result file"); //分类
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('客户管理');  //设置当前sheet的标题

        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setWidth(35);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setWidth(25);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setWidth(85);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);

        //设置第一栏的标题
        $objSheet->setCellValue('A1', '会员名')
                 ->setCellValue('B1', '商铺名称')
                 ->setCellValue('C1', '到期时间')
                 ->setCellValue('D1', '类型')
                 ->setCellValue('E1', '手机')
                 ->setCellValue('F1', '地址')
                 ->setCellValue('G1', '业务员')
                 ->setCellValue('H1', '邀请码');

        foreach ($listArr as $key => $value) {
        	$k = $key+2;
        	  $objSheet->setCellValueExplicit('A' . $k, $value['u_name'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('B' . $k, $value['shop_name'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('C' . $k, $value['status'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('D' . $k, $value['user_style'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('E' . $k, $value['u_mobile'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('F' . $k, $value['addr'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('G' . $k, $value['dwo_name'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING)
                       ->setCellValueExplicit('H' . $k, $value['uvl_dwi_invcode'],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
        }
        $this->downloadExcel($newExcel, '客户管理'.date('Y-m-d H:i:'), 'Xls');
    }

	 //公共文件，用来传入xls并下载
    function downloadExcel($newExcel, $filename, $format)
    {
    	//require mvc::$cfg['PATH_ROOT'].'vendor/'.'autoload.php';
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($newExcel, $format);
        //var_dump($objWriter);exit();
        $objWriter->save("php://output");

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        //header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        //header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        //header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        //header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        //header('Pragma: public'); // HTTP/1.0
        exit;
    }

	function getClientList()
	{
		$rule = LibFc::checkDlRule('DL05', false);
		$Params = mvc::$URL_PARAMS;

		$PjlDaili = new PjlDaili();
		$uid = $rule? 0: $_SESSION['_userid'];
		$res = $PjlDaili->getDcoWorkers($_SESSION['_dcoid'], $uid);
		$workerArr = $res['data'];

		$PjlBase = new PjlBase();
		$table = 'pl_user JOIN pl_user_vip_list ON uvl_uid = pu_uid
		LEFT JOIN pl_shop ON shop_id = pu_uid
		LEFT JOIN dl_worker_invcode ON uvl_dwi_invcode = dwi_invcode
		LEFT JOIN dl_order_list ON pu_uid = dml_order_uid';
		if(!$rule)
		{
			$where = sprintf(' and ((dwi_dco_id = %d and dwi_dwo_uid = %d) OR (dml_dco_id = %d and dml_dwo_uid=%d))', $_SESSION['_dcoid'], $_SESSION['_userid'], $_SESSION['_dcoid'], $_SESSION['_userid']);
		}
		else if(!empty($Params['dwo_uid']))
		{
			$where = sprintf(' and ((dwi_dco_id = %d and dwi_dwo_uid = %d) OR (dml_dco_id = %d and dml_dwo_uid=%d))', $_SESSION['_dcoid'], $Params['dwo_uid'], $_SESSION['_dcoid'], $Params['dwo_uid']);
		}
		else
		{
			$where = sprintf(' and (dwi_dco_id = %d OR dml_dco_id = %d)', $_SESSION['_dcoid'], $_SESSION['_dcoid']);
		}

		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'pu_uid':
					$where .= sprintf(" and %s=%d", $filed, $val);
				break;
				case 'dml_style':
				case 'dml_dwi_invcode':
					$where .= sprintf(" and %s='%s'", $filed, $val);
				break;
				case 'user':
					$LibYpApi = new LibYpApi();
					$dataArr = [
						'filed'=>['u_id'],
						'where'=>sprintf("and (u_name like '%%%s%%' or (u_mobile ='%s' and u_mobile_check='Y'))", $val, $val)
					];
					$res = $LibYpApi->Get('user/getUser', [], $dataArr);
					if(!empty($res['data']))
					{
						$where .= sprintf(" and (shop_name like '%%%s%%' or pu_uid in (%s))", $val, implode(',', array_column($res['data'], 'u_id')));
					}
					else
					{
						$where .= sprintf(" and shop_name like '%%%s%%'", $val);
					}
				break;
			}
		}
		$res = $PjlBase->get($table, ['count(distinct pu_uid) count'], $where, true);
		$where .=' GROUP BY pu_uid';
		$count = $res['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$filed = ['pu_uid, shop_id, CASE WHEN shop_style IS NOT NULL THEN shop_style ELSE pu_work_style END AS user_style, CASE WHEN shop_pct_ids IS NOT NULL THEN shop_pct_ids ELSE pu_pct_ids END AS pct_ids, shop_vip_etime AS shop_end_time, shop_name, shop_status, MAX(uvl_dwi_invcode) as uvl_dwi_invcode, shop_addr, CASE WHEN dml_dwo_uid IS NOT NULL THEN dml_dwo_uid ELSE dwi_dwo_uid END AS pu_dwo_uid'];
			$res = $PjlBase->get($table, $filed,sprintf('%s ORDER BY shop_end_time, pu_pct_ids, shop_pct_ids limit %s, %s', $where, ($page-1)*$limit, $limit));
			if(!empty($res['data']))
			{
				$listArr = $res['data'];
				$YpwAddr = new YpwAddr();

				$LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name', 'u_mobile'],
					'where'=>sprintf("and u_id in(%s)", implode(',', array_column($listArr, 'pu_uid')))
				];
				$res = $LibYpApi->Get('user/getUser', [], $dataArr);
				$userArr = array_column($res['data'], null, 'u_id');
				foreach($listArr as $k=>$v)
				{
					$res = $YpwAddr->getAddrByIds($v['pct_ids']);
					$v['addr'] = implode('', $res['data']).$v['shop_addr'];
					if(!empty($userArr[$v['pu_uid']])) $v = array_merge($v, $userArr[$v['pu_uid']]);
					if(!empty($workerArr[$v['pu_dwo_uid']])) $v = array_merge($v, $workerArr[$v['pu_dwo_uid']]);
					$v['shop_end_date'] = $v['shop_end_time'] > 0? date('Y-m-d', $v['shop_end_time']): '';
					$v['shop_end_count'] = $v['shop_end_time'] > 0 ? round(($v['shop_end_time']-time())/3600/24): '';
					$listArr[$k] = $v;
				}
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$listArr
		];
		echo json_encode($arr);
	}


	//申请体验商铺权益 15天
	function applyFreeShop()
	{
		$Params = mvc::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('pjl/applyFreeShop', ['uid'=>$Params['shop_id']]);
		LibFc::ajaxJsonEncode($res);
	}


	//邀请记录
	function yqList()
	{
		$Params = mvc::$URL_PARAMS;
		$PjlDaili = new PjlDaili();
		$rule = LibFc::checkDlRule('DL03', false);
		$uid = $rule? 0: $_SESSION['_userid'];
		$res = $PjlDaili->getDcoWorkers($_SESSION['_dcoid'], $uid);
		LibTpl::Set('workerArr', $res['data']);

		$endDayArr = [
			7=>'7天内',
			15=>'15天内',
			30=>'30天内',
			60=>'60天内',
			90=>'90天内',
			-7=>'过期7天',
			-15=>'过期15天',
			-30=>'过期30天',
			-60=>'过期60天',
			-365=>'所有过期'
		];
		LibTpl::Set('endDayArr', $endDayArr);

		LibTpl::Set('rule', $rule);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '邀请记录');
		LibTpl::Put();
	}


	//邀请码列表
	function getYqList()
	{
		$rule = LibFc::checkDlRule('DL03', false);
		$Params = mvc::$URL_PARAMS;
		$PjlBase = new PjlBase();
		$table = 'dl_order_list as a
		join pl_user_vip_list on dml_order_id = uvl_id
		left join pl_shop on shop_id=dml_shop_id 
		left join dl_worker on dml_dco_id=dwo_dco_id and dml_dwo_uid=dwo_uid';
		$where = sprintf(' and dwo_dco_id=%d', $_SESSION['_dcoid']);
		if(!$rule) $where .= sprintf(' and dml_dwo_uid=%d', $_SESSION['_userid']);
		$order = 'order by dml_atime desc';
		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'dml_dwo_uid':
				case 'dml_order_uid':
				case 'dml_shop_id':
					$where .= sprintf(" and %s=%d", $filed, $val);
				break;
				case 'dml_style':
				case 'dml_dwi_invcode':
					$where .= sprintf(" and %s='%s'", $filed, $val);
				break;
				case 'user':
					$LibYpApi = new LibYpApi();
					$dataArr = [
						'filed'=>['u_id'],
						'where'=>sprintf("and (u_name like '%%%s%%' or (u_mobile ='%s' and u_mobile_check='Y'))", $val, $val)
					];
					$res = $LibYpApi->Get('user/getUser', [], $dataArr);
					if(!empty($res['data']))
					{
						$where .= sprintf(" and (shop_name like '%%%s%%' or dml_order_uid in (%s))", $val, implode(',', array_column($res['data'], 'u_id')));
					}
					else
					{
						$where .= sprintf(" and shop_name like '%%%s%%'", $val);
					}
				break;
				case 'dwo_name':
					$where .= sprintf(" and %s like '%%%s%%'", $filed, $val);
				break;
				case 'dml_atime':
					$t = explode(' ~ ', $val);
					$where .= sprintf(" and dml_atime >= %d and dml_atime <= %d", strtotime($t[0]), strtotime($t[1].' 23:59:59'));
				break;
				case 'pjlshop_etime':
					$val = (int) $val;
					if($val < 0){
						$where .= sprintf(" and (CASE WHEN dml_style = 'shop' THEN (shop_id > 0 and shop_vip_etime <=%d and shop_vip_etime > 0) ELSE (uvl_now_etime <%d) END )", time(),time());
						if($val !== -365) $where .= sprintf(" and (CASE WHEN  dml_style = 'shop' THEN (shop_vip_etime >=%d) ELSE (uvl_now_etime>%d) END)", strtotime($val.'day'),strtotime($val.'day'));	
						$order = " order by CASE WHEN dml_style = 'shop' THEN  shop_vip_etime ELSE uvl_now_etime END desc";
					}else if($val > 0){
						$where .= sprintf(' and (CASE WHEN dml_style = \'shop\' THEN (shop_id > 0 and shop_vip_etime >= %d and shop_vip_etime <= %d) ELSE (uvl_now_etime >=%d AND uvl_now_etime<= %d) END)', time(), strtotime('+'.$val.'day'),time(), strtotime('+'.$val.'day'));
						$order = " order by CASE WHEN dml_style = 'shop' THEN  shop_vip_etime ELSE uvl_now_etime END ASC";
					}
				break;
				case 'etime':
					$temp = explode('~',$val);
					if(count($temp)>1){
						$where .= sprintf(" and (CASE WHEN  dml_style = 'shop' THEN (shop_id > 0 and shop_vip_etime between %d and %d) ELSE ( uvl_now_etime between %d and %d) END)", strtotime($temp[0]),strtotime($temp[1])+86399, strtotime($temp[0]),strtotime($temp[1])+86399);
					}
					$order = " order by CASE WHEN dml_style = 'shop' THEN  shop_vip_etime ELSE uvl_now_etime END desc";
				break;
			}
		}
		$res = $PjlBase->get($table, ['count(*) count'], $where, true);
		$count = $res['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$filed = ['shop_id', 'shop_name', 'shop_vip_etime','shop_apply_time','uvl_now_etime','a.*', 'dwo_name'];

			$res = $PjlBase->get($table, $filed,sprintf('%s %s limit %s, %s', $where,$order, ($page-1)*$limit, $limit));
			if(!empty($res['data']))
			{
				$listArr = $res['data'];

				$LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf("and u_id in(%s)", implode(',', array_column($listArr, 'dml_order_uid')))
				];
				$res = $LibYpApi->Get('user/getUser', [], $dataArr);
				$userArr = array_column($res['data'], null, 'u_id');

				foreach($listArr as $k=>$v)
				{
					$v['username'] = $userArr[$v['dml_order_uid']]['u_name'];
					$v['dml_style_name'] = $this->allStyle[$v['dml_style']];
					$v['dml_atime'] = date('Y-m-d H:i', $v['dml_atime']);
					$listArr[$k] = $v;
				}
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$listArr
		];
		echo json_encode($arr);
	}



	//业务员管理
	function worker()
	{
		LibFc::checkDlRule('DL01');
		LibTpl::Set('title', '业务员管理');
		LibTpl::Put();
	}


	//业务员列表
	function getWorker()
	{
		LibFc::checkDlRule('DL01');
		$Params = mvc::$URL_PARAMS;
		$where = sprintf('and dwo_dco_id=%d', $_SESSION['_dcoid']);
		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'keyword':
					$where .= sprintf(" and (dwo_name like '%%%s%%' or dwo_tel like '%%%s%%')", $val, $val);
				break;
			}
		}

		$PjlBase = new PjlBase();
		$res = $PjlBase->get('dl_worker',['count(*) count'], $where, true);
		$count = $res['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$res = $PjlBase->get('dl_worker',['*'],sprintf('%s order by dwo_status desc, CONVERT(dwo_name using gbk) asc limit %s, %s', $where, ($page-1)*$limit, $limit));
			if (!empty($res['data']))
			{
				$listArr = $res['data'];

				$uidArr = array_column($listArr, 'dwo_uid');

				$where = sprintf(" and dml_dco_id=%d and dml_dwo_uid in (%s) GROUP BY dml_dwo_uid", $_SESSION['_dcoid'], implode(',', $uidArr));
				$res = $PjlBase->get('dl_order_list', ['dml_dwo_uid, sum(dml_money_pay) as ywtotal'], $where);
				$moneyArr = array_column($res['data'], null, 'dml_dwo_uid');

	            $LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf("and u_id in(%s)", implode(',', $uidArr))
				];
				$res = $LibYpApi->Get('user/getUser', [], $dataArr);
				$userArr = array_column($res['data'], null, 'u_id');

				//获取对应的邀请码
				$res = $PjlBase->get('dl_worker_invcode',['*'],sprintf('and dwi_dco_id=%d and dwi_dwo_uid in (%s)', $_SESSION['_dcoid'], implode(',', $uidArr)));
				$invArr = [];
				foreach($res['data'] as $v)
				{
					$invArr[$v['dwi_dwo_uid']][] = $v;
				}

				foreach($listArr as $k=>$v)
				{
					if(!empty($userArr[$v['dwo_uid']])) $v = array_merge($v, $userArr[$v['dwo_uid']]);
					$v['ywtotal'] = empty($moneyArr[$v['dwo_uid']]['ywtotal'])? '' :$moneyArr[$v['dwo_uid']]['ywtotal'];
					$v['invcodes'] = empty($invArr[$v['dwo_uid']])? []: $invArr[$v['dwo_uid']];
					$v['dwo_atime'] = date('Y-m-d', $v['dwo_atime']);
					$listArr[$k] = $v;
				}
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$listArr
		];
		echo json_encode($arr);
	}


	//新增、编辑业务员信息
	function editWorkerHtml()
	{
		LibFc::checkDlRule('DL01');
		$Params = mvc::$URL_PARAMS;
		$PjlBase = new PjlBase();
		if(!empty($Params['dwo_uid']))
		{
			$res = $PjlBase->get('dl_worker',['*'], sprintf(" and dwo_uid=%d", $Params['dwo_uid']), true);
			$workerArr = $res['data'];
			//获取用户的名字
			if(!empty($workerArr))
			{
				$where = sprintf("and u_id =%s ", $workerArr['dwo_uid']);
	            $LibYpApi = new LibYpApi();
				$dataArr = [
					'filed' => ['u_id','u_name'],
					'where' => $where,
					'oneRow' => true
				];
				$res = $LibYpApi->Get('user/getUser', [], $dataArr);
				$workerArr['u_name'] = $res['data']['u_name'];
			}
			$workerArr['rules'] = explode(',', $workerArr['dwo_rule_ids']);
			LibTpl::Set('workerArr', $workerArr);
		}

		$res = $PjlBase->get('dl_rule',['rule_id','rule_name'], ' order by rule_path');
		LibTpl::Set('ruleArr',$res['data']);

		LibTpl::Set('Params', $Params);
		$res = LibTpl::Fetch();
		echo $res;
	}


	//新增、保存业务员信息
	function editWorker()
	{
		LibFc::checkDlRule('DL01');
		$data = $_POST;
		$PjlBase = new PjlBase();
		$newFlag = false;
		$uid = (int) $data['dwo_uid'];
		//获取宜配账号ID
		if(!empty($data['username']) && $uid < 1)
		{
			$username = LibFc::Escape($data['username']);
			$where = sprintf("and (u_name = '%s' or u_mobile='%s' and u_mobile_check='Y') ", $username, $username);
			$LibYpApi = new LibYpApi();
			$dataArr = [
				'filed'=>['u_id','u_name'],
				'where'=>$where,
				'oneRow'=>true
			];
			$res = $LibYpApi->Get('user/getUser', [], $dataArr);
			if(empty($res['data'])) LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'此账号尚未注册，请先前往跑街令APP注册！']);
			$uid = $res['data']['u_id'];

			$res = $PjlBase->get('dl_worker',['dwo_uid'], sprintf(" and dwo_uid=%d and dwo_dco_id=%d", $uid, $_SESSION['_dcoid']), true);
			if(empty($res['data'])) $newFlag = true;
		}

		$setArr = [
			'dwo_status'=>$data['dwo_status'],
			'dwo_name'=>$data['dwo_name'],
			'dwo_tel'=>$data['dwo_tel'],
			'dwo_remark'=>$data['dwo_remark']
		];
		$setArr['dwo_rule_ids'] = empty($data['rule'])? '': implode(',', $data['rule']);

		if($newFlag)
		{
			$setArr['dwo_dco_id'] = $_SESSION['_dcoid'];
			$setArr['dwo_uid'] = $uid;
			$setArr['dwo_atime'] = time();
			$res = $PjlBase->add('dl_worker', $setArr);
		}
		else
		{
			$res = $PjlBase->set('dl_worker', $setArr, sprintf(" and dwo_uid=%d and dwo_dco_id=%d", $uid, $_SESSION['_dcoid']));
		}
		LibFc::ajaxJsonEncode($res);
	}


	//删除业务员
	function delWorker()
	{
		$Params = mvc::$URL_PARAMS;
		LibFc::checkDlRule('DL01');
		$PjlDaili = new PjlDaili();
		$uid = (int) $Params['dwo_uid'];
		$res = $PjlDaili->delWorker($_SESSION['_dcoid'], $uid);
		LibFc::ajaxJsonEncode($res);
	}


	//邀请码管理
	function invcodeList()
	{
		$Params = mvc::$URL_PARAMS;
		$PjlDaili = new PjlDaili();
		$PjlDaili->rebuildinvcodeEwm('');
		$res = $PjlDaili->get('dl_company',['dco_tc'], sprintf(" and dco_id=%d", $_SESSION['_dcoid']), true);
		$docArr = $res['data'];

		$rule = LibFc::checkDlRule('DL01', false);
		$where =  sprintf(" and dwo_dco_id=%d", $_SESSION['_dcoid']);
		if(!$rule) $where .=  sprintf(" and dwo_uid=%d", $_SESSION['_userid']);
		$res = $PjlDaili->get('dl_worker',['dwo_uid', 'dwo_name'], $where.' order by dwo_status desc, CONVERT(dwo_name using gbk) asc');
		LibTpl::Set('workerArr', $res['data']);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('rule', $rule);
		LibTpl::Set('docArr', $docArr);
		LibTpl::Set('title', '邀请码管理');
		LibTpl::Put();
	}


	//邀请码列表
	function getInvcodeList()
	{
		$rule = LibFc::checkDlRule('DL01', false);
		$Params = mvc::$URL_PARAMS;
		$PjlBase = new PjlBase();
		$table = 'dl_worker_invcode join dl_worker on dwo_dco_id=dwi_dco_id and dwi_dwo_uid=dwo_uid';
		$where = sprintf(' and dwo_dco_id=%d', $_SESSION['_dcoid']);
		if(!$rule) $where .= sprintf(' and dwi_dwo_uid=%d', $_SESSION['_userid']);
		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'dwo_uid':
					$where .= sprintf(" and dwi_dwo_uid=%d", (int) $val);
				break;
				case 'dwi_invcode':
					$where .= sprintf(" and %s like '%%%s%%'", $filed, $val);
				break;
			}
		}
		$res = $PjlBase->get($table, ['count(*) count'], $where, true);
		$count = $res['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$res = $PjlBase->get($table,['*'],sprintf('%s order by dwo_status desc, CONVERT(dwo_name using gbk) asc, dwi_shop_price desc limit %s, %s', $where, ($page-1)*$limit, $limit));
			if (!empty($res['data']))
			{
				$listArr = $res['data'];
				$where = sprintf(" and dml_dwi_invcode in ('%s') GROUP BY dml_dwi_invcode", implode("','", array_column($listArr, 'dwi_invcode')));
				$res = $PjlBase->get('dl_order_list', ['dml_dwi_invcode, sum(dml_money_pay) as dml_money_pay'], $where);
				$moneyArr = array_column($res['data'], 'dml_money_pay', 'dml_dwi_invcode');

				$res = $PjlBase->get('dl_company', ['*'], sprintf(' and dco_id=%d', $_SESSION['_dcoid']), true);
				$comArr = $res['data'];

				$uidArr = array_column($listArr, 'dwo_uid');
	            $LibYpApi = new LibYpApi();
				$dataArr = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf("and u_id in(%s)", implode(',', $uidArr))
				];
				$res = $LibYpApi->Get('user/getUser', [], $dataArr);
				$userArr = array_column($res['data'], null, 'u_id');
				$styleArr = ['shop', 'pcyear', 'pchyear', 'pcmonth'];
				foreach($listArr as $k=>$v)
				{
					if(!empty($userArr[$v['dwo_uid']])) $v = array_merge($v, $userArr[$v['dwo_uid']]);
					foreach($styleArr as $style)
					{
						if($rule)
						{
							$v[$style.'_selftc'] = sprintf('%.2f', $v['dwi_'.$style.'_price'] - $v['dwi_'.$style.'_gstc']);
						}
						unset($v['dwi_'.$style.'_gstc']);
					}
					$v['dml_money_pay'] = empty($moneyArr[$v['dwi_invcode']])? '' :$moneyArr[$v['dwi_invcode']];
					$v['dwi_invcode_url'] = $v['dwi_invcode_url'].'?ver='.date('Ym');
					unset($v['dwi_etime']);
					if($v['dwo_status'] == -1) $v['dwo_name'] .= '【停用】';
					$listArr[$k] = $v;
				}
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$listArr
		];
		echo json_encode($arr);
	}


	//删除邀请码
	function delInvcode()
	{
		$Params = mvc::$URL_PARAMS;
		if(empty($Params['dwi_invcode'])) LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'获取邀请码失败！']);
		$rule = LibFc::checkDlRule('DL01', false);
		$where = sprintf(" and dwi_invcode = '%s' and dwi_dco_id=%d", LibFc::Escape($Params['dwi_invcode']), $_SESSION['_dcoid']);
		if(!$rule) $where .= sprintf(" and dwi_dwo_uid=%d", $_SESSION['_userid']);

		$PjlDaili = new PjlDaili();
		$res = $PjlDaili->get('dl_worker_invcode', ['dwi_invcode'], $where, true);
		if(!empty($res['data']))
		{
			$res = $PjlDaili->delInvcode([$res['data']['dwi_invcode']]);
			LibFc::ajaxJsonEncode($res);
		}
		LibFc::ajaxJsonEncode(['status' => false, 'data' => '邀请码不存在，请稍后重试！' ]);
	}

	//新增邀请码
	function getSetWorkerInvcode()
	{
		LibFc::checkDlRule('DL01');
		$Params = mvc::$URL_PARAMS;
		$PjlDaili = new PjlDaili();

		//前缀
		$res = $PjlDaili->get('dl_company join dl_worker on dwo_dco_id = dco_id',['dco_code, dco_tc, dwo_name'], sprintf(" and dco_id=%d and dwo_uid=%d", $_SESSION['_dcoid'], $Params['dwo_uid']), true);
		$arr = $res['data'];
		$arr['dco_tc'] = json_decode($arr['dco_tc'], true);

		$res = $PjlDaili->get('dl_worker_invcode as a left join dl_order_list on dml_dwi_invcode=dwi_invcode',['a.*, sum(dml_money_pay) as yjmoney'], sprintf(" and dwi_dco_id=%d and dwi_dwo_uid = %d group by dwi_invcode order by dwi_status desc, dwi_shop_price desc", $_SESSION['_dcoid'], $Params['dwo_uid']));
		$arr['has'] = $res['data'];

		LibFc::ajaxJsonEncode(['status' => true, 'data' => $arr]);
	}


	//修改邀请码
	function setWorkerInvcode()
	{
		LibFc::checkDlRule('DL01');
		$PjlDaili = new PjlDaili();
		$res = $PjlDaili->editWorkerInvcode($_SESSION['_dcoid'], $_POST['dwo_uid'], $_POST['invs']);
		LibFc::ajaxJsonEncode($res);
	}



	//提成统计
	function tcTj()
	{
		$Params = mvc::$URL_PARAMS;
		$PjlDaili = new PjlDaili();
		$rule = LibFc::checkDlRule('DL04', false);
		$uid = $rule? 0: $_SESSION['_userid'];
		$res = $PjlDaili->getDcoWorkers($_SESSION['_dcoid'], $uid);
		$workerArr = $res['data'];
		LibTpl::Set('workerArr', $workerArr);

		$where = sprintf(" and dml_dco_id=%d  and dml_dwo_uid in (%s)", $_SESSION['_dcoid'], implode(',', array_keys($workerArr)));

		if(!isset($Params['dml_atime'])) $Params['dml_atime'] = date('Y-m-01').' ~ '.date('Y-m-d');

		if(!empty($Params['dml_atime']))
		{
			$t = explode(' ~ ', $Params['dml_atime']);
			$where .= sprintf(" and dml_atime >= %d and dml_atime <= %d", strtotime($t[0]), strtotime($t[1].' 23:59:59'));
		}
		$res = $PjlDaili->get('dl_order_list', ['dml_dwo_uid, dml_style, sum(dml_money_pay) as dml_money_pay,sum(dml_money_selftc) as dml_money_selftc,sum(dml_money_ywytc) as dml_money_ywytc, count(*) as order_count'], $where.'  GROUP BY dml_dwo_uid, dml_style');
		$tjArr = [];
		$total = [];
		foreach($workerArr as $uid=>$v)
		{
			if(empty($tjArr[$uid])) $tjArr[$uid] = [];
		}
		foreach($res['data'] as $v)
		{
			$tjArr[$v['dml_dwo_uid']][$v['dml_style']] = $v;
			$tjArr[$v['dml_dwo_uid']]['dml_money_pay'] += $v['dml_money_pay'];
			$tjArr[$v['dml_dwo_uid']]['dml_money_selftc'] += $v['dml_money_selftc'];
			$tjArr[$v['dml_dwo_uid']]['order_count'] += $v['order_count'];
			$total[$v['dml_style']]['dml_money_pay'] += $v['dml_money_pay'];
			$total[$v['dml_style']]['dml_money_selftc'] += $v['dml_money_selftc'];
			$total[$v['dml_style']]['dml_money_ywytc'] += $v['dml_money_ywytc'];
			$total[$v['dml_style']]['order_count'] += $v['order_count'];
		}

		$fastTime = [
			'本月'=>date('Y-m-01').' ~ '.date('Y-m-d'),
			'上个月'=>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('total', $total);
		LibTpl::Set('fastTime', $fastTime);
		LibTpl::Set('tjArr', $tjArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('rule', $rule);
		LibTpl::Set('title', '提成统计');
		LibTpl::Put();
	}

	/**
	 * [activeUsers 列表]
	 * @Author   Yangxing
	 * @DateTime 2020-05-12T15:35:57+0800
	 * @return   [type]                   [description]
	 */
	public function activeUsers()
	{
		//todo 权限
		LibTpl::Set('endArr',[
			 7 => '7天内',
			15 => '15天内',
			30 => '30天内',
			60 => '60天内',
			90 => '90天内',
           -7  => '过期7天',
		   -15 => '过期15天',
		   -30 => '过期30天',
		   -60 => '过期60天',
		]);
		$model = new YpwBase;
		$time = time();
		$pls = new PjlBase();
		$isYp =  $pls->get("dl_company",['dco_isyp'],sprintf(" and dco_isyp=1 and dco_id=%d",$_SESSION['_dcoid']),true);
		if($isYp['data']['dco_isyp'] == 1){
			$pctIds = $pls->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_end >'%s' and dco_status=1",$time));
			if(!empty($pctIds['data'])){
				$pctIds = array_column($pctIds['data'],'dctp_pc_id');
			}
			$address = $model->YpwDb->table(sprintf('select pc_id,pc_name from yp_province_city where pc_id not in (%s) and pc_pid=0',implode(',', $pctIds)));
		}else{
			$pctIds = $pls->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_dco_id in (%s) and dct_end>'%s' and dco_status=1",$_SESSION['_dcoid'],$time));
		   $pctIds = array_column($pctIds['data'],'dctp_pc_id');
		   if(!empty($pctIds)){
		      $address = $model->YpwDb->table(sprintf('select pc_id,pc_name from yp_province_city where pc_id in (%s) and pc_pid=0',implode(',', $pctIds)));
		   }
		}
		LibTpl::Set('address',$address ?: []);
		LibTpl::Set('title', '活跃用户');
		LibTpl::Put();
	}

	/**
	 * [showMobile 查看手机号]
	 * @Author   Yangxing
	 * @DateTime 2020-05-12T15:35:50+0800
	 * @return   [type]                   [description]
	 */
	public function showMobile()
	{

		$Params = mvc::$URL_PARAMS;

		$model = new YpwBase();

		if(empty($Params['uid']))
		{
           LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}
		$max = ['dco'=>300, 'uid'=>50];
		//内部员工不限制数量
		if($_SESSION['_dcoid'] == 1 && in_array($_SESSION['_userid'], [669553,669578,669581,673937,480035,434497,151295,334744]))
		{
			$max = ['dco'=>3000, 'uid'=>500];
		}


		$where = sprintf('and dwo_dco_id=%d', $_SESSION['_dcoid']);
		$pjlBase = new PjlBase();
		$res = $pjlBase->get('dl_worker',['dwo_uid'], $where);
		$worker = array_column($res['data'],'dwo_uid');
		$sql = "select at_uid from yp_user_act_tjtel where date_format(from_unixtime(at_time),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d') and at_uid in (".implode(',', $worker).")";
		$actTjtel = $model->YpwDb->Table($sql);

		if(count($actTjtel) >= $max['dco'])
		{
			 LibFc::ajaxJsonEncode(['status' => false,'data' => "查看电话号码超过限制"]);
		}

		$result = array_count_values(array_column($actTjtel,'at_uid'));

		if($result[$_SESSION['_userid']] >= $max['uid'])
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '查看电话号码超过限制']);
		}


		$mobile = $model->YpwDb->Row(sprintf("select u_name,ua_link_tel,ua_link_name from yp_user_act join yp_user on ua_uid=u_id where ua_uid=%d",$Params['uid']));
		if($mobile['ua_link_tel'])
		{
		    $model->add('yp_user_act_tjtel',[
		        'at_uid' => $_SESSION['_userid'],
		        'at_get_uid' => $Params['uid'],
		        'at_time' => time()
		    ]);

		    if(!empty($mobile['ua_link_name'])){
		        $mobile['ua_link_name'] = $mobile['u_name'].'('.$mobile['ua_link_name'].')';
            }else{
                $mobile['ua_link_name'] = $mobile['u_name'];
            }
		    unserialize($mobile['u_name']);
		   LibFc::ajaxJsonEncode(['status' => true,'data' => $mobile]);
		}
		else
		{
		   LibFc::ajaxJsonEncode(['status' => true,'data' => '']);
		}
	}

	/**
	 * //todo废弃
	 * [getActiverUserList 列表数据]
	 * @Author   Yangxing
	 * @DateTime 2020-05-12T15:35:43+0800
	 * @return   [type]                   [description]
	 */
	public function getActiverUserList()
	{
		$params = mvc::$URL_PARAMS;
		//todo 权限
		$time = time();
		$pls = new PjlBase();
		$isYp =  $pls->get("dl_company",['dco_isyp'],sprintf(" and dco_isyp=1 and dco_id=%d",$_SESSION['_dcoid']),true);
		$where = '';
		if($isYp['data']['dco_isyp'] == 1){
			$pctIds = $pls->get("dl_company  join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_end >'%s' and dco_status=1",$time));
			if(!empty($pctIds['data'])){
				$pctIds = array_column($pctIds['data'],'dctp_pc_id');
			}
			foreach ($pctIds as $index => $item)
			{
				if($index == 0){
                   $wheres[] = sprintf(" u_pct_ids not like '%s%%'",$item);
				}else{
					$wheres[] = sprintf(" and u_pct_ids not like '%s%%'",$item);
				}

			}
			$where .= sprintf(" and (%s)",implode('', $wheres));
		}else{
			$pctIds = $pls->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_dco_id in (%s) and dct_end >'%s' and dco_status=1",$_SESSION['_dcoid'],$time));
		   if(empty($pctIds['data']['0']['dctp_pc_id'])){
		      $arr = [
		      "code" => 1,
		      "msg" => "无数据",
		      "count" => 0,
		      "data" => []
		      ];
		      ob_clean();
		      echo json_encode($arr);exit();
		   }
		   $pctIds = array_column($pctIds['data'],'dctp_pc_id');
		   	foreach ($pctIds as $index => $item)
			{
				if($index == 0){
                   $wheres[] = sprintf(" u_pct_ids like '%s%%'",$item.',');
				}else{
					$wheres[] = sprintf(" and u_pct_ids like '%s%%'",$item.',');
				}

			}
			$uidArr = $pls->get('dl_order_list',['dml_dwo_uid'],sprintf(" and dml_dco_id in (%s)",$_SESSION['_dcoid']));
			$uidArr = array_column($uidArr['data'],'dml_dwo_uid');
			if(empty($uidArr)){
			   $where .= sprintf("  and (ua_pjl_shop_etime < %d)",$time);
			}else{
			   $where .= sprintf("  and (ua_pjl_shop_etime < %d OR ua_uid IN (%s))",$time,implode(',', $uidArr));
			}
			$where .= sprintf(" and (%s)",implode('', $wheres));
		}

		$model = new YpwBase();

		$page = (int) $params['page'];
		$page = $page < 1 ? 1: $page;
		$limit = empty($params['limit']) ? 15: (int) $params['limit'];
		if($params['user']){
			$where .= sprintf(" and concat(ua_com_name,ua_link_name,ua_link_tel) like '%%%s%%'",trim($params['user']));
		}
		if($params['province']){
			$where .= sprintf(" and find_in_set('%s',u_pct_ids)",$params['province']);
		}
		if($params['city']){
			$where .= sprintf(" and find_in_set('%s',u_pct_ids)",$params['city']);
		}
		if($params['status']){
			switch ($params['status']) {
				case '1': //使用中
					$where .= sprintf(" and ua_pjl_shop_status=1 and ua_pjl_shop_etime > %d",$time);
					break;
				case '2': //已过期
					$where .= sprintf(" and ua_pjl_shop_status=1 and ua_pjl_shop_etime <= '%s' and ua_pjl_shop_etime!=0",$time);
					break;
				case '3': //未缴费
				    $where .= sprintf(" and ua_pjl_shop_status=1 and ua_pjl_shop_etime=0");
					break;
				case '4'://未申请
				    $where .= sprintf(" and ua_pjl_shop_status=0");
					break;
			}
		}
		if($params['ua_score']){
			$where .= sprintf(" and ua_score > '%d'",$params['ua_score']);
		}
		if($params['ua_pjl_shop_etime']){
			//直接取区间就行了
			if($params['ua_pjl_shop_etime'] < 0){ //查询要过期时间
				$end = time();
				$start = strtotime($params['ua_pjl_shop_etime'].'day');

			}else{ //查询已经过期的时间
				$end = strtotime($params['ua_pjl_shop_etime'].'day');
				$start = time();
			}
			$where .= sprintf(" and ua_pjl_shop_etime between %d and %d",$start,$end);
		}
		$where .= sprintf(" and u_status=1 and ua_crm_protect=0");
		$where .= sprintf("and ua_uid not in (select DISTINCT ctr_uid FROM `yp_crm.crm_customer_admin` JOIN `yp_crm.crm_customer` ON ctr_id = cca_ctr_id WHERE cca_end_time > %d",time());
        $ypCrm = (new BaseDb(mvc::$cfg['YP_CRM']))->get('yp_crm.crm_customer_admin join yp_crm.crm_customer on ctr_id=cca_ctr_id',["ctr_uid"],sprintf(" and cca_end_time > %d and cca_au_uid != '%s'",time(),$_SESSION['_userid']));
        if(!empty($ypCrm['data']) && $ypCrm['status'] == true){
            $ypCrm = array_column($ypCrm['data'],'ctr_uid');
            $where .= sprintf(" and ua_uid not in (%s)",implode(',',$ypCrm));
        }
		$filed = "ua_uid,ua_pjl_shop_status,ua_score,ua_pjl_shop_etime,ua_pjd_shop_id,ua_pjd_shop_status,ua_com_name,ua_com_style,ua_link_name,ua_link_tel,ua_crm_user,ua_crm_last_time";
		$sql = sprintf("select %s,u_pct_ids from yp_user_act join yp_user on u_id = ua_uid where 1=1 %s order by ua_pv desc",$filed,$where);
		$count = $model->YpwDb->One(sprintf("select count(*) from yp_user_act join yp_user on u_id = ua_uid where 1=1 %s",$where));
		if($count <= 0){
			$arr = [
			"code" => 0,
			"msg" => "无数据",
			"count" => 0,
			"data" => []
		];
		ob_clean();
		echo json_encode($arr);exit();
		}
		//echo sprintf("%s limit %s,%s",$sql,($page-1)*$limit,$limit);exit();
		$listArr = $model->YpwDb->Table(sprintf("%s limit %s,%s",$sql,($page-1)*$limit,$limit));
		$uId = implode(',', array_unique(array_column($listArr,'ua_uid')));
//		$selfFollow = $model->YpwDb->Table("SELECT max(uf_atime),yp_user_follow.* from yp_user_follow where uf_uid=%d and uf_to_uid in (%s) GROUP BY uf_to_uid",$_SESSION['admin_userid'],$uId);
		$selfFollow = $model->YpwDb->Table(sprintf("select b.uf_atime, b.uf_to_uid, b.uf_uname from ( select uf_to_uid, max(uf_atime) as uf_atime from yp_user_follow where uf_uid =%d group by uf_to_uid ) as a inner join yp_user_follow as b on a.uf_atime = b.uf_atime and a.uf_to_uid = b.uf_to_uid",$_SESSION['_userid']));
		if(!empty($selfFollow)){
			$selfFollow = array_column($selfFollow,null,'uf_to_uid');
		}else{
			$selfFollow = [];
		}
		$lastFollow = $model->YpwDb->Table(sprintf("select b.uf_atime, b.uf_to_uid, b.uf_uname from ( select uf_to_uid, max(uf_atime) as uf_atime from yp_user_follow where uf_to_uid in (%s) group by uf_to_uid ) as a inner join yp_user_follow as b on a.uf_atime = b.uf_atime and a.uf_to_uid = b.uf_to_uid",$uId));
		if(!empty($lastFollow)){
			$lastFollow = array_column($lastFollow,null,'uf_to_uid');
		}else{
			$lastFollow = [];
		}
		$brand = $model->YpwDb->Table(sprintf("select * from yp_user_act_brand where uab_uid in (%s)",$uId));
		$parts = $model->YpwDb->Table(sprintf("select * from yp_user_act_part where uap_uid in (%s)",$uId));
		$getUid = $model->YpwDb->Table("select at_get_uid from yp_user_act_tjtel where date_format(from_unixtime(at_time),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d') and at_uid=".$_SESSION['_userid']." and at_get_uid in (".$uId.")");
		$getUid = array_column($getUid,'at_get_uid');

		$brandTemp = [];
		//如果个数大于了三个，那么我就直接排序(倒叙)去掉最后
		foreach ($brand as $v) {
			$brandTemp[$v['uab_uid']][] = $v;
			if(count($brandTemp[$v['uab_uid']]) > 3){
				array_multisort(array_column($brandTemp[$v['uab_uid']],'uab_count'),SORT_DESC,$brandTemp[$v['uab_uid']]);
				array_pop($brandTemp[$v['uab_uid']]);
			}
		}
		unset($brand);
		$partsTemp = [];
		foreach ($parts as  $item) {
			$partsTemp[$item['uap_uid']][] = $item;
			if(count($partsTemp[$item['uap_uid']]) > 3){
				array_multisort(array_column($partsTemp[$item['uap_uid']],'uap_count'),SORT_DESC,$partsTemp[$item['uap_uid']]);
				array_pop($partsTemp[$item['uap_uid']]);
			}
		}
		unset($parts);
		$address = array_column($listArr,'u_pct_ids');
		$addressId = [];
		foreach ($address as $index => $item) {
		   $tem = explode(',', $item);
		   if(!empty($tem['0'])){
		       array_push($addressId, $tem['0']);
		   }
		   if(!empty($tem['1'])){
		     array_push($addressId, $tem['1']);
		   }
		   unset($tem);
		   unset($address[$index]);
		}
		$addressId = array_unique($addressId);
		$addressData = $model->YpwDb->Table(sprintf("select pc_id,pc_name from yp_province_city where pc_id in (%s)",implode(',', $addressId)));
		unset($addressId);
		$addressData = array_column($addressData,'pc_name','pc_id');
		foreach ($listArr as $index => &$item) {
			/**
			 * status = 1 && 有到期时间   具体日期
             * status = 0   未申请
             * status = 1 && 无到期时间    申请中
             * status = 1 && 无到期时间   未缴费
             *
			 */
			$item['exp_time'] = '';
			if($item['ua_pjl_shop_status'] == 1 && $item['ua_pjl_shop_etime'] > 0) {
				$item['status'] = 1;
				$item['exp_time'] = ceil((($item['ua_pjl_shop_etime'] - $time) / 86400));

			}else if($item['ua_pjl_shop_status'] == 1 && $item['ua_pjl_shop_etime'] == 0){
				$item['status'] = 2; //未缴费
			}else{
				$item['status'] = 3;
			}
			$item['ua_crm_last_time'] = $item['ua_crm_last_time'] ? date('Y-m-d H:i',$item['ua_crm_last_time']) : '';
			$item['parts'] = isset($partsTemp[$item['ua_uid']]) ? implode(',',array_column($partsTemp[$item['ua_uid']],'uap_part')) : '';
			$item['brand'] = isset($brandTemp[$item['ua_uid']]) ? implode(',',array_column($brandTemp[$item['ua_uid']],'uab_brand')) : '';
			$item['address'] = '';
			if(!in_array($item['ua_uid'], $getUid)){
			   $item['ua_link_tel'] = !empty($item['ua_link_tel']) ? substr_replace($item['ua_link_tel'], '****', 3, 4) : '';
			}
			if(!empty($item['u_pct_ids'])){
				$tem = explode(',', $item['u_pct_ids']);
				if(isset($tem['0'])){
					$item['address'] = isset($addressData[$tem['0']]) ? $addressData[$tem['0']] : '';
				}
				if(isset($tem['1'])){
					$item['address'] .= isset($addressData[$tem['1']]) ? $addressData[$tem['1']] : '';
				}
			}
			$item['last_follow'] = '';
			if(isset($lastFollow) && $lastFollow[$item['ua_uid']]){
				$item['last_follow'] = date('Y-m-d',$lastFollow[$item['ua_uid']]['uf_atime']).'/'.$lastFollow[$item['ua_uid']]['uf_uname'];
			}

			$item['self_follow'] = '';
			if(isset($selfFollow) && $selfFollow[$item['ua_uid']]){
				$item['self_follow'] = date('Y-m-d',$selfFollow[$item['ua_uid']]['uf_atime']);
			}

		}
		unset($addressData);
		$arr = [
			"code" => 0,
			"msg" => "",
			"count" => $count,
			"data" => $listArr
		];
		ob_clean();
		echo json_encode($arr);
	}

	/**
	 * [showCity 查看城市]
	 * @Author   Yangxing
	 * @DateTime 2020-05-12T15:35:31+0800
	 * @return   [type]                   [description]
	 */
	public function showCity()
	{
		$params = mvc::$URL_PARAMS;

		if(empty($params['pc_id']) && $params['pc_id'] <=0)
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}

		$result = (new YpwBase)->get('yp_province_city',['pc_id','pc_name'],sprintf(" and pc_pid=%d",$params['pc_id']));

		LibFc::ajaxJsonEncode($result);
	}

	/**
	 * [communicationRecord 沟通记录]
	 * @Author   Yangxing
	 * @DateTime 2020-05-15T10:18:05+0800
	 * @return   [type]                   [view 模板]
	 */
	public function communicationRecord()
	{
		//todo权限
		LibTpl::Put();
	}

	/**
	 * [addCommunication 添加沟通]
	 * @Author   Yangxing
	 * @DateTime 2020-05-15T10:18:44+0800
	 */
	public function addCommunication()
	{
		$_POST = array_map('trim', $_POST);

		$data = [
		  'uf_uid' => (int) $_SESSION['_userid'], //跟进人
		  'uf_uname' => $_SESSION['_realname'], //跟进人
		  'uf_to_uid' => (int) $_POST['uf_to_uid'], //跟进谁
		  'uf_txt' => htmlspecialchars($_POST['uf_txt'], ENT_QUOTES), //跟进内容
		  'uf_atime' => time(), //跟进时间
		  'uf_ip' => LibFc::GetClientIp() //ip地址
		];

		if($data['uf_to_uid'] <= 0) LibFc::ajaxJsonEncode(['status' => false,'data' => '客户不可为空']);

		if(empty($data['uf_txt'])) LibFc::ajaxJsonEncode(['status' => false,'data' => '跟进内容不可为空']);

		if(mb_strlen($data['uf_txt']) > 4000) LibFc::ajaxJsonEncode(['status' => false,'data' => '跟进内容长度超过了限制4000']);

		$result = (new YpwBase)->add('yp_user_follow',$data);

		LibFc::ajaxJsonEncode($result);
	}

	/**
	 * [getCommunicationRecord 获取沟通记录]
	 * @Author   Yangxing
	 * @DateTime 2020-05-15T10:20:30+0800
	 * @return   [type]                   [json]
	 */
	public function getCommunicationRecord()
	{
		$result = (new YpwBase)->get('yp_user_follow',['*'],sprintf(" and uf_uid=%d and uf_to_uid=%d order by uf_atime desc limit %s,%s",$_SESSION['_userid'],$_POST['to_uid'],($_POST['page'] -1)*8,8));
		foreach($result['data'] as &$item)
		{
			$item['uf_atime'] = date('Y-m-d H:i:s',$item['uf_atime']);
		}
		LibFc::ajaxJsonEncode($result);
	}

	/**
	 * [activeUsersOneHundred 活跃用户TOP100列表]
	 * @Author   Yangxing
	 * @DateTime 2020-05-16T11:15:38+0800
	 * @return   [type]                   [description]
	 */
	public function activeUsersOneHundred()
	{
		//todo 权限
		LibTpl::Put();
	}

	/**
	 * [selfUser 我跟进的列表]
	 * @Author   Yangxing
	 * @DateTime 2020-05-16T11:16:24+0800
	 * @return   [type]                   [description]
	 */
	public function selfUser()
	{
		//todo 权限
		LibTpl::Put();
	}

	/**
	 * [appliedUser 已申请]
	 * @Author   Yangxing
	 * @DateTime 2020-05-16T11:17:28+0800
	 * @return   [type]                   [description]
	 */
	public function appliedUser()
	{
		LibTpl::Set('endArr',[
			7=>'7天内',
			15=>'15天内',
			30=>'30天内',
			60=>'60天内',
			90=>'90天内',
			-7=>'过期7天',
			-15=>'过期15天',
			-30=>'过期30天',
			-60=>'过期60天',
		]);
		LibTpl::Put();
	}

	/**
	 * [getActiverUserLists 相关活跃用户接口]
	 * @Author   Yangxing
	 * @DateTime 2020-05-16T11:23:00+0800
	 * @return   [type]                   [description]
	 */
	public function getActiverUserLists()
	{
	    //todo 权限

	    /**
	     * [$params 参数]
	     * @var [type|array]
	     */
		$params = mvc::$URL_PARAMS;

		$params = array_map("trim", $params);

        /**
         * [$time 当前时间]
         * @var [type|Int]
         */
	    $time = time();

	    /**
	     * [$dcoId 供应商ID]
	     * @var [type|Int]
	     */
	    $dcoId = (int) $_SESSION['_dcoid'];
	    if(empty($dcoId) || (int) $dcoId <= 0)
	    {
	    	$this->ajaxReturnJson(0,"",0,[]);
	    }

		/**
		 * [$pjlBaseModel  数据库操作类]
		 * @var PjlBase
		 */
		$pjlBaseModel = new PjlBase();

		/**
		 * 把是否是YP放Session里面
		 * [$isYp 是否是YP用户]
		 * @var [type]
		 */
		if(isset($_SESSION['is_yp']))
		{
			$isYp = $_SESSION['isYp'];
		}
		else
		{
		   $isYp =  $pjlBaseModel->get("dl_company",['dco_isyp'],sprintf(" and dco_isyp=1 and dco_id=%d",$dcoId),true);

		   if($isYp['data']['dco_isyp'] == 1)
		   {
		   	  $_SESSION['isYp'] = 1;
		   	  $isYp = 1;
		   }
		   else
		   {
		   	  $_SESSION['isYp'] = 0;
		   	  $isYp = 0;
		   }
		}

		/**
		 * [$where 查询条件开始]
		 * @var string
		 */
		$where = '';

		/**
		 * 根据是否是YP获取不同的pcId并放入where 条件中
		 * [$pcId 代理城市的城市ID(省)]
		 * @var [type]
		 */

		if($isYp)
		{
            $pcId = $pjlBaseModel->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_end >'%s' and dco_status=1",$time));
            $pcId = array_column($pcId['data'],'dctp_pc_id');
            if(empty($pcId)){
                $this->ajaxReturnJson(0,"无数据",0,[]);
            }
            $where .= sprintf(" and ui_province not in (%s)",implode(',', $pcId));
		}
		else
		{
		    $pcId = $pjlBaseModel->get("dl_company join dl_company_target on dco_id=dct_dco_id join dl_company_target_pcts on dct_dco_id=dctp_dct_id",['dctp_pc_id'],sprintf(" and dct_end >'%s' and dco_status=1 and dco_id=%d",$time,$dcoId));
		    if(empty($pcId['data'])){
                $this->ajaxReturnJson(0,"无数据",0,[]);
            }
		    $where .= sprintf(" and ui_province in (%s)",implode(',', array_column($pcId['data'],'dctp_pc_id')));
			$uidArr = $pjlBaseModel->get('dl_order_list',['dml_dwo_uid'],sprintf(" and dml_dco_id in (%s)",$dcoId));

			if(!empty($uidArr['data']))
			{
				$uidArr = array_column($uidArr['data'],'dml_dwo_uid');

				$where .= sprintf("  and (ua_pjl_shop_etime < %d OR ua_uid IN (%s))",$time,implode(',', $uidArr));
			}
			else
			{
				$where .= sprintf("  and (ua_pjl_shop_etime < %d)",$time);

			}
		}

		/**
		 * [$ypwModel 数据库]
		 * @var YpwBase
		 */
		$ypwModel = new YpwBase();

		$page = (int) $params['page'];

		$page = $page < 1 ? 1: $page;

		$limit = empty($params['limit'])? 15: (int) $params['limit'];

		if($params['user'])
		{
			$where .= sprintf(" and concat(ua_com_name,ua_link_name,ua_link_tel) like '%%%s%%'",trim($params['user']));
		}

		if($params['province'])
		{
			$where .= sprintf(" and find_in_set('%s',u_pct_ids)",$params['province']);
		}

		if($params['city'])
		{
			$where .= sprintf(" and find_in_set('%s',u_pct_ids)",$params['city']);
		}

		if($params['status'])
		{
            /**
             * 未申请 ua_pjl_shop_id = 0
             *使用中 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime > TIME()
             *已过期 ua_pjl_shop_id >0  ua_pjl_shop_status = 1 ua_pjl_shop_etime >0 a_pjl_shop_etime < TIME()
             *未缴费 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime =0
             *已停用 ua_pjl_shop_id >0  ua_pjl_shop_status = 0
             */
			switch ($params['status'])
			 {
				case '1': //使用中
					$where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=1 and ua_pjl_shop_etime > '%d'",$time);
					break;
				case '2': //已过期
					$where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=1 and ua_pjl_shop_etime <= '%s' and ua_pjl_shop_etime!=0",$time);
					break;
				case '3': //未缴费
				    $where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=1 and ua_pjl_shop_etime=0");
					break;
                case '4':
                    $where .= sprintf(" and ua_pjl_shop_id > 0 and ua_pjl_shop_status=0");
			}
		}

		if($params['ua_score'])
		{
			$where .= sprintf(" and ua_score > '%d'",$params['ua_score']);
		}

		if($params['ua_pjl_shop_etime'])
		{
			//直接取区间就行了
			if($params['ua_pjl_shop_etime'] < 0)
			{
			    //查询要过期时间
				$end = time();
				$start = strtotime($params['ua_pjl_shop_etime'].'day');

			}
			else
			{ //查询已经过期的时间
				$end = strtotime($params['ua_pjl_shop_etime'].'day');
				$start = time();
			}
			$where .= sprintf(" and ua_pjl_shop_etime between %d and %d",$start,$end);
		}

		//剔除状态和crm保护的数据
		$where .= sprintf(" and u_status=1 and ua_crm_protect=0");


        $ypCrm = (new BaseDb(mvc::$cfg['DB']['YP_CRM']))->get('yp_crm.crm_customer_admin join yp_crm.crm_customer on ctr_id=cca_ctr_id',["ctr_uid"],sprintf(" and cca_end_time > %d and cca_au_uid!='%s'",time(),$_SESSION['_userid']));
        
        if(!empty($ypCrm['data']) && $ypCrm['status'] == true){
            $ypCrm = array_column($ypCrm['data'],'ctr_uid');
            $where .= sprintf(" and ua_uid not in (%s)",implode(',',$ypCrm));
        }


        //1.活跃TOP100（最多显示100条，按活跃度出一个月内无任何人跟进过的)
		if($params['type'] == 1)
		{
			$where .= sprintf(" and ua_uid not in (select uf_to_uid from yp_user_follow where uf_atime between %s and %s group by uf_to_uid )",strtotime('-1 month'),$time);
		}

		//已申请入驻
		if($params['type'] == 3)
		{
			$where .= sprintf(" AND ua_pjl_shop_id > 0");
		}

		//我跟进的（最多显示100条，按照自己跟进时间倒序）
		if($params['type'] == 2)
		{
			$where .= sprintf(" and ua_uid in (select uf_to_uid from yp_user_follow where uf_uid=%d group by uf_to_uid order by uf_atime)",$_SESSION['_userid']);
		}

		$filed = "u_login_time,ua_pjl_shop_id,ua_uid,u_name,ua_pjl_shop_status,ua_score,ua_pjl_shop_etime,ua_pjd_shop_id,ua_pjd_shop_status,ua_com_name,ua_com_style,ua_link_name,ua_link_tel,ui_province,ui_city";
		$order = 'ua_pv';

		$count = $ypwModel->YpwDb->One(sprintf("select count(*) from yp_user_act join yp_user on u_id=ua_uid join yp_user_ext on ui_uid = ua_uid where 1=1 %s",$where));
		if($params['sort']){
			switch ($params['sort']) {
				case 'ua_score':
					$order = 'ua_score';
					break;
				case 'shop_apply_time':
				    $shopId = $ypwModel->YpwDb->Table(sprintf("select ua_pjl_shop_id from yp_user_act join yp_user on u_id=ua_uid join yp_user_ext on ui_uid = ua_uid where 1=1 %s and ua_pjl_shop_id>0 order by null",$where));
				    if(empty($shopId)){
				    	$this->ajaxReturnJson(0,"无数据",0,[]);
				    }
				    $apply_time = $pjlBaseModel->get("pl_shop",['shop_id','shop_apply_time'],sprintf(" and shop_id in(%s) order by shop_apply_time desc limit %s,%s",implode(',', array_column($shopId,'ua_pjl_shop_id')),($page-1)*$limit,$limit));
				    if(!empty($apply_time)){
				    	  $page = 1;
				    	  $apply_time = array_column($apply_time['data'],'shop_apply_time','shop_id');
				           $temp = array_keys($apply_time);
				           array_push($temp, 0);
				           $where .= sprintf(" and ua_pjl_shop_id in (%s)",implode(',', $temp));
				    }else{
				    	$apply_time = [];
				    }
				    break;
				default:
					$order = 'ua_pv';
			}
		}



		$sql = sprintf("select %s from yp_user_act join yp_user on u_id=ua_uid join yp_user_ext on ui_uid = ua_uid where 1=1 %s order by %s desc",$filed,$where,$order);
		//echo $sql;exit();
		if($count <= 0)
		{
			$this->ajaxReturnJson(0,"无数据",0,[]);
		}

		/**
		 * [$listArr 最终查询数据]
		 * @var [type]
		 */
		$listArr = $ypwModel->YpwDb->Table(sprintf("%s limit %s,%s",$sql,($page-1)*$limit,$limit));

		if($params['sort'] != 'shop_apply_time'){
			$apply_time = $pjlBaseModel->get("pl_shop",['shop_id','shop_apply_time'],sprintf(" and shop_id in(%s) order by shop_apply_time desc",implode(',', array_column($listArr,'ua_pjl_shop_id'))),false);
			if(!empty($apply_time)){
				$apply_time = array_column($apply_time['data'],'shop_apply_time','shop_id');
			}else{
				$apply_time = [];
			}
		}

		/**
		 * [$uId Uid]
		 * @var [type|string]
		 */
		$uId = implode(',', array_unique(array_column($listArr,'ua_uid')));

		/**
		 * [$selfFollow 我跟进]
		 * @var [type|array]
		 */
		$selfFollow = $ypwModel->YpwDb->Table(sprintf("select b.uf_atime, b.uf_to_uid, b.uf_uname from ( select uf_to_uid, max(uf_atime) as uf_atime from yp_user_follow where uf_uid =%d group by uf_to_uid ) as a inner join yp_user_follow as b on a.uf_atime = b.uf_atime and a.uf_to_uid = b.uf_to_uid",$_SESSION['_userid']));

		if(!empty($selfFollow))
		{
			$selfFollow = array_column($selfFollow,null,'uf_to_uid');
		}
		else
		{
			$selfFollow = [];
		}
		/**
		 * [$lastFollow 最后跟进人]
		 * @var [type|array]
		 */
		$lastFollow = $ypwModel->YpwDb->Table(sprintf("select b.uf_atime, b.uf_to_uid, b.uf_uname from ( select uf_to_uid, max(uf_atime) as uf_atime from yp_user_follow where uf_to_uid in (%s) group by uf_to_uid ) as a inner join yp_user_follow as b on a.uf_atime = b.uf_atime and a.uf_to_uid = b.uf_to_uid",$uId));
		if(!empty($lastFollow))
		{
			$lastFollow = array_column($lastFollow,null,'uf_to_uid');
		}
		else
		{
			$lastFollow = [];
		}

		/**
		 * [$brand 品牌排行榜]
		 * @var [type|array]
		 */
		$brand = $ypwModel->YpwDb->Table(sprintf("select * from yp_user_act_brand where uab_uid in (%s)",$uId));

		/**
		 * [$parts 零件排行榜]
		 * @var [type|array]
		 */
		$parts = $ypwModel->YpwDb->Table(sprintf("select * from yp_user_act_part where uap_uid in (%s)",$uId));

		/**
		 * [$getUid 电话加密今天是否可以解开]
		 * @var [type|array]
		 */
		$getUid = $ypwModel->YpwDb->Table("select at_get_uid from yp_user_act_tjtel where date_format(from_unixtime(at_time),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d') and at_uid=".$_SESSION['_userid']." and at_get_uid in ('.$uId.')");

		$getUid = array_column($getUid,'at_get_uid');

		$brandTemp = [];
		//如果个数大于了三个，那么我就直接排序(倒叙)去掉最后
		foreach ($brand as $v)
		{
			$brandTemp[$v['uab_uid']][] = $v;

			if(count($brandTemp[$v['uab_uid']]) > 3)
			{
				array_multisort(array_column($brandTemp[$v['uab_uid']],'uab_count'),SORT_DESC,$brandTemp[$v['uab_uid']]);

				array_pop($brandTemp[$v['uab_uid']]);
			}
		}

		unset($brand);

		$partsTemp = [];

		foreach ($parts as  $item)
		{
			$partsTemp[$item['uap_uid']][] = $item;

			if(count($partsTemp[$item['uap_uid']]) > 3)
			{
				array_multisort(array_column($partsTemp[$item['uap_uid']],'uap_count'),SORT_DESC,$partsTemp[$item['uap_uid']]);

				array_pop($partsTemp[$item['uap_uid']]);
			}
		}

		unset($parts);

		/**
		 * [$address key=>城市,value=>省份]
		 * @var array
		 */
		$address = array_column($listArr,'ui_province','ui_city');

		$addressId = array_unique(array_merge(array_keys($address),array_values($address)));

		$addressData = $ypwModel->YpwDb->Table(sprintf("select pc_id,pc_name from yp_province_city where pc_id in (%s)",implode(',', $addressId)));

		$addressData = array_column($addressData,'pc_name','pc_id');
		if($params['type'] == 3){
			$shopId = array_column($listArr,'ua_pjl_shop_id');
		  if(!empty($shopId)){
			//XXX:wwww
			$end = date('Ymd',time());
            $start = date('Ymd',strtotime("-3 month"));
			$showCount = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get('tj_pjl_shop_date',['tpsd_shop_id','sum(tpsd_pv_count) as show_count'],sprintf(" and tpsd_shop_id in (%s) and tpsd_date between '%s' and '%s' group by tpsd_shop_id",implode(',',$shopId),$start,$end));
			if(!empty($showCount['data'])){
				$showCount = array_column($showCount['data'],'show_count','tpsd_shop_id');
			}else{
				$showCount = [];
			}
		  }
		}else{
			$shopId = [];
		}


		foreach ($listArr as $index => &$item)
		{

			/**
             * 未申请 ua_pjl_shop_id = 0
             *使用中 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime > TIME()
             *已过期 ua_pjl_shop_id >0  ua_pjl_shop_status = 1 ua_pjl_shop_etime >0 a_pjl_shop_etime < TIME()
             *未缴费 ua_pjl_shop_id >0  ua_pjl_shop_status = 1  ua_pjl_shop_etime =0
             *已停用 ua_pjl_shop_id >0  ua_pjl_shop_status = 0
			 */
			$item['exp_time'] = '';

			if($item['ua_pjl_shop_id'] <= 0){
			    $item['status'] = 1; //未申请
            }else if($item['ua_pjl_shop_id'] > 0){
			    if($item['ua_pjl_shop_status'] == 1){
			        if($item['ua_pjl_shop_etime']  <= 0){
                        $item['status'] = 3; //未缴费
                    }else{
                        $item['status'] = 2;
                        $item['exp_time'] = ceil((($item['ua_pjl_shop_etime'] - $time) / 86400));
                    }
                }else{
			        $item['status'] = 4; //已停用
                }
            }

            //处理展示总数
            if(isset($showCount[$item['ua_pjl_shop_id']]))
            {
            	$item['show_count'] = $showCount[$item['ua_pjl_shop_id']];
            }else{
            	$item['show_count'] = null;
            }

			//处理关注零件
			$item['parts'] = isset($partsTemp[$item['ua_uid']]) ? implode(',',array_column($partsTemp[$item['ua_uid']],'uap_part')) : '';

			//处理关注品牌
			$item['brand'] = isset($brandTemp[$item['ua_uid']]) ? implode(',',array_column($brandTemp[$item['ua_uid']],'uab_brand')) : '';

			$item['address'] = '';



			if(!in_array($item['ua_uid'], $getUid))
			{
				//处理联系人
				if(!empty($item['ua_link_name']))
				{
					$item['ua_link_name'] = $this->userNameCut($item['ua_link_name']);
				}
				$item['ua_link_tel'] = !empty($item['ua_link_tel']) ? substr_replace($item['ua_link_tel'], '****', 3, 4) : '';
			}

			//处理城市
			if(!empty($item['ui_province']))
			{
				$item['address'] = $addressData[$item['ui_province']];
				if(!empty($item['ui_city']))
				{
					$item['address'] .= $addressData[$item['ui_city']];
				}
			}

			//处理最后跟进
			$item['last_follow'] = '';
			if(isset($lastFollow) && $lastFollow[$item['ua_uid']])
			{
				$item['last_follow'] = date('Y-m-d',$lastFollow[$item['ua_uid']]['uf_atime']).'/'.$this->userNameCut($lastFollow[$item['ua_uid']]['uf_uname']);
			}
			//var_dump($item['ua_pjl_shop_id']);
			if(!empty($apply_time) && isset($apply_time[$item['ua_pjl_shop_id']]))
			{
				$item['app_time'] = date('Y-m-d',$apply_time[$item['ua_pjl_shop_id']]);
			}

			//处理我跟进
			$item['self_follow'] = '';
			if(isset($selfFollow) && $selfFollow[$item['ua_uid']])
			{
				$item['self_follow'] = date('Y-m-d',$selfFollow[$item['ua_uid']]['uf_atime']);
			}
			if(!empty($item['ua_link_name'])){
                $item['ua_link_name']  = $item['u_name'] .'('.$item['ua_link_name']. ')';
            }else{
                $item['ua_link_name']  = $item['u_name'];
            }

            $item['last_login_time'] = $this->getLastTime($item['u_login_time']);
		}
		if($params['sort'] == 'shop_apply_time'){
			array_multisort(array_column($listArr,'app_time'),SORT_DESC,$listArr);
		}
		unset($addressData);

		$this->ajaxReturnJson(0,"",$count,$listArr);
	}

	/**
	 * [showCount 展示页面]
	 * @Author   Yangxing
	 * @DateTime 2020-06-04T10:16:33+0800
	 * @return   [type]                   [view]
	 */
	public function showCount()
	{
		LibTpl::Set('shop_id',(int) $_GET['shop_id']);
		LibTpl::Put();
	}

	/**
	 * [showCountList 展示列表接口]
	 * @Author   Yangxing
	 * @DateTime 2020-06-04T10:16:38+0800
	 * @return   [type]                   [json]
	 */
	public function showCountList()
	{
		$shopId = (int) $_POST['shop_id'];
		if(empty($shopId)){
			LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}
		$end = date('Ymd',time());
        $start = date('Ymd',strtotime("-3 month"));
		$showCount = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get('tj_pjl_shop_date',['*'],sprintf(" and tpsd_shop_id = %d and tpsd_date between '%s' and '%s' order by tpsd_date desc limit %s,%s",$shopId,$start,$end,($_POST['page'] -1)*20,20));
		LibFc::ajaxJsonEncode($showCount);
	}

	/**
	 * [ajaxReturnJson API接口返回]
	 * @Author   Yangxing
	 * @DateTime 2020-05-16T13:01:37+0800
	 * @param    [type]                   $code  [description]
	 * @param    [type]                   $msg   [description]
	 * @param    [type]                   $count [description]
	 * @param    [type]                   $list  [description]
	 * @return   [type]                          [description]
	 */
	private function ajaxReturnJson($code,$msg,$count,$list)
	{
		ob_clean();
		echo json_encode(['code' => $code,'msg' => $msg,'count' => $count,'data' => $list]); exit();
	}

	/**
	 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
	 * @Author   Yangxing
	 * @param string $userName 姓名
	 * @return string 格式化后的姓名
	 */
	private function userNameCut($userName)
	{
		if(empty($userName)){
			return '';
		}
		if(mb_strlen($userName, 'utf-8') - 1 == 0){
			return '';
		}
		$strlen     = mb_strlen($userName, 'utf-8');
		$firstStr     = mb_substr($userName, 0, 1, 'utf-8');
		$lastStr     = mb_substr($userName, -1, 1, 'utf-8');
		return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($userName, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
	}

	private function getLastTime($time)
	{

       $t=time()-$time;
       $f=array(
           '31536000'=>'年',
           '2592000'=>'个月',
          // '604800'=>'星期',
           '86400'=>'天',
           '3600'=>'小时',
           '60'=>'分钟',
           '1'=>'秒'
       );
       foreach ($f as $k=>$v)    {
           if (0 !=$c=floor($t/(int)$k)) {
               return $c.$v.'前';
           }
       }
	}

    // 下载广告报价
    function nadsExcel()
    {
        $data = $_POST['data'] ?: '';
        $data = json_decode($data, true);
        if (!is_array($data)) {
            return false;
        }

        // 广告名称
        $place = [];
        $ads = new AdsBase();
        $query = $ads->get('pj_place', ['pa_id', 'pa_name', 'pa_max', 'pa_size'], 'order by pa_id');
        foreach ($query['data'] as $item)
        {
            $name = $item['pa_name'];
            if (false !== in_array($item['pa_id'], [84, 86])) {
                $name .= '-乘用车';
            }

            $change = [
                'name' => $name,
                'remark' => sprintf('最大投放%d个广告, 尺寸%s', $item['pa_max'], $item['pa_size']),
            ];
            $place[sprintf('%d-0', $item['pa_id'])] = $change;

            if (false !== in_array($item['pa_id'], [84, 86]))
            {
                $place[sprintf('%d-1', $item['pa_id'])] = array_merge($change, [
                    'name' => sprintf('%s-商用车', $item['pa_name']),
                ]);
            }
        }

        $excel = [['广告位置', '省份', '价格:元/月', '广告尺寸', '备注']];
        foreach ($data as $item_key => $item_val)
        {
            foreach ($item_val as $item_data)
            {
                $excel[] = [
                    $place[$item_key]['name'],
                    $item_data['name'],
                    $item_data['price'],
                    $place[$item_key]['remark'],
                    $item_data['status'],
                ];
            }
        }

        ob_clean();
        $now = gmdate("D, d M Y H:i:s");
        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");

        header("Content-Disposition: attachment;filename=price.csv");
        header("Content-Transfer-Encoding: binary");
        $fp = fopen("php://output", 'w');
        foreach ($excel as $fields)
        {
            foreach ($fields as $kk => $vv)
            {
                $fields[$kk] = iconv('utf-8', 'gbk//IGNORE', $vv);
            }
            fputcsv($fp, $fields);
        }
        fclose($fp);
        exit;
    }

	//广告销售统计
	function nads()
	{
		$Params = mvc::$URL_PARAMS;
		$Params['sby'] ='place';
		$LibCrmApi = new LibCrmApi();
		$res = $LibCrmApi->Get('cus/getAdsPlaces', $Params);
		$plaArr = $res['data'];
		foreach($plaArr as $k=>$pla)
		{
			foreach($pla['adsuse'] as $kk=>$as)
			{
				$as['url'] = mvc::$cfg['SELF_URI'].'crm/index?fast=all';
				if($pla['pa_is_area']) $as['url'] .= '&pct_ids='.$as['id'];
				if($pla['pa_keyword_type'] == 'brand') $as['url'] .= '&brand_id='.$as['id'];
				$pla['adsuse'][$kk] = $as;
			}
			$plaArr[$k] = $pla;
		}
		LibTpl::Set('plaArr', $plaArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '广告位销售统计');
		LibTpl::Put();
	}

	//广告销售组统计
	function nadsGroup()
	{
		$Params = mvc::$URL_PARAMS;
		$Params['sby'] ='group';
		$LibCrmApi = new LibCrmApi();
		$res = $LibCrmApi->Get('cus/getAdsPlaces', $Params);
		$groupArr = $res['data'];
		foreach($groupArr as $style=>$gv)
		{
			foreach($gv as $gkk=>$gvv)
			{
				$gvv['url'] = mvc::$cfg['SELF_URI'].'crm/index?fast=all';
				if($style == 'province') $gvv['url'] .= '&pct_ids='.$gvv['id'];
				if($style == 'brand') $gvv['url'] .= '&brand_id='.$gvv['id'];
				$gv[$gkk] = $gvv;
			}
			$groupArr[$style] = $gv;
		}
		LibTpl::Set('groupArr', $groupArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', '广告销售组统计');
		LibTpl::Put();
	}

    /**
     * 广告报价
     */
    public function nadsPrice()
    {
        $time = time();
        $Params = mvc::$URL_PARAMS;

        LibTpl::Set('title', '广告报价');
        LibTpl::Put();
    }

    /**
     * 跑街令广告区域
     */
    public function nadsPriceArea()
    {
        $ads = new AdsBase();

        // 广告名称
        $place = [];
        $query = $ads->get('pj_place', ['pa_id', 'pa_name', 'pa_max', 'pa_size'], 'order by pa_id');
        foreach ($query['data'] as $item)
        {
            $name = $item['pa_name'];
            if (false !== in_array($item['pa_id'], [84, 86])) {
                $name .= '-乘用车';
            }

            $change = [
                'id' => sprintf('%d-0', $item['pa_id']),
                'place' => $name,
                'info' => sprintf('最大投放<b class="red">%d</b>个广告, 尺寸<b>%s</b>', $item['pa_max'], $item['pa_size']),
                'total' => 0,
                'sign' => '<span>选择位置</span><span class="change"></span>',
            ];
            $place[] = $change;

            if (false !== in_array($item['pa_id'], [84, 86]))
            {
                $change['id'] = sprintf('%d-1', $item['pa_id']);
                $change['place'] = sprintf('%s-商用车', $item['pa_name']);
                $place[] = $change;
            }
        }

        echo json_encode(['data' => $place, 'count' => count($place), 'code' => 0, 'msg' => '']);
    }

    /**
     * 广告位报价情况
     */
    public function nadsPriceChange()
    {
        $ads = new AdsBase();
        $get = mvc::$URL_PARAMS;
        $idx = explode('-', $get['ads']);
        $adv = ($get['adv'] !== '') ? explode(',', $get['adv']) : [];

        // 广告价格
        $price = [];
        $adsApp = new BaseDb(mvc::$cfg['DB']['B2C']);
        $adsRes = $adsApp->get(
            'yp_ads.all_ad_price',
            ['aap_pc_id', 'aap_keyword', 'aap_price', 'app_modtype'],
            sprintf('and aap_site = "pjd" and aap_p_id = %d', $idx[0])
        );
        foreach ($adsRes['data'] as $item)
        {
            $label = $item['aap_pc_id'] ?: $item['aap_keyword'];

            if ($item['aap_price']) {
                $price[$label][$item['app_modtype'] ?: 'all'] = (int) $item['aap_price'];
            }
        }

        // 广告位详情
        $adsAr = $ads->get('pj_place', ['*'], sprintf('and pa_id = %d', $idx[0]), true);
        $first = $adsAr['data'];

        // 广告位占用情况
        $used = [];
        $time = time();
        $column = [
            'ads_id',
            'pla_pa_id', // 广告区域
            'pat_pc_id', // 广告位置
            'pat_keyword', // 广告位置
            'pat_btime', // 开始时间
            'pat_etime', // 结束时间

            'pla_status', // 广告状态
            'pal_shoufei', // 收费
            'pat_modcv', // 乘用车
            'pat_modpc', // 商用车
        ];
        $where = sprintf('and pla_status >= 1 and pal_shoufei = 1 and pla_pa_id=%d and pat_etime >= %d order by pat_etime', $idx[0], $time);
        $table = 'pj_user_ads a JOIN pj_place_ads b ON ads_id = pla_ads_id join pj_place_ads_time on pla_id = pat_pla_id';
        $adArr = $ads->get($table, $column, $where);
        foreach ($adArr['data'] as $item)
        {
            if ($first['pa_is_area'])
            {
                // 省份
                $used[$item['pat_pc_id']][] = $item;
            } else if ($first['pa_is_keyword'])
            {
                if ($first['pa_keyword_type'] === 'brand')
                {
                    if ($item['pat_modpc'] && !$idx[1]) {
                        $used[$item['pat_keyword']][] = $item;
                    }

                    if ($item['pat_modcv'] && $idx[1]) {
                        $used[$item['pat_keyword']][] = $item;
                    }
                }
            } else
            {
                $used[0][] = $item;
            }
        }

        // 广告位置
        $mod = 'all';
        $adsAr = [];
        switch ($idx[0])
        {
            case 84:
            case 86:
                $com = new ComBase();
                $res = $com->Get(
                    'bc_brand join bc_model2 on brand_id = mod2_brand_id',
                    ['brand_id as id', 'brand_name as name', 'mod2_pc', 'mod2_cv', 'brand_initial'],
                    ' order by brand_name'
                );
                foreach ($res['data'] as $item)
                {
                    $mod = $idx[1] ? 'cv' : 'pc';
                    $col = $idx[1] ? 'mod2_cv' : 'mod2_pc';

                    if (!$item[$col] || isset($adsAr[$item['id']])) {
                        continue;
                    }

                    $chk = $price[$item['id']][$mod] ?? 0;
                    $res = $this->nadsSta($item, $used, $first, $chk, $adv);
                    $lab = sprintf('%s-%s-%s', $res['status'], $item['brand_initial'], $item['id']);

                    $adsAr[$lab] = [
                        'id' => $item['id'],
                        'name' => $item['name'],
                        'price' => $chk,
                        'class' => $res['cla'],
                        'status' => $res['sta'],
                        'btn' => $res['btn'],
                    ];
                }
                break;

            case 87:
                $chk = $price[0][$mod] ?? 0;
                $res = $this->nadsSta(['id' => 0], $used, $first, $chk, $adv);

                $adsAr = [
                    [
                        'id' => 0,
                        'name' => '独家',
                        'price' => $chk,
                        'class' => $res['cla'],
                        'status' => $res['sta'],
                        'btn' => $res['btn'],
                    ]
                ];
                break;

            default:
                $res = $ads->get('yp_province_city', ['pc_id as id', 'pc_name as name', 'pc_en_name'], 'and pc_pid = 0 order by pc_seq, pc_id');
                foreach ($res['data'] as $item)
                {
                    $chk = $price[$item['id']][$mod] ?? 0;
                    $res = $this->nadsSta($item, $used, $first, $chk, $adv);
                    $lab = sprintf('%s-%s-%s', $res['status'], $item['pc_en_name'], $item['id']);

                    $adsAr[$lab] = [
                        'id' => $item['id'],
                        'name' => $item['name'],
                        'price' => $chk,
                        'class' => $res['cla'],
                        'status' => $res['sta'],
                        'btn' => $res['btn'],
                    ];
                }
                break;
        }

        ksort($adsAr);
        LibTpl::Set('adsAr', $adsAr);
        LibTpl::Set('title', '广告报价');
        LibTpl::Put();
    }

    /**
     * 计算广告状态
     */
    public function nadsSta($item, $used, $first, $price, $checked)
    {
        // 查看广告数量
        // 查看最近到期, 30天内可预售
        $has = [
            'all' => 0, // 当前所有广告
            'has' => 0, // 不可销售数量
            'pre' => 0, // 可预售数量
            'fast' => 0, // 最快到期
        ];

        $time = time();
        if (isset($used[$item['id']]))
        {
            $has['all'] = count($used[$item['id']]);
            foreach ($used[$item['id']] as $item_exp)
            {
                $exp = (int) ceil(($item_exp['pat_etime'] - $time) / 3600 / 24);
                $lab = ($exp > 30) ? 'has' : 'pre';
                $has[$lab] += 1;

                // 最快到期时间
                if ($lab == 'pre')
                {
                    $date = date('Y-m-d', $item_exp['pat_etime']);

                    if (!$has['fast'] || ($has['fast'] < $date)) {
                        $has['fast'] = $date;
                    }
                }
            }
        }

        if ($has['all'] >= $first['pa_max'])
        {
            $res = ($has['has'] >= $first['pa_max'])
                ? ['sta' => '售罄', 'btn' => 'layui-btn-danger', 'status' => 3,]
                : ['sta' => sprintf('可预售[%s]', $has['fast']), 'btn' => 'layui-btn-warm', 'status' => 2,];
        } else
        {
            $res = ['sta' => '可售', 'btn' => '', 'status' => 1,];
        }

        // 售罄 & 暂无报价的情况, 不可选中
        $res['cla'] = 'disabled';
        if ($price && ($res['sta'] != '售罄')) {
            $res['cla'] = (false !== in_array($item['id'], $checked)) ? 'checked' : '';
        } else {
            $res['btn'] = 'layui-btn-danger';
            $res['status'] = 4;
        }

        return $res;
    }

    // 跑街令广告位简易报表
    public function nadsView()
    {
        // 可修改添加时间
        // 赠送广告位不能在已有的位置上
        // 购买-上线 有三天时间
        $time = strtotime(date('Y-m-d 00:00:00'));
        $Params = array_merge(['action' => 'all'], mvc::$URL_PARAMS);

        // 省份
        $ads = new AdsBase();
        $res = $ads->get('yp_province_city', ['pc_id as id', 'pc_name as name'], 'and pc_pid = 0 order by pc_seq, pc_id');
        $city = array_column($res['data'], null, 'id');

        // 品牌
        $make = [];
        $com = new ComBase();
        $res = $com->Get(
            'bc_brand join bc_model2 on brand_id = mod2_brand_id',
            ['brand_id as id', 'brand_name as name', 'mod2_pc', 'mod2_cv'],
            ' order by brand_name'
        );
        foreach ($res['data'] as $item)
        {
            if (!isset($make[$item['id']]))
            {
                $make[$item['id']] = [
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'mod2_pc' => 0,
                    'mod2_cv' => 0,
                ];
            }

            if ($item['mod2_pc'] && !$make[$item['id']]['mod2_pc']) {
                $make[$item['id']]['mod2_pc'] = 1;
            }

            if ($item['mod2_cv'] && !$make[$item['id']]['mod2_cv']) {
                $make[$item['id']]['mod2_cv'] = 1;
            }
        }

        // 按省或者品牌合并规整
        $world = [['id'=>0, 'name'=>'独家']];

        // 广告名称
        $area = $ads->get('pj_place', ['pa_id', 'pa_name', 'pa_size'], 'order by pa_name');
        $area = array_column($area['data'], null, 'pa_id');

        $area[84]['pa_name'] = 'VIN解码-乘用车';
        $area[84*10] = array_merge($area[84], [
            'pa_id' => 84*10,
            'pa_name' => 'VIN解码-商用车',
        ]);

        $area[86]['pa_name'] = '车型查询-乘用车';
        $area[86*10] = array_merge($area[86], [
            'pa_id' => 86*10,
            'pa_name' => '车型查询-商用车',
        ]);
        ksort($area, SORT_STRING);

        // 已有客户数据
        $where = '';
        $column = [
            'ads_id',
            'pla_id',
            'pla_pa_id',
            'pat_pc_id',
            'pla_sales',
            'ads_title',
            'pat_keyword',
            'pat_btime',
            'pat_etime',
            'ads_atime',
            'pla_remark',
            'pla_status',
            'pal_shoufei',
            'pat_modcv',
            'pat_modpc',
            'ads_sucai',
            'ads_require',
            'ads_sucai_time',
            'ads_template',
            'ads_design',
        ];
        foreach ($Params as $item_key => $item_val)
        {
            $item_val = trim($item_val);
            if (!$item_val) {
                continue;
            }

            switch ($item_key)
            {
                case 'word':
                    // 客户过滤
                    $where = sprintf('%s and ads_title like "%%%s%%"', $where, $item_val);
                    break;

                case 'shoufei':
                    // 收费过滤
                    $where = sprintf('%s and pal_shoufei = %d', $where, $item_val);
                    break;

                case 'pla_sales':
                    // 业务员过滤
                    $where = sprintf('%s and pla_sales = "%s"', $where, $item_val);
                    break;

                case 'betime':
                    // 添加时间
                    $betime = explode(' ~ ', $item_val);
                    $where = sprintf('%s and (ads_atime between %d and %d)', $where,
                        strtotime($betime[0] . ' 00:00:00'),
                        strtotime($betime[1] . ' 23:59:59')
                    );
                    break;

                case 'tftime':
                    // 投放时间
                    $tftime = explode(' ~ ', $item_val);
                    $where = sprintf('%s and (pat_btime >= %d and pat_etime <= %d)', $where,
                        strtotime($tftime[0] . ' 00:00:00'),
                        strtotime($tftime[1] . ' 23:59:59')
                    );
                    break;
            }
        }
        $where = sprintf('%s and pla_status >= 1 and pat_etime >= %d order by pat_etime', $where, $time);
        $table = 'pj_user_ads a JOIN pj_place_ads b ON ads_id = pla_ads_id join pj_place_ads_time on pla_id = pat_pla_id';
        $adsAr = $ads->get($table, $column, $where);

        // 业务员
        $where = sprintf('and pla_status >= 1 and pat_etime >= %d and pla_sales != "" order by pla_sales', $time);
        $sale = $ads->get($table, ['distinct pla_sales'], $where);
        $sale = array_column($sale['data'], 'pla_sales');

        // 广告价格
        $price = [];
        $adsApp = new BaseDb(mvc::$cfg['DB']['B2C']);
        $adsRes = $adsApp->get('yp_ads.all_ad_price', ['aap_p_id, aap_pc_id, aap_keyword, aap_price, app_modtype']," and aap_site='pjd' order by aap_p_id, app_modtype");
        foreach ($adsRes['data'] as $item)
        {
            $label = $item['aap_pc_id'] ?: $item['aap_keyword'];

            if ($item['aap_price']) {
                $price[$item['aap_p_id']][$label][$item['app_modtype'] ?: 'all'] = (int) $item['aap_price'];
            }
        }

        // 广告区域
        $conform = [];
        $hasAr = ['row' => 1, 'has' => 0, 'date' => 0];
        $column = ['pa_id', 'pa_name', 'pa_is_area', 'pa_is_keyword', 'pa_keyword_type', 'pa_max'];
        $place = $ads->get('pj_place', $column, 'and pa_status = 1 order by pa_seq');
        foreach ($place['data'] as $item)
        {
            if ($item['pa_is_area'] && $item['pa_is_keyword']) {
                continue;
            }

            // 广告位
            $item['use'] = [];
            $item['client'] = [];
            $item['size'] = $area[$item['pa_id']]['pa_size'];
            if ($item['pa_is_area'])
            {
                foreach ($city as $pk => $pv)
                {
                    $item['use'][$pk] = array_merge($pv, $hasAr, [
                        'max' => $item['pa_max'], // 广告位最大个数
                        'can' => $item['pa_max'],
                        'mod' => 'all',
                    ]);
                }
            } else if ($item['pa_is_keyword'])
            {
                foreach ($make as $pk => $pv)
                {
                    if ($pv['mod2_pc'])
                    {
                        $item['use'][$pk] = array_merge($pv, $hasAr, [
                            'max' => $item['pa_max'], // 广告位最大个数
                            'can' => $item['pa_max'],
                            'mod' => 'pc',
                        ]);
                    }

                    if ($pv['mod2_cv'])
                    {
                        $item['use_oth'][$pk] = array_merge($pv, $hasAr, [
                            'max' => $item['pa_max'], // 广告位最大个数
                            'can' => $item['pa_max'],
                            'mod' => 'cv',
                        ]);
                    }
                }
            } else
            {
                $item['use'][] = array_merge($world[0], $hasAr, [
                    'max' => $item['pa_max'], // 广告位最大个数
                    'can' => $item['pa_max'],
                    'mod' => 'all',
                ]);
            }

            if (false !== in_array($item['pa_id'], [84, 86])) {
                $item['pa_name'] .= '-乘用车';
            }

            // 广告数据
            foreach ($adsAr['data'] as $data)
            {
                if ($data['pla_pa_id'] != $item['pa_id']) {
                    continue;
                }

                // 剩余天数
                $data['s_date'] = date('Y-m-d', $data['pat_btime']);
                $data['e_date'] = date('Y-m-d', $data['pat_etime']);
                $data['ads_add_time'] = $data['ads_atime'];
                $data['ads_atime'] = date('Y-m-d', $data['ads_atime']);
                $data['pat_last_day'] = (int) ceil(($data['pat_etime'] - $time) /3600 /24);
                $data['pat_total_day'] = (int) ceil(($data['pat_etime'] - $data['pat_btime']) /3600 /24);

                if ($item['pa_is_area'])
                {
                    $item['client'][$data['pat_pc_id']][] = $data;
                } else if ($item['pa_is_keyword'])
                {
                    if ($item['pa_keyword_type'] === 'brand')
                    {
                        if ($data['pat_modpc'] && isset($make[$data['pat_keyword']]) && $make[$data['pat_keyword']]['mod2_pc']) {
                            $item['client'][$data['pat_keyword']][] = $data;
                        }

                        if ($data['pat_modcv'] && isset($make[$data['pat_keyword']]) && $make[$data['pat_keyword']]['mod2_cv']) {
                            $item['other'][$data['pat_keyword']][] = $data;
                        }
                    }
                } else
                {
                    $item['client'][0][] = $data;
                }
            }

            $conform[$item['pa_id']] = $item;

            // 乘/商用车
            if (false !== in_array($item['pa_id'], [84, 86]))
            {
                $item['pa_name'] = str_replace('乘用车', '商用车', $item['pa_name']);
                $item['client'] = $item['other'] ?? [];
                $item['use'] = $item['use_oth'] ?? [];

                $conform[$item['pa_id'] * 10] = $item;
            }
        }

        // 计算一些东西
        $today = date('Y-m-d', $time);
        switch ($Params['action'])
        {
            case 'kf':
                $change = [];
                $saller = ['cus' => [], 'place' => [], 'money' => [], 'free' => []];
                foreach ($conform as $key => $val)
                {
                    // 广告条件过滤
                    if (isset($Params['pa_id']) && $Params['pa_id'] && ($key != $Params['pa_id'])) {
                        continue;
                    }

                    foreach ($val['client'] as $kkk => $vvv)
                    {
                        foreach ($vvv as $kk1 => $vv1)
                        {
                            // 过滤省市品牌
                            if (isset($Params['tfword']) && $Params['tfword'])
                            {
                                $true = true;
                                $word = explode(',', str_replace('，', ',', $Params['tfword']));
                                foreach ($word as $item_wd)
                                {
                                    $item_wd = trim($item_wd);
                                    if ($item_wd && (false !== strpos($val['use'][$kkk]['name'], $item_wd))) {
                                        $true = false;
                                    }
                                }

                                if ($true) {
                                    continue;
                                }
                            }

                            $adsData = [
                                'ads_id' => $vv1['pla_id'],
                                'ads_name' => $val['pa_name'], // 广告位置
                                'ads_pa_id' => $val['pa_id'], // 广告位置id
                                'ads_pc' => $val['use'][$kkk]['name'], // 广告位置
                                'ads_title' => $vv1['ads_title'], // 公司名称
                                'ads_price' => $price[$val['pa_id']][$kkk][$val['use'][$kkk]['mod']] ?? '暂无', // 广告价格
                                'ads_sale' => $vv1['pla_sales'], // 业务员
                                'ads_last' => $vv1['pat_last_day'], // 剩余天数
                                'ads_shoufei' => $vv1['pal_shoufei'], // 收费
                                'ads_status' => $vv1['pla_status'], // 状态
                                'ads_s_day' => $vv1['s_date'], // 开始时间
                                'ads_e_day' => $vv1['e_date'], // 结束时间
                                'ads_total_day' => $vv1['pat_total_day'], // 时长
                                'ads_remark' => $vv1['pla_remark'], // 备注
                                'ads_add_day' => $vv1['ads_atime'], // 添加时间
                                'sucai' => $vv1['ads_sucai'], // 设计素材
                                'yaoqiu' => $vv1['ads_require'], // 设计要求
                                'sucai_first_time' => $vv1['ads_sucai_time'], // 设计要求
                            ];

                            if (!isset($change[$adsData['ads_title']]))
                            {
                                $change[$adsData['ads_title']] = [
                                    'rows' => 0,
                                    'ads' => [],
                                ];
                            }

                            $label = sprintf('%s-%s-%s-%s', $val['pa_name'], $val['use'][$kkk]['name'], $adsData['ads_s_day'], $adsData['ads_id']);
                            $change[$adsData['ads_title']]['ads'][$label] = $adsData;
                            $change[$adsData['ads_title']]['rows'] += 1;

                            // 有业务员的情况下
                            $saller['cus'][$adsData['ads_title']] = $adsData['ads_title'];

                            $label = '';
                            $plaStr = sprintf('%s-%s-%d', $val['pa_name'], $adsData['ads_pc'], $adsData['ads_id']);

                            if ($adsData['ads_shoufei'] == 1) {
                                $label = 'money';
                            }
                            if ($adsData['ads_shoufei'] == -1) {
                                $label = 'free';
                            }

                            if ($label) {
                                $saller[$label][$plaStr] = $plaStr;
                            }
                        }
                    }
                }
                LibTpl::Set('saller', $saller);
                ksort($change);
                break;

            // 我的
            case 'my':
            // 赠送
            case 'zs':
            // 预售
            case 'ys':
            // 待设计
            case 'dsj':
            // 最近到期
            case 'zjdq':
                $change = [];
                $orderby = [];
                $having = [];
                foreach ($conform as $key => $val)
                {
                    // 广告条件过滤
                    if (isset($Params['pa_id']) && $Params['pa_id'] && ($key != $Params['pa_id'])) {
                        continue;
                    }

                    foreach ($val['client'] as $kkk => $vvv)
                    {
                        foreach ($vvv as $kk1 => $vv1)
                        {
                            // 过滤省市品牌
                            if (isset($Params['tfword']) && $Params['tfword'])
                            {
                                $true = true;
                                $word = explode(',', str_replace('，', ',', $Params['tfword']));
                                foreach ($word as $item_wd)
                                {
                                    $item_wd = trim($item_wd);
                                    if ($item_wd && (false !== strpos($val['use'][$kkk]['name'], $item_wd))) {
                                        $true = false;
                                    }
                                }

                                if ($true) {
                                    continue;
                                }
                            }

                            // 赠送广告
                            if (($Params['action'] == 'zs') && ($vv1['pal_shoufei'] != -1)) {
                                continue;
                            }

                            // 预售广告 & 启用
                            if (($Params['action'] == 'ys') && ($vv1['s_date'] <= $today)) {
                                continue;
                            }

                            // 预售广告 & 设计阶段
                            if ($Params['action'] == 'dsj')
                            {
                                if ($vv1['pla_status'] != 2) {
                                    continue;
                                }

                                // 没有权限或者不是自己的广告不显示
                                if (($vv1['pla_sales'] != $_SESSION['_realname']) && !LibFc::checkDlRule('DL08', false)) {
                                    continue;
                                }
                            }

                            // 我的广告 $_SESSION['_realname']
                            if (($Params['action'] == 'my') && ($vv1['pla_sales'] != $_SESSION['_realname'])) {
                                continue;
                            }

                            $named = sprintf('%s-%s', $val['pa_name'], $val['use'][$kkk]['name']);
                            $label = sprintf('%d|%s|%s|%d', $vv1['pat_etime'], $named, $vv1['ads_title'], $vv1['ads_id']);
                            if ($Params['action'] == 'dsj')
                            {
                                $label = sprintf('%d|%d', $vv1['pat_btime'], $vv1['ads_id']);
                                if (false !== strpos($val['pa_name'], '-')) {
                                    $val['pa_name'] = substr($val['pa_name'], 0, strpos($val['pa_name'], '-'));
                                }
                            }

                            $adsData = [
                                'ads_id' => $vv1['pla_id'],
                                'ads_name' => $val['pa_name'], // 广告位置
                                'ads_pa_id' => $val['pa_id'], // 广告位置id
                                'ads_pc' => $val['use'][$kkk]['name'], // 广告位置
                                'ads_title' => $vv1['ads_title'], // 公司名称
                                'ads_price' => $price[$val['pa_id']][$kkk][$val['use'][$kkk]['mod']] ?? '暂无', // 广告价格
                                'ads_sale' => $vv1['pla_sales'], // 业务员
                                'ads_last' => $vv1['pat_last_day'], // 剩余天数
                                'ads_shoufei' => $vv1['pal_shoufei'], // 收费
                                'ads_status' => $vv1['pla_status'], // 状态
                                'ads_s_day' => $vv1['s_date'], // 开始时间
                                'ads_e_day' => $vv1['e_date'], // 结束时间
                                'ads_total_day' => $vv1['pat_total_day'], // 时长
                                'ads_remark' => $vv1['pla_remark'], // 备注
                                'ads_add_day' => $vv1['ads_atime'], // 添加时间
                                'sucai' => $vv1['ads_sucai'], // 设计素材
                                'yaoqiu' => $vv1['ads_require'], // 设计要求
                                'sucai_first_time' => $vv1['ads_sucai_time'], // 设计要求
                                'ads_design' => $vv1['ads_design'], // 通知设计时间
                            ];

                            // 添加提交素材, 添加广告时间差
                            if ($Params['action'] == 'dsj')
                            {
                                $adsData['check_sucai'] =
                                    $adsData['sucai_first_time']
                                    ? (int) ceil(($adsData['sucai_first_time'] - $vv1['ads_add_time']) / 3600 / 24)
                                    : 0;

                                $adsData['check_design'] =
                                    $adsData['ads_design']
                                        ? (int) ceil(($time - $adsData['ads_design']) / 3600 / 24)
                                        : 0;

                                $adsData['check_online'] = (int) ceil(($time - $vv1['ads_add_time']) / 3600 / 24);

                                // 选择样板
                                $adsData['ads_template'] = $vv1['ads_template']
                                    ? sprintf('https://file.paojd.cn/center/read.php?site=bna&c=bna&f=%s&i=f1', $vv1['ads_template'])
                                    : '/static/images/logo.png';
                            }

                            // 最近到期下面接预售信息
                            if (($Params['action'] == 'zjdq') && ($vv1['s_date'] > $today)) {
                                $orderby[$adsData['ads_name']][$adsData['ads_pc']][sprintf('%s-%d', $vv1['s_date'], $vv1['pla_id'])] = $adsData; continue;
                            }

                            $change[$label] = $adsData;
                            $having[$key][$kkk] = 1;
                        }
                    }
                }

                ksort($change);
                if ($Params['action'] == 'zjdq')
                {
                    $addPre = [];

                    // 预售 排位 到最近到期辣个
                    foreach ($change as $item_key => $item_val)
                    {
                        // 过滤可售
                        if (isset($Params['canSale']) && $Params['canSale'])
                        {
                            // 有预售
                            if (isset($orderby[$item_val['ads_name']][$item_val['ads_pc']]) && $orderby[$item_val['ads_name']][$item_val['ads_pc']])
                            {
                                array_shift($orderby[$item_val['ads_name']][$item_val['ads_pc']]);

                                continue;
                            }

                            // 收费 30内 & 赠送
                            if (($item_val['ads_shoufei'] == 1) && ($item_val['ads_last'] > 30)) {
                                continue;
                            }
                        }

                        $addPre[$item_key] = $item_val;

                        if (isset($orderby[$item_val['ads_name']][$item_val['ads_pc']]) && $orderby[$item_val['ads_name']][$item_val['ads_pc']])
                        {
                            $shift = array_shift($orderby[$item_val['ads_name']][$item_val['ads_pc']]);

                            $addPre[] = $shift;
                        }
                    }

                    // 剩余
                    foreach ($orderby as $item_key => $item_val)
                    {
                        foreach ($item_val as $item_kkk => $item_vvv)
                        {
                            foreach ($item_vvv as $item_vv1)
                            {
                                $addPre[] = $item_vv1;
                            }
                        }
                    }

                    $change = $addPre;

                    // 只显示空的位置
                    if (isset($Params['empty']) && $Params['empty']) {
                        $change = [];
                    }

                    // 没有收费的空位 排到 最后
                    foreach ($conform as $key => $val)
                    {
                        // 广告条件过滤
                        if (isset($Params['pa_id']) && $Params['pa_id'] && ($key != $Params['pa_id'])) {
                            continue;
                        }

                        foreach ($val['use'] as $kkk => $vvv)
                        {
                            if ($Params['pla_sales'] || $Params['shoufei'] || $Params['word'] || $Params['betime'] || $Params['tftime']) {
                                continue;
                            }

                            // 过滤省市品牌
                            if (isset($Params['tfword']) && $Params['tfword'])
                            {
                                $true = true;
                                $word = explode(',', str_replace('，', ',', $Params['tfword']));
                                foreach ($word as $item_wd)
                                {
                                    $item_wd = trim($item_wd);
                                    if ($item_wd && (false !== strpos($vvv['name'], $item_wd))) {
                                        $true = false;
                                    }
                                }

                                if ($true) {
                                    continue;
                                }
                            }

                            // 查找收费广告
                            $shoufei = [];
                            if (isset($val['client'][$kkk])) {
                                $shoufei = array_column($val['client'][$kkk], 'pal_shoufei');
                            }
                            $count = count($shoufei);
                            if ($count >= $vvv['max']) {
                                continue;
                            }

                            $change[] = [
                                'ads_id' => 0,
                                'ads_name' => $val['pa_name'], // 广告位置
                                'ads_pa_id' => $val['pa_id'], // 广告位置id
                                'ads_pc' => $vvv['name'], // 广告位置
                                'ads_title' => '', // 公司名称
                                'ads_price' => $price[$val['pa_id']][$kkk][$vvv['mod']] ?? '暂无', // 广告价格
                                'ads_sale' => '', // 业务员
                                'ads_last' => '', // 剩余天数
                                'ads_shoufei' => '', // 收费
                                'ads_status' => '', // 状态
                                'ads_s_day' => '', // 开始时间
                                'ads_e_day' => '', // 结束时间
                                'ads_total_day' => '', // 时长
                                'ads_remark' => '', // 备注
                                'ads_add_day' => '', // 添加时间
                                'sucai' => '', // 设计素材
                                'yaoqiu' => '', // 设计要求
                                'sucai_first_time' => '', // 设计要求
                                'ads_design' => '', // 通知设计时间
                            ];
                        }
                    }
                }
                break;

            // 可售
            case 'ks':
            // 全部
            default:
                $change = $conform;
                foreach ($change as $key => $val)
                {
                    $order = [];
                    foreach ($val['use'] as $kkk => $vvv)
                    {
                        $shoufei = [];
                        if (isset($val['client'][$kkk])) {
                            $shoufei = array_column($val['client'][$kkk], 'pal_shoufei');
                        }

                        // 表格行数
                        $count = count($shoufei);
                        $vvv['has'] = $count;
                        $vvv['row'] = $count ?: 1;

                        // 可售数量
                        $count = array_count_values($shoufei);
                        if (isset($count[1])) {
                            $vvv['can'] = ($count[1] >= $vvv['max']) ? 0 : ($vvv['max'] - $count[1]);
                        }

                        $label = sprintf('%d.%d', $price[$key][$kkk][$vvv['mod']] ?? 0, $kkk);
                        $order[$label] = $vvv;
                    }

                    krsort($order, SORT_NUMERIC);
                    $change[$key]['use'] = [];
                    foreach ($order as $item_or) {
                        $change[$key]['use'][$item_or['id']] = $item_or;
                    }
                }

                break;
        }

        LibTpl::Set('sale', $sale);
        LibTpl::Set('area', $area);
        LibTpl::Set('today', $today);
        LibTpl::Set('conform', $change);
        LibTpl::Set('price', $price);
        LibTpl::Set('Params', $Params);
        LibTpl::Set('title', '广告位简易报表');
        LibTpl::Put();
    }


    // 展示广告设计要求,素材
    public function nadsDesign()
    {
        $Params = mvc::$URL_PARAMS;

        // 已有数据
        $ads = new AdsBase();
        $adsAr = $ads->get('pj_user_ads', ['*'], sprintf('and ads_id = %d', $Params['ads']), true);

        LibTpl::Set('adsAr', $adsAr['data']);
        LibTpl::Put();
    }

    // 通知设计
    public function nadsDesignSave()
    {
        $res = ['res' => true, 'data' => ''];
        if (isset($_POST['ads_id']) && filter_var($_POST['ads_id'], FILTER_VALIDATE_INT))
        {
            $ads = new AdsBase();

            $table = 'pj_user_ads';
            $where = sprintf('and ads_id = %d', $_POST['ads_id']);
            $column = ['ads_design' => time()];

            // 更新素材数据
            $res = $ads->set($table, $column, $where);
        }

        echo json_encode($res);
    }

    // 保存广告要求, 素材
    public function nadsSave()
    {
        $res = ['res' => true, 'data' => ''];
        if (isset($_POST['ads_id']) && filter_var($_POST['ads_id'], FILTER_VALIDATE_INT))
        {
            $ads = new AdsBase();

            $table = 'pj_user_ads';
            $where = sprintf('and ads_id = %d', $_POST['ads_id']);
            $column = array_merge(['ads_sucai' => '', 'ads_require' => ''], $_POST);
            $column['ads_sucai'] = trim($column['ads_sucai']);

            // 查找是否第一次提交素材
            $res = $ads->get($table, ['ads_sucai_time'], $where, true);
            if ($column['ads_sucai'] && isset($res['data']['ads_sucai_time']) && !$res['data']['ads_sucai_time']) {
                $column['ads_sucai_time'] = time();
            }

            // 更新素材数据
            $res = $ads->set($table, $column, $where);
        }

        echo json_encode($res);
    }

    // 展示跑街令所有广告图片, 提供模板参考
    public function nadsTemplate()
    {
        $ads = new AdsBase();
        $Params = mvc::$URL_PARAMS;

        $adsAr = [];
        if (isset($Params['tpl']) && filter_var($Params['tpl'], FILTER_VALIDATE_INT))
        {
            $table = 'pj_user_ads join pj_place_ads on ads_id=pla_ads_id';
            $where = sprintf('and pla_pa_id =%d and ads_img != "" order by ads_atime desc', $Params['tpl']);
            $adsAr = $ads->get($table, ['distinct ads_img'], $where);

            $adsAr = $adsAr['data'];
        }

        LibTpl::Set('Params', $Params);
        LibTpl::Set('adsAr', $adsAr);
        LibTpl::Put();
    }

    // 保存广告样板
    public function nadsSaveTpl()
    {
        $res = ['res' => true, 'data' => ''];
        if (isset($_POST['ads_id']) && filter_var($_POST['ads_id'], FILTER_VALIDATE_INT))
        {
            $ads = new AdsBase();

            $table = 'pj_user_ads';
            $where = sprintf('and ads_id = %d', $_POST['ads_id']);
            $column = array_merge(['ads_template' => ''], $_POST);

            // 更新素材数据
            $res = $ads->set($table, $column, $where);
        }

        echo json_encode($res);
    }

	//申请单列表页面
	function applyList()
	{
		LibTpl::Set('title', '申请单列表');
		$typeArr = [
			'invcode'=>'邀请码',
			'user'=>'账户相关',
			'orther'=>'其他'
		];
		LibTpl::Set('typeArr', $typeArr);
		LibTpl::Put();
	}

	/* 
	* 获取申请单列表数据
	*/
	function getApplyList()
	{
		$statusArr = [
			'0'=>'待处理',
			'2'=>'初审状态',
			'1'=> '已处理',
			'-1'=> '退回'
			
		];
		$typeArr = [
			'invcode'=>'邀请码',
			'user'=>'账户相关',
			'orther'=>'其他'
		];
		$Params = mvc::$URL_PARAMS;
		$where = sprintf('and ap_by_uid=%d', $_SESSION['_userid']);
		
		foreach($Params as $filed=>$val)
		{
			$val = LibFc::Escape($val);
			if($val == '') continue;
			switch($filed)
			{
				case 'keyword':
					$where .= sprintf(" and ap_to_username like '%%%s%%'", $val);
				break;
				case 'ap_type':
					$where .= sprintf(" and ap_type = '%s'", $val);
				break;
			}
		}

		$PjlBase = new PjlBase();
		$res = $PjlBase->get('bu_apply',['count(*) count'], $where, true);
		$count = $res['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$res = $PjlBase->get('bu_apply',['*'],sprintf('%s limit %d, %d', $where, ($page-1)*$limit, $limit));
			
			if (!empty($res['data']))
			{
				$listArr = $res['data'];
				foreach($listArr as $k=> &$v)
				{	
					$v['status_text'] = $statusArr[$v['ap_status']]??'';
					$v['ap_type_text'] = $typeArr[$v['ap_type']]??'';
					$v['ap_atime'] = date('Y-m-d H:i', $v['ap_atime']);
					$v['imgs'] = $v['ap_imgs']?explode(',',$v['ap_imgs']):'';
					$v['ap_etime'] = $v['ap_etime']?date('Y-m-d H:i', $v['ap_etime']):'';
					//先给了间隔
					$v['ap_content'] = strip_tags(str_replace("<br>",'  ',$v['ap_content']));
					$listArr[$k] = $v;
				}
				unset($v);
			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$listArr
		];
		echo json_encode($arr);
	}

	// 提交申请单页面
	function apply()
	{	
		$title = '创建申请单';
		$Params = mvc::$URL_PARAMS;
		$PjlBase = new PjlBase();
		if(!empty($Params['ap_id']))
		{
			$title = '编辑申请单';
			$res = $PjlBase->get('bu_apply',['*'], sprintf(" and ap_id=%d", $Params['ap_id']), true);
			$applyArr = $res['data'];
			
			$applyArr['imgs'] = explode(',', $applyArr['ap_imgs']);
			LibTpl::Set('applyArr', $applyArr);
		}
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title', $title);
		LibTpl::Put();
	}
	
	//新增、编辑申请单
	function AddOrEditApply()
	{	
		$updateFlag = false;
		$PjlBase = new PjlBase();
		if(!empty($_POST['ap_id'])){
			$res = $PjlBase->get('bu_apply',['*'], sprintf(" and ap_id=%d ", $_POST['ap_id']), true);
			
			if(!empty($res['data'])){
				$updateFlag = true;
				//已处理不可编辑
				if($res['data']['ap_status']==1){
					LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'该申请单已处理完毕，不可编辑！']);
				}
			}
			
		}
		$ap_to_uid  = 0;
		$dataArr = ['account'=> trim($_POST['ap_to_username'])];
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('user/getUserByAccount',$dataArr);
		if($res['status']){
			$ap_to_uid = !empty($res['data'][0]['u_id'])?$res['data'][0]['u_id']:0;
		}
		$data   =  [
			'ap_type' => $_POST['ap_type'],
			'ap_to_uid' => $ap_to_uid, 
			'ap_imgs' =>  empty($_POST['imgs'])?'':implode(',',$_POST['imgs']),
			'ap_to_username'  =>	$_POST['ap_to_username']?trim($_POST['ap_to_username']):'',
			'ap_by_uid' => $_SESSION['_userid'],
			'ap_by_name' => $_SESSION['_realname'],
			'ap_content' => $_POST['ap_content'],
			'ap_status' => 0,
			'ap_atime' => time(),
		];
		if($updateFlag){
			$res =  $PjlBase->set('bu_apply',$data,sprintf(" and ap_id=%d ", $_POST['ap_id']));	
		}else{
			$res =  $PjlBase->add('bu_apply',$data);
		}
		
		return LibFc::ajaxJsonEncode($res);
		// $data = [
		// 	'code' => $res?1:0,
		// 	'msg' => $res?'操作成功':'操作失败，请重试',
		// ];
		// exit(json_encode($data));
	}
	// 删除申请单
	function delApply()
	{
		if (is_numeric($_POST['ap_id']) ) {
            $PjlBase = new PjlBase();
            $result = $PjlBase->del('bu_apply', sprintf(' and ap_id = %d ', $_POST['ap_id']));
        }
		LibFc::ajaxJsonEncode($result);
	}

	// 上传图片
	function uploadImg()
	{
		$site = isset($_REQUEST['site']) ? strtolower(trim($_REQUEST['site'])): 'b2c';
		$OthFileCenter = new OthFileCenter();
		$dataArr = ['cate'=>$_REQUEST['cate'], 'file'=>$_FILES['file']];
		$fileRes = $OthFileCenter->upload($dataArr, $site);
		LibFc::ajaxJsonEncode($fileRes);
	}

	/**
	 * @method 广告列表
	 * @author zhengweihua 
	 * @copyright 2023-05-30
	 */
	public function adsList()
	{
		$Params = mvc::$URL_PARAMS;


		//业务员
		$PjlBase = new PjlBase();
		$salesRes = $PjlBase->get('bu_user',['usr_name']," AND usr_status=1 AND usr_name!='' order by usr_seq,convert(usr_name using gbk)");
		LibTpl::Set('salesArr', $salesRes['data']);

		$AdsBase = new AdsBase();
		$res =$AdsBase->Get('pj_place', ['*'], ' order by pa_seq');
		$placeArr = $res['data'];
		LibTpl::Set('placeArr', $placeArr);
		LibTpl::Set('Params', $Params);
        LibTpl::Set('title', '广告列表-跑街的');
        LibTpl::Put();
	}

	/**
	 * @method 获取广告列表
	 * @author zhengweihua 
	 * @copyright 2023-05-29
	 */
	public function getAdsList()
	{
		LibFc::checkDlRule('DL07');
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
        $perPage = empty($Params['limit'])? 30: (int) $Params['limit'];
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
                case 'word':
                    $where .= sprintf(" and ads_name like '%%%s%%'", LibFc::Escape($v));
                break;
                case 'pa_id':
                    $where .= sprintf(" and pa_id =%d", $v);
                break;
				case 'pla_status':
                    $where .= sprintf(" and pla_status =%d", $v);
                break;
				case 'pla_sales':
                    $where .= sprintf(" and pla_sales ='%s'", LibFc::Escape($v));
                break;
				case 'pal_shoufei':
                    $where .= sprintf(" and pal_shoufei =%d", $v);
                break;
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and pla_atime >= %d and pla_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'valid_status':
					if($v == 1){
						$where .= sprintf(" and pat_btime <= %d and pat_etime + 86400 >= %d",time(),time());
					}
					if($v == -1){
						$where .= sprintf(" and pat_etime + 86400 < %d",time());
					}	
				break;
				case 'tftime':
					$t = explode(' ~ ', $v);
					$sql = sprintf(" select pat_pla_id from pj_place_ads_time where pat_btime >= %d or pat_etime < %d ",strtotime($t[1])+86400, strtotime($t[0]));
					$where .= sprintf(" and pla_id not in (%s)",$sql);
				break;
				case 'tfword':
					$orwhere  = [];
					$YpcBase = new YpcBase();
					$res =$YpcBase->Get('yp_brand', ['b_id'], sprintf(" AND b_name LIKE '%%%s%%' ",LibFc::Escape($v)));	
					if($res['data']){
						$orwhere[] = sprintf(" pat_keyword in (%s)",implode(',',array_column($res['data'],'b_id')));
					}
					$AdsBase = new AdsBase();
					$res =$AdsBase->Get('yp_province_city', ['pc_id'], sprintf(" AND pc_name LIKE '%%%s%%' ",LibFc::Escape($v)));
					if($res['data']){
						$orwhere[] = sprintf(" pat_pc_id in (%s)",implode(',',array_column($res['data'],'pc_id')));
					}
					$where .= sprintf(" and %s",implode(' or ',$orwhere));
				break;
				case 'mod_type':
					if($v=='pc'){
						$sql = " select pat_pla_id from pj_place_ads_time where pat_modpc = 1 and pat_modcv =0 ";
					}elseif ($v=='cv') {
						$sql = " select pat_pla_id from pj_place_ads_time where pat_modpc = 0 and pat_modcv =1 ";
					}elseif($v=='all') {
						$sql = " select pat_pla_id from pj_place_ads_time where pat_modpc = 1 OR pat_modcv =1 ";
					}
					$where .= sprintf(" and pla_id in (%s)",$sql);
				break;
            }
        }
		
		$AdsBase = new AdsBase();
		$res =$AdsBase->Get('yp_province_city', ['pc_id as id','pc_name as name'], '');
		$pcArr = array_column($res['data'], 'name', 'id');

		$YpcBase = new YpcBase();
		$res =$YpcBase->Get('yp_brand', ['b_id as id','b_name as name'], '');
		$brandArr = array_column($res['data'], 'name', 'id');

		$table = 'pj_place_ads join pj_place on pa_id=pla_pa_id join pj_place_group on pg_id=pa_pg_id join pj_user_ads on ads_id=pla_ads_id left JOIN pj_place_ads_time ON pat_pla_id = pla_id ';
		$res = $AdsBase->get($table, ['count(distinct pla_id) as count'], $where, true);
		$total = $res['data']['count'];
      
		$adsArr = [];
		if($total > 0)
		{
			$res = $AdsBase->get($table, ['*'], sprintf(" %s group by pla_id order by CASE WHEN MIN(pat_etime) > %d THEN MIN(pat_etime)-%d ELSE %d*2 END ASC, max(pat_etime) desc limit %d,%d", $where, time(), time(),time(), ($nowPage-1)*$perPage, $perPage));
			
			$adsArr = array_column($res['data'], null, 'pla_id');
			$absIds = array_column($res['data'],'pla_ads_id');
			if(!empty($adsArr))
			{
				$res = $AdsBase->get('pj_place_ads_time', ['*'], sprintf(" and pat_pla_id in(%s) order by pat_etime desc", implode(',', array_keys($adsArr))));
				/**
				 * @var $adsReportDate array 获取广告的展现量和点击量
				 */
				$adsReportDate = $AdsBase->get('pj_ads_report_date',['ard_ads_id','sum(ard_show) as ard_show_sum,sum(ard_click) as ard_click_sum'],sprintf(' and ard_ads_id in(%s) group by ard_ads_id',implode(',',$absIds)));
				if(!empty($adsReportDate['data']))
				{
					$adsReportDate = array_column($adsReportDate['data'],null,'ard_ads_id');
					foreach($adsReportDate as &$value)
					{
						$value['click_rate'] = $value['ard_click_sum'] > 0 ? (number_format($value['ard_click_sum'] / $value['ard_show_sum'],4) * 100). '%' : '';
					}
				}
				else
				{
					$adsReportDate = [];
				}
				foreach ($adsArr as $key => $val) {
					$val['ard_show_sum'] = $adsReportDate[$val['pla_ads_id']]['ard_show_sum']?:'';
					$val['ard_click_sum'] = $adsReportDate[$val['pla_ads_id']]['ard_click_sum'] ?: '';
					$val['click_rate'] = $adsReportDate[$val['pla_ads_id']]['click_rate'] ?: '';
					$adsArr[$key] = $val;
				}

				foreach($res['data'] as $v)
				{
					$v['word'] = [];

					if($adsArr[$v['pat_pla_id']]['pa_keyword_type'] == 'brand'){
						$v['word'][] = $brandArr[$v['pat_keyword']];
					}

					if($adsArr[$v['pat_pla_id']]['pa_is_area']){
						$v['word'][] = $pcArr[$v['pat_pc_id']];
					}
					$v['word'] = implode(' ', $v['word']);
					
					$adsArr[$v['pat_pla_id']]['times'][] = $v;
				}
			}
		}
		
		$this->ajaxReturnJson(0,'',$total,array_values($adsArr));
		
	}

	/**
	 * @method 广告位统计
	 * @author zhengweihua 
	 * @copyright 2023-05-29
	 */
    public function adSlotStatistics()
    {
        //todo 权限
        $params = mvc::$URL_PARAMS;
        $plaId = (int) $params['ard_id'];
        if($plaId <= 0){
            echo '';exit;
        }
        $adsDb = (new AdsBase)->AdsDb;

		$groupByArr = [
			'day'=>['日统计', 'ard_date'],
			'month'=>['月统计', 'left(ard_date,6)'],
			'year'=>['年统计', 'left(ard_date,4)']
		];
		LibTpl::Set('groupByArr',$groupByArr);
		if(empty($groupByArr[$params['group']]))
			$params['group'] = 'month';
		$dfiled = $groupByArr[$params['group']][1];

        $result = $adsDb->Table(sprintf("select * from pj_place_ads_time where pat_pla_id =%d order by pat_etime desc",$plaId));
        $a = $adsDb->Row(sprintf("select * from pj_place_ads join pj_place on pa_id=pla_pa_id join pj_place_group on pg_id=pa_pg_id join pj_user_ads on ads_id=pla_ads_id JOIN pj_place_ads_time ON pat_pla_id = pla_id where ads_id=%d",$plaId));
        if($a['pa_keyword_type'] == 'brand'){
            $brandId = array_column($result,'pat_keyword');
            $where = '';
           
            $YpcBase = new YpcBase();
            $res =$YpcBase->Get('yp_brand', ['b_id as id','b_name as name'], sprintf(' and b_id in (%s) order by b_initial',implode(",",$brandId)));
            $allPcArr = array_column($res['data'], null, 'id');
            if(!empty($params['ard_month'])){
                $temp = explode(" ~ ",$params['ard_month']);
				$temp[0] = (int) date('Ymd',strtotime($temp[0]));
				//月份的天数
				$daynum = date('t',strtotime($temp[1]));
				$temp[1] = date('Ym',strtotime($temp[1])).$daynum;
               
                $where .= sprintf(" and ard_date between %d and %d",$temp['0'],$temp['1']);
            }
            if(!empty($params['ard_brand'])){
                $where .= sprintf(" and ard_word=%d",$params['ard_brand']);
            }
            $brand = $adsDb->Table(sprintf("select ard_word,sum(ard_show) as ard_show,sum(ard_click) ard_click, %s as ard_month from pj_ads_report_date as a where ard_ads_id=%d and 1=1 %s GROUP BY ard_month,ard_word order by ard_month desc",$dfiled, $plaId,$where));
            $brandArr = [];
            $click = 0;
            $show = 0;
            $other = [];
            foreach ($brand as $key => $value)
            {
                $click += $value['ard_click'];
                $show += $value['ard_show'];
                if(!in_array($value['ard_word'],$brandId)){
                    $other[] = $value;
                    unset($brand[$key]);
                }
            }
            $others = [];
            foreach ($other as $value)
            {
                $others[$value['ard_month']]['ard_click'] += $value['ard_click'];
                $others[$value['ard_month']]['ard_show'] += $value['ard_show'];
            }
            foreach ($brand as $val)
            {
                $brandArr[$val['ard_month']][] = $val;
            }
            $temp = [
                'ard_month' => '<span style="color: red;">全部汇总</span>',
                'ard_word' => '',
                'ard_pct_id' => '',
                'ard_show' => $show,
                'ard_click' => $click
            ];
            foreach ($brandArr as $key => &$item)
            {
                if(isset($others[$key])){
                    array_push($item,[
                        'ard_month' => $key,
                        'ard_word' => '其它',
                        'ard_pct_id' => 0,
                        'ard_show' => $others[$key]['ard_show'],
                        'ard_click' => $others[$key]['ard_click']
                    ]);
                }
                if(count($item) > 1){
                    foreach ($item as &$items)
                    {
                        if($items['ard_word'] != '其它'){
                            $items['ard_word'] = $allPcArr[$items['ard_word']]['name'];
                        }
                    }
                    array_multisort(array_column($item,'ard_show'), SORT_DESC, $item);
                    array_push($item,[
                        'ard_word' => "<span style='color: red;'>当月汇总<span>",
                        'ard_pct_id' => '',
                        'ard_show' => array_sum(array_column($item,'ard_show')),
                        'ard_click' => array_sum(array_column($item,'ard_click')),
                        'ard_month' => $item['0']['ard_month']
                    ]);
                }else{
                    $item['0']['ard_word'] = $allPcArr[$item['0']['ard_word']]['name'];
                }
            }
            $brandArr['全部汇总']['0'] = $temp;
            LibTpl::Set('allPcArr',$allPcArr);
            LibTpl::Set('brandArr',$brandArr);
        }
        if(empty($brandArr)){
            //todo 优化
			$where = '';
			if(!empty($params['ard_month'])){
				$temp = explode(" ~ ",$params['ard_month']);
				$temp[0] = (int) date('Ymd',strtotime($temp[0]));
				//月份的天数
				$daynum = date('t',strtotime($temp[1]));
				$temp[1] = date('Ym',strtotime($temp[1])).$daynum;
				$where .= sprintf(" and ard_date between %d and %d",$temp['0'],$temp['1']);
			}
            if($a['pa_is_area']){
                $cityId = array_column($result,'pat_pc_id');
                //$where = '';
                //$where .= sprintf(" and ard_pct_id in (%s)",implode(",",$cityId));
                if(!empty($params['pc_id'])){
                    $where .= sprintf(" and ard_pct_id=%d",$params['pc_id']);
                }

                $address = $adsDb->Table(sprintf("select pc_id as id ,pc_name as name from yp_province_city where pc_pid=0 and pc_id in (%s)",implode(',',$cityId)));
                $address = array_column($address,null,'id');
                $list =  $adsDb->Table(sprintf("select ard_pct_id,sum(ard_show) as ard_show,sum(ard_click) ard_click, %s as ard_month from pj_ads_report_date where ard_ads_id=%d and 1=1 %s GROUP BY ard_month,ard_pct_id order by ard_month desc",$dfiled, $plaId,$where));
                $other = [];
                $click = 0;
                $show = 0;
                foreach ($list as $key => $value)
                {
                    $click += $value['ard_click'];
                    $show += $value['ard_show'];
                    if(!in_array($value['ard_pct_id'],$cityId)){
                        $other[] = $value;
                        unset($list[$key]);
                    }
                }
                $others = [];
                foreach ($other as $value)
                {
                    $others[$value['ard_month']]['ard_click'] += $value['ard_click'];
                    $others[$value['ard_month']]['ard_show'] += $value['ard_show'];
                }
                $listArr = [];
                foreach ($list as $value)
                {
                    $listArr[$value['ard_month']][] = $value;
                }
                $temp = [
                    'ard_month' => '<span style="color: red;">全部汇总</span>',
                    'pc_name' => '',
                    'ard_pct_id' => '',
                    'ard_show' => $show,
                    'ard_click' => $click
                ];
                foreach ($listArr as $key => &$value)
                {
                    if(isset($others[$key])){
                        array_push($value,[
                            'ard_month' => $key,
                            'pc_name' => '其它',
                            'ard_pct_id' => 0,
                            'ard_show' => $others[$key]['ard_show'],
                            'ard_click' => $others[$key]['ard_click']
                        ]);
                    }

                    if(count($value) > 1){
                        array_multisort(array_column($value,'ard_show'), SORT_DESC, $value);
                        foreach ($value as &$items)
                        {
                            if($items['pc_name'] != '其它'){
                                $items['pc_name'] = $address[$items['ard_pct_id']]['name'];
                            }
                        }
                        //var_dump($value);
                        array_push($value,[
                            'pc_name' => "<span style='color: red;'>当月汇总<span>",
                            'ard_pct_id' => '',
                            'ard_show' => array_sum(array_column($value,'ard_show')),
                            'ard_click' => array_sum(array_column($value,'ard_click')),
                            'ard_month' => $value['0']['ard_month']
                        ]);
                    }else{
                        $value['0']['pc_name'] = $address[$value['0']['ard_pct_id']]['name'];
                    }
                }
                $listArr['全部汇总']['0'] = $temp;
                LibTpl::Set('address',$address);
                LibTpl::Set('listArr',$listArr);
            }
			else
			{
				$list =  $adsDb->Table(sprintf("select ard_pct_id,sum(ard_show) as ard_show,sum(ard_click) ard_click, %s as ard_month from pj_ads_report_date where ard_ads_id=%d and 1=1 %s GROUP BY ard_month order by ard_month desc",$dfiled, $plaId,$where));
                $other = [];
                $click = 0;
                $show = 0;
                foreach ($list as $key => $value)
                {
                    $click += $value['ard_click'];
                    $show += $value['ard_show'];
                }
                
                $listArr = [];
                foreach ($list as $value)
                {
                    $listArr[$value['ard_month']][] = $value;
                }
                $temp = [
                    'ard_month' => '<span style="color: red;">全部汇总</span>',
                    'ard_show' => $show,
                    'ard_click' => $click
                ];
                foreach ($listArr as $key => &$value)
                {
                    if(isset($others[$key])){
                        array_push($value,[
                            'ard_month' => $key,
                            'ard_show' => $others[$key]['ard_show'],
                            'ard_click' => $others[$key]['ard_click']
                        ]);
                    }

                    if(count($value) > 1){
                        array_multisort(array_column($value,'ard_show'), SORT_DESC, $value);
                        array_push($value,[
                            'ard_show' => array_sum(array_column($value,'ard_show')),
                            'ard_click' => array_sum(array_column($value,'ard_click')),
                            'ard_month' => $value['0']['ard_month']
                        ]);
                    }
                }
				unset($value);
                $listArr['全部汇总']['0'] = $temp;
                LibTpl::Set('quanqiuArr',$listArr);
			}
        }

        LibTpl::Set('title',$a['ads_name'].'---统计报表');
        LibTpl::Set('param',$params);
        LibTpl::Set('plaId',$plaId);
        $res = LibTpl::Fetch();
		echo $res;
    }

	/**
	 * @method 跟进记录列表
	 * @author zhengweihua 
	 * @copyright 2023-12-25
	 */
	public function followList()
	{	
		LibFc::checkDlRule('DL05');
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user',['au_uid,au_group,au_name']," AND au_group IN ('跑街令','业务部') AND au_status=1 ORDER BY  au_name desc");
		$salesArr =[];
		foreach ($res['data'] as $key => $val) {
			$salesArr[$val['au_group']][$val['au_uid']] = $val['au_name'];
		}
		foreach ($salesArr as $skey => $sval) {
			$allKeys =array_keys($sval);
			
			$salesArr[$skey][implode(',',$allKeys)] = sprintf('选择 [%s] 所有人', $skey);
		}
		$dayRange = date('Y-m-d').' ~ '.date('Y-m-d');
		LibTpl::Set('dayRange',$dayRange);
		LibTpl::Set('salesArr',$salesArr);
		LibTpl::Put();
	}

	/**
	 * @method  获取跟进记录列表
	 * @author zhengweihua 
	 * @copyright 2023-12-25
	 */
	public function getFollowList()
	{
		LibFc::checkDlRule('DL05');
		$Params = mvc::$URL_PARAMS;
		$BaseDb = new BaseDb(mvc::$cfg['DB']['YPCRM']);
		$order = 'order by cfo_atime desc';
		$where = '';
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'keyword':
					$where .=sprintf("AND ctr_comname like '%%%s%%'",$v);
					break;
              	case 'follow_name':
				$where .=sprintf(" AND cfo_au_uid IN (%s)",$v);
					break;
				case 'follow_time':
					//最后申请时间
					$temp = explode('~',$v);
					if(count($temp)>1){
						$where .= sprintf(" AND  cfo_atime between %d and %d",strtotime($temp[0]),strtotime($temp[1])+86399);
					}
					break;
            }
        }
		$table = 'crm_follow left join crm_customer on cfo_ctr_id = ctr_id';
		$countres = $BaseDb->get($table,['count(*) as count'],$where,true);
		$count = $countres['data']['count'];
		$listArr = [];
		if ($count > 0)
		{
			$page = (int) $Params['page'];
			$page = $page < 1 ? 1: $page;
			$limit = empty($Params['limit'])? 30: (int) $Params['limit'];
			$fields = ['crm_follow.*,ctr_comname,ctr_contact,ctr_tel'];

			$res = $BaseDb->get($table, $fields,sprintf('%s %s limit %s, %s', $where,$order, ($page-1)*$limit, $limit));
			if(!empty($res['data']))
			{
				$listArr = $res['data'];	

			}
		}
		$arr = [
			"code"=>0,
			"msg"=>"",
			"count"=>$count,
			"data"=>$listArr
		];
		echo json_encode($arr);
	}

}



