<?php
class indexAction extends baseAction
{

	function test()
	{
		$B2cZhipei = new B2cZhipei();
		$ZpBase = new BaseDb(mvc::$cfg['DB']['ZHIPEIC']);
		$res = $B2cZhipei->matchItemModel(51842890);
		var_dump($res);
		exit;

		$libYpApi = new LibYpApi();
		$param = [
		    'Owner_Account' => 'yipartsb2c', //群ID
		    'Type' => 'Public', //公开的
		    'Name' => 'test',//群名称
		 
		];
		$res = $libYpApi->get('im/getApi',[], ['apiName'=>'v4/group_open_http_svc/create_group','params'=>$param]);
		var_dump($res);
	}


	function http_post_json($url, $jsonStr)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: text/plain;charset=UTF-8',
				'Content-Length: ' . strlen($jsonStr)
			)
		);
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		
		return $response;
	}




	
	function index()
	{

		LibTpl::Set('title', '管理系统-跑街的');
		
		LibTpl::Put();
	}

	function main()
	{
		LibRule::Check('HP00');
		LibTpl::Set('title', '管理系统-跑街的');
		$B2cBase = new B2cBase();
		//今天的事件戳
		$todayTime = strtotime(date('Y-m-d',time()));
		//昨天的时间戳
		$YSYTime = strtotime(date('Y-m-d',strtotime("-1 day")));
		//30天
		$THYTime = time() - 60*60*24*30;

		//售出的配件
		$saleBaseWhere = "and orp_status='completed' and orp_refund_status !='refunded'";
		$sale = [
			'saleToday'=>sprintf(' and ord_pay_time between %d and %d',$todayTime,time()),
			'saleYesterday'=>sprintf(' and ord_pay_time between %d and %d',$todayTime-60*60*24,$todayTime),
			'saleMonth'=>sprintf(' and ord_pay_time between %d and %d',$THYTime,time()),
			'saleAll'=>''
		];
		foreach ($sale as $key => $value) 
		{
			$res = $B2cBase->get('or_order_product left join or_order on orp_ord_id=ord_id',['count(*) count'],$saleBaseWhere.$value,true);
			if(!empty($res['data']['count']))
			{
				LibTpl::Set($key,$res['data']['count']);
			}
		}

		//支付的金额
		$BaseWhere = "and (mon_stype='0' or mon_stype='1') group by mon_stype";
		$status=['0'=>'pay','1'=>'refunded'];
		$sale = [
			'Today'=>sprintf('and mon_atime>=%d and mon_atime<%d %s',$todayTime,time(),$BaseWhere),
			'Yesterday'=>sprintf('and mon_atime>=%d and mon_atime<%d %s',$todayTime-60*60*24,$todayTime,$BaseWhere),
			'Month'=>sprintf('and mon_atime>=%d and mon_atime<%d %s',$THYTime,time(),$BaseWhere),
			'All'=>$BaseWhere,
		];
		foreach ($sale as $key => $value) 
		{
			$res = $B2cBase->get('sh_money',['sum(abs(mon_money)) count','mon_stype'],$value);
			$res = array_column($res['data'],'count','mon_stype');
			if(!empty($res))
			{
				foreach($res as $k=>$v)
				{
					LibTpl::Set($status[$k].$key,$v);
				}
			}
		}

		//配件售后
		$res = $B2cBase->get('or_order_product',['count(*) count','orp_refund_status'],"and (orp_refund_status='wait' or orp_refund_status='refunded') group by orp_refund_status");
		$res = array_column($res['data'],'count','orp_refund_status');
		LibTpl::Set('refund',$res);

		//订单
		$res = $B2cBase->get('or_order',['count(*) count','ord_status']," group by ord_status");
		$res = array_column($res['data'],'count','ord_status');
		LibTpl::Set('order',$res);
		//订单金额
		$sale = ['creat','completed','cancel'];
		$res = $B2cBase->get('or_order',['sum(ord_pay_money) count','ord_status'],"group by ord_status");
		$res = array_column($res['data'],'count','ord_status');
		LibTpl::Set('orderMoney',$res);

		//配件
		$res = $B2cBase->get('bc_product',['count(*) count','pro_status'],"group by pro_status");
		$res = array_column($res['data'],'count','pro_status');
		LibTpl::Set('product',$res);
		$res = $B2cBase->get('bc_product',['count(*) count','pro_promoted'],"group by pro_promoted");
		$res = array_column($res['data'],'count','pro_promoted');
		LibTpl::Set('productRecommend',$res);

		//店铺
		$res = $B2cBase->get('sh_shop',['count(*) count','shop_status'],"group by shop_status");
		$res = array_column($res['data'],'count','shop_status');
		LibTpl::Set('shop',$res);
		LibTpl::Put();
	}

	public function pjlMain()
	{
		LibTpl::Set('title', '管理系统-跑街令');
		$PjlBase = new PjlBase();
		//今天的事件戳
		$todayTime = strtotime(date('Y-m-d',time()));
		//昨天的时间戳
		$YSYTime = strtotime(date('Y-m-d',strtotime("-1 day")));
		//30天
		$THYTime = time() - 60*60*24*30;

		//询价
		$purchaseWhere = " and (pur_status=0 or pur_status=-1)";
		$status=['0'=>'using','-1'=>'stop'];
		$purArr = [
			'purToday'=>sprintf(' and pur_atime between %d and %d',$todayTime,time()),
			'purYesterday'=>sprintf(' and pur_atime between %d and %d',$todayTime-60*60*24,$todayTime),
			'purMonth'=>sprintf(' and pur_atime between %d and %d',$THYTime,time()),
			'purAll'=>''
		];
		foreach ($purArr as $key => $value) 
		{
			$res = $PjlBase->get('pl_purchase',['count(*) count','pur_status'],$purchaseWhere.$value.' group by pur_status');
			if(!empty($res['data']))
			{
				foreach ($res['data'] as $value) 
				{
					LibTpl::Set($key.$status[$value['pur_status']],$value['count']);
				}

			}
		}

		//报价
		$offerWhere = " ";
		$status=['1'=>'using','-1'=>'stop'];
		$offArr = [
			'offToday'=>sprintf(' and po_atime between %d and %d',$todayTime,time()),
			'offYesterday'=>sprintf(' and po_atime between %d and %d',$todayTime-60*60*24,$todayTime),
			'offMonth'=>sprintf(' and po_atime between %d and %d',$THYTime,time()),
			'offAll'=>''
		];
		foreach ($offArr as $key => $value) 
		{
			$res = $PjlBase->get('pl_purchase_offer',['count(*) count','po_status'],$offerWhere.$value.' group by po_status');
			if(!empty($res['data']))
			{
				foreach ($res['data'] as $value) 
				{
					LibTpl::Set($key.$status[$value['po_status']],$value['count']);
				}

			}
		}

		//售出的配件
		$saleBaseWhere = " and ord_status='completed'";
		$sale = [
			'saleToday'=>sprintf(' and ord_pay_time between %d and %d',$todayTime,time()),
			'saleYesterday'=>sprintf(' and ord_pay_time between %d and %d',$todayTime-60*60*24,$todayTime),
			'saleMonth'=>sprintf(' and ord_pay_time between %d and %d',$THYTime,time()),
			'saleAll'=>''
		];
		foreach ($sale as $key => $value) 
		{
			$res = $PjlBase->get('pl_order_product left join pl_order on odp_ord_id=ord_id',['count(*) count'],$saleBaseWhere.$value,true);
			if(!empty($res['data']['count']))
			{
				LibTpl::Set($key,$res['data']['count']);
			}
		}

		//支付的金额
		$BaseWhere = " and orp_status='paied'";
		$status=['0'=>'paied','1'=>'refunded'];
		$sale = [
			'Today'=>sprintf('and orp_atime>=%d and orp_atime<%d %s',$todayTime,time(),$BaseWhere),
			'Yesterday'=>sprintf('and orp_atime>=%d and orp_atime<%d %s',$todayTime-60*60*24,$todayTime,$BaseWhere),
			'Month'=>sprintf('and orp_atime>=%d and orp_atime<%d %s',$THYTime,time(),$BaseWhere),
			'All'=>$BaseWhere,
		];
		foreach ($sale as $key => $value) 
		{
			//订单金额
			$res = $PjlBase->get('pl_order_pay',['sum(abs(orp_money)) count','orp_status'],$value);
			$res = array_column($res['data'],'count','orp_status');
			if(!empty($res))
			{
				foreach($res as $k=>$v)
				{
					LibTpl::Set('paied'.$key,$v);
				}
			}
		}

		//配件售后
		$res = $PjlBase->get('pl_refund_pact',['count(*) count','rep_status'],"and (rep_status='wait' or rep_status='refunded') group by rep_status");
		$res = array_column($res['data'],'count','rep_status');
		LibTpl::Set('refund',$res);

		//订单
		$res = $PjlBase->get('pl_order',['count(*) count','ord_status']," group by ord_status");
		$res = array_column($res['data'],'count','ord_status');
		LibTpl::Set('order',$res);

		//订单金额
		$sale = ['creat','completed','cancel'];
		$res = $PjlBase->get('pl_order',['sum(ord_money) count','ord_status'],"group by ord_status");
		$res = array_column($res['data'],'count','ord_status');
		LibTpl::Set('orderMoney',$res);

		//配件
		// $res = $PjlBase->get('bc_product',['count(*) count','pro_status'],"group by pro_status");
		// $res = array_column($res['data'],'count','pro_status');
		// LibTpl::Set('product',$res);
		// $res = $PjlBase->get('bc_product',['count(*) count','pro_promoted'],"group by pro_promoted");
		// $res = array_column($res['data'],'count','pro_promoted');
		// LibTpl::Set('productRecommend',$res);

		//店铺
		$res = $PjlBase->get('pl_shop',['count(*) count','shop_status'],"group by shop_status");
		$res = array_column($res['data'],'count','shop_status');
		LibTpl::Set('shop',$res);
		LibTpl::Put();
	}

	function pjlReport()
	{
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->get('index/getTjReportUrl', ['site'=>'PJL', 'uid'=>$_SESSION['admin_userid']]);
		header("Location: ".$res['data']);
	}


	/**
	  * @method 图片上传
	  * @http  post
	  * @param  site  站点 跑街令:pjl[默认]  商城:b2c 宜配:yp
	  * @param  cate  类别
	  * @param  imgurl  图片地址 优先
	  * @param  file  $_FILES 
	  * @author soul
	  * @copyright 2017/5/9
	  * @return  json  {status:true,data:{
	  *          			crc32: "21305987"
							etime: 1535704530
							ext: "jpg"
							heigth: 428
							name: "286b24da071ccfdc"
							oriname: "微信图片_20180831141507"
							path: "20180831/"
							sfile: "20180831/240/286b24da071ccfdc.jpg"
							size: 32838
							small: "240/"
							url: "http://192.168.1.42/file_center/center/read.php?site=pjl&c=purchase&f=20180831/240/286b24da071ccfdc.jpg&i=42"
							width: 640
	  *          	}}		
	  */
	public function uploadImg()
	{
		$site = isset($_REQUEST['site']) ? strtolower(trim($_REQUEST['site'])): 'b2c';
		$OthFileCenter = new OthFileCenter();
		if(!empty($_POST['imgurl'])){
			$dataArr = [
				'cate'=>$_REQUEST['cate'], 
				'file'=>[
					'name'=>empty($_POST['imgName'])? 'temp.jpg': $_POST['imgName'],
					'data'=>base64_decode(substr(strstr($_POST['imgurl'], ','), 1))
				]
			];
		}else{
			$dataArr = ['cate'=>$_REQUEST['cate'], 'file'=>$_FILES['file']];
		}
		$fileRes = $OthFileCenter->upload($dataArr, $site);
		LibFc::ajaxJsonEncode($fileRes);
	}


	/**
	  * @method 搜索宜配会员
	  * @http  post
	  * @param  keywords 关键字
	  * @author soul
	  * @copyright 2017/5/9
	  * @return  	
	  */
	public function searchUser()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		$word = LibFc::Escape($Params['query']);
		if(strlen($word) > 2)
		{
			$LibYpApi = new LibYpApi();
			$post = [
				'filed'=>['u_id', 'u_name', 'u_mobile'],
				'where'=>sprintf(" and u_name like '%%%s%%' or u_mobile like '%%%s%%' order by u_name limit 20", $word, $word)
			];
			$res = $LibYpApi->get('user/getUser', [], $post);
			$arr = $res['data'];
		}
		echo json_encode($arr);
	}


	/**
	  * @method article图片上传
	  * @author liao
	  * @copyright 2018/3/7
	  */
	function uploadImgEditor()
	{
		$Params = mvc::$URL_PARAMS;
		$OthFileCenter = new OthFileCenter();
		$site = isset($_REQUEST['site']) ? strtolower(trim($_REQUEST['site'])): 'pjl';
		$dataArr = ['cate'=>$_REQUEST['cate'], 'file'=>$_FILES['upfile']];
		$fileRes = $OthFileCenter->upload($dataArr, $site);
		if($fileRes['status'])
		{
			$dataArr=[
				"state"=>"SUCCESS",
				"url"=>str_replace($fileRes['data']['small'], '', $fileRes['data']['url']),
				"title"=>$fileRes['data']['name'].'.'.$fileRes['data']['ext'],
    			"original"=>$fileRes['data']['name'].'.'.$fileRes['data']['ext']
			];
			echo json_encode($dataArr);
			die;
		}
		echo json_encode(["state"=>"ERROR",]);
	}

    /**
     * layui.code
      * {
      * "code": 0 //0表示成功，其它失败
      * ,"msg": "" //提示信息 //一般上传失败后返回
      * ,"data": {
      * "src": "图片路径"
      * ,"title": "图片名称" //可选
      * }
      * }
     * @method layui富文本图片上传
     * @author yangxing
     * @copyright 2018/3/7
     */
    function uploadImgLayuiEditor()
    {
        $Params = mvc::$URL_PARAMS;
        $OthFileCenter = new OthFileCenter();
        $site = isset($_REQUEST['site']) ? strtolower(trim($_REQUEST['site'])): 'pjl';
        $dataArr = ['cate'=>$_REQUEST['cate'], 'file'=> $_FILES['file']];
        if(!file_exists($dataArr['file']['tmp_name'])){
            ob_clean();
            echo json_encode(['code' => 1 ,'msg' => 'OthFileCenter=>upload 找不到临时文件' ,'data' => []]); exit();
        }
        $fileRes = $OthFileCenter->upload($dataArr, $site);
        if($fileRes['status'])
        {
            $dataArr=[
                "code" => 0,
                "msg" => "上传成功",
                "data" => [
                    'src' => str_replace($fileRes['data']['small'], '', $fileRes['data']['url']),
                ]
            ];
            ob_clean();
            echo json_encode($dataArr);
            die;
        }
        ob_clean();
        echo json_encode(["code"=>1,"msg" => "服务器错误，请重试",'data' => []]);
    }

	/**
	 * @method 导出品牌统计
	 * @author zhengweihua 
	 * @copyright 2024-12-26
	 */
	public function exportBrandTj()
	{
		
		$params = mvc::$URL_PARAMS;
        $where = '';
        if(empty($params['year'])){
			$params['year'] = date('Y');
        }
		$start = $params['year'].'01';
		$end = $params['year'].'12';

		//品牌总的统计数据
		$db = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$where = sprintf(" and bm_month between '%s' and '%s'",$start,$end);
        $list = $db->get('at_brand_month',["sum(bm_count) as bm_counts,bm_brand"],sprintf(" %s group by bm_brand order by bm_counts desc",$where));
		$brandArr = array_column($list['data'],'bm_brand');
		
		//查pc\cv的统计数据
		$where .= sprintf(" and bm_brand in ('%s') group by bm_brand,bm_modtype",implode("','",$brandArr));
		$templist = $db->get('at_brand_month',["sum(bm_count) as bm_counts,bm_brand,bm_modtype"],$where);
		$arr = [];
		foreach ($templist['data'] as $val) {
			$arr[$val['bm_modtype']][$val['bm_brand']] = $val['bm_counts'];
		}
	
		//查价格
		$YPAdsDb = new BaseDb(mvc::$cfg['DB']['YP_WRITE']);
		$adsRes = $YPAdsDb->get('yp_ads.all_ad_price', ['aap_p_id,aap_keyword, aap_price, app_modtype'],sprintf(" and aap_p_id=%d and aap_site='pjd' order by aap_p_id, app_modtype", 86));
		$price = [];
		foreach ($adsRes['data'] as $item)
		{
			if ($item['aap_price']) {
				$price[$item['aap_keyword']][$item['app_modtype'] ?: 'all'] = (int) $item['aap_price'];
			}
		}
		
		$ComDb = new BaseDb(mvc::$cfg['DB']['COM']);
		$comArr = $ComDb->get('bc_model3 JOIN `bc_brand` ON mod3_brand_id = brand_id',['brand_id', 'brand_name','COUNT(*) as total', 'SUM(CASE WHEN mod3_cc=0 THEN 1 ELSE 0 END) as xny_count'],sprintf(" GROUP BY brand_id"));

		$brandArr = array_column($comArr['data'],null,'brand_name');


		$allArr = [
			['排名','新能源','品牌','浏览量(pv)','乘用车','乘用车价格','商用车','商用车价格','新能源占比']
		];
		foreach ($list['data'] as $key => $val) {
			$brandid =0;
			$xny = 0;
			$xnyrate = '';
			if($brandArr[$val['bm_brand']]){
				$brandid = $brandArr[$val['bm_brand']]['brand_id'];
				$xny = $brandArr[$val['bm_brand']]['xny_count'];
				$xnyrate = (round($xny/$brandArr[$val['bm_brand']]['total'],4)*100).'%';
			}
			
		
			$allArr[] = [
				$key+1,
				$xny>0?'Y':'N',
				$val['bm_brand'],
				$val['bm_counts'],
				$arr['pc'][$val['bm_brand']]??'',
				$price[$brandid]['pc']??'',
				$arr['cv'][$val['bm_brand']]??'',
				$price[$brandid]['cv']??'',
				$xny>0?$xnyrate:'',
			];
		}
		$OthSExcel = new OthSExcel();

		$OthSExcel->writer($allArr, '数据统计排行'.date('Ymd').'.xls');
	}

}