<?php
class pjlShopAction extends baseAction
{
	private $reasonArr = [
			1=>[-1, '请在线支付入驻费，我的邀请码（0188）！'],
			7=>[-1, '请在线支付入驻费，我的邀请码（01006）！'],
			4=>[-1, '请在线支付入驻费，我的邀请码（01054）！'],
			2=>[2, '恭喜您成功入驻跑街令，请移步PC端导入产品目录，地址为：https://pc.paojd.cn'],
			3=>[-1, '营业执照或法人身份证图片不清晰，请重新上传！'],
			5=>[-1, '营业执照、法人身份证图片不匹配，请重新上传！'],
			8=>[-1, '请上传营业执照、法人身份证的原件图片！'],
			10=>[-1, '此营业执照不允许申请商家入驻，请提供汽车相关的营业执照！'],
		];
	/**
	 * @method 店铺管理主页
	 * @author xu
	 * @copyright 2017.01.04
	 */
	function index()
	{
		LibRule::Check('JS01');
		$Params = mvc::$URL_PARAMS;
		if(isset($Params['pu_id'])) LibTpl::Set('pu_id',$Params['pu_id']);
		LibTpl::Set('title','商铺-跑街令');
		LibTpl::Put();
	}


	/**
	 * @店铺列表页
	 * @author xu
	 * @copyright 2017.12.19
	 */
	function lists()
	{
		LibRule::Check('JS01');
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();

		$sres = $PjlBase->get('pl_shop', ['shop_id', 'shop_checkby', 'shop_apply_time'], ' and shop_enter_time = 0 and shop_status=2');
		foreach($sres['data'] as $v)
		{
			$v['shop_checkby'] = json_decode($v['shop_checkby'], true);
			if($v['shop_checkby']['result'] == 1 && $v['shop_checkby']['time'] > 0)
				$PjlBase->set('pl_shop', ['shop_enter_time'=>$v['shop_checkby']['time']], ' and shop_id ='.$v['shop_id']);
			else
				$PjlBase->set('pl_shop', ['shop_enter_time'=>$v['shop_apply_time']], ' and shop_id ='.$v['shop_id']);
		}


		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
			$page = isset($Params['page']) ? $Params['page'] : 1;
		$where = '';

		$endDayArr = [
			1=>'未过期',
			7=>'7天内',
			15=>'15天内',
			30=>'30天内',
			60=>'60天内',
			90=>'90天内',
			-7=>'过期7天',
			-15=>'过期15天',
			-30=>'过期30天',
			-60=>'过期60天',
			-365=>'已过期'
		];
		LibTpl::Set('endDayArr', $endDayArr);

		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if($v == '') continue;
			switch($k)
			{
				case 'status':
					switch ($v)
					{
						case 'stop':
							$where .= " and shop_status =-1";
							break;
						case 'write':
							$where .= " and shop_status = 0";
							break;
						case 'wait':
							$where .= " and shop_status = 1";
							break;
						case 'use':
							$where .= " and shop_status = 2";
						break;
					}
				break;
				case 'shopname':
					$where .= sprintf(' and shop_name like "%%%s%%"', LibFc::Escape($Params['shopname']));
				break;
				case 'etime':
					$v = (int) $v;
					if($v < 0){
						$where .= sprintf(' and shop_vip_etime <= %d', time());
						if($v !== -365) $where .= sprintf(' and shop_vip_etime >= %d', strtotime($v.'day'));
					}else if($v > 0){
						$where .= sprintf(' and shop_vip_etime >= %d', time());
						if($v !== 1) $where .= sprintf(' and shop_vip_etime <= %d', strtotime('+'.$v.'day'));
					}
				break;
				case 'username':
					//根据用户名搜索
					$LibYpApi = new LibYpApi();
					$post = [
						'filed'=>['u_id'],
						'where'=>sprintf(" and (u_name like '%s%%' or u_nickname like '%s%%' or (u_mobile='%s' and u_mobile_check = 'Y'))", LibFc::Escape($Params['username']), LibFc::Escape($Params['username']), LibFc::Escape($Params['username'])),
						'oneRow'=>false
					];
					$userArr = $LibYpApi->Get('user/getUser',[], $post);
					$userArr = array_column($userArr['data'], 'u_id');
					if(!empty($userArr))
						$where .= sprintf(" and shop_pu_id in(%s)", implode(',', $userArr));
					else
						$where .= " and shop_id < 0";
				break;
				case 'hascode':
					//是否存在信用代码
					if($v == 'yes'){
						$where .= " and shop_com_code <> ''";
					}elseif ($v == 'no') {
						$where .= " and shop_com_code = ''";
					}
				break;
				// 添加店铺页单独跳转的逻辑
				case 'pu_id':
					$where .= sprintf(" and shop_pu_id = %d", (int) $v);
				break;
			}
		}
		// var_dump($where);die;
		$pctArr = [];
		if(!empty($Params['data%5Bprovince%5D'])) $pctArr[] = (int) $Params['data%5Bprovince%5D'];
		if(!empty($Params['data%5Bcity%5D'])) $pctArr[] = (int) $Params['data%5Bcity%5D'];
		if(!empty($Params['data%5Bregion%5D'])) $pctArr[] = (int) $Params['data%5Bregion%5D'];
		if(!empty($Params['data%5Bstreet%5D'])) $pctArr[] = (int) $Params['data%5Bstreet%5D'];
		if(!empty($pctArr))
			$where .= sprintf(" and concat(shop_pct_ids, ',') like '%s,%%'", implode(',', $pctArr));

		LibTpl::Set('pctArr', $pctArr);

		$table = 'pl_shop left join pl_shop_addr on sha_shop_id = shop_id and sha_main= 1';
		$res = $PjlBase->get($table, ['count(distinct shop_id) as count'], $where, true);
		$total = $res['data']['count'];
		if ($total > 0)
		{
			$sres = $PjlBase->get($table, ['*'], sprintf("%s order by shop_status desc,shop_enter_time desc, shop_apply_time desc limit %d,%d", $where, ($page-1)*$perPage, $perPage));
			$YpwAddr = new YpwAddr();
			foreach($sres['data'] as $v)
			{
				$pres = $YpwAddr->getAddrByIds($v['shop_pct_ids']);
				$v['shop_pcts'] = implode(' ', $pres['data']);
				$v['shop_license'] = json_decode($v['shop_license'], true);
				$shopArr[$v['shop_id']] = $v;
			}
			if(!empty($shopArr))
			{
				$res = $PjlBase->get('crm_follow',['afl_shop_id', 'max(afl_atime) as afl_atime'], sprintf(" and afl_shop_id in (%s) group by afl_shop_id", implode(',', array_keys($shopArr))));
				foreach($res['data'] as $v)
				{
					$shopArr[$v['afl_shop_id']]['afl_atime'] = $v['afl_atime'];
				}

				$YpwBase = new YpwBase();
				$res = $YpwBase->get('yp_user', ['u_id','u_name', 'u_mobile'], sprintf(" and u_id in (%s)", implode(',', array_column($shopArr, 'shop_pu_id'))));
				LibTpl::Set('userArr', array_column($res['data'], null, 'u_id'));

				$res = $PjlBase->get('pl_product', ['pro_shop_id, count(*) as count'], sprintf(" and pro_shop_id in (%s) group by pro_shop_id", implode(',', array_keys($shopArr))));
				LibTpl::Set('shopItemCount', array_column($res['data'], 'count', 'pro_shop_id'));

				$res = $PjlBase->get('pl_purchase_call', ['puca_by_uid, count(*) as count'], sprintf(" and puca_by_uid in (%s) group by puca_by_uid", implode(',', array_keys($shopArr))));
				LibTpl::Set('callCount', array_column($res['data'], 'count', 'puca_by_uid'));
			}

			if(!empty($shopArr))
			{
			    $shopId = implode(",",array_keys($shopArr));

			    // $tuisong = $PjlBase->get('pl_tuisong',['stu_shop_id'],sprintf(" and stu_shop_id in(%s)",$shopId));
			    // if(!empty($tuisong['data'])){
			    //     $tuisong = array_column($tuisong['data'],'stu_shop_id');
                // }else{
			    //     $tuisong = [];
                // }
			    // LibTpl::Set('tuisong',$tuisong);
				$B2cBase = new B2cBase();
				$res = $B2cBase->get('wx_robot',['wr_id','wr_uid'],sprintf(" AND wr_totype='pjlshop' AND wr_uid in (%s)",$shopId));
				$wxrobot = [];
				if($res['data']){
					$wxrobot =  array_column($res['data'],'wr_id','wr_uid');
				}
				LibTpl::Set('wxrobot',$wxrobot);
                $table = 'tj_pjl_shop_date';
                $field = ["tpsd_shop_id","sum(tpsd_devcode_count) as devcode_count","sum(tpsd_pv_count) as pv_count"];
                $end = date('Ymd',time());
                $start = date('Ymd',strtotime("-3 month"));
                $list = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get($table,$field,sprintf(" and tpsd_shop_id in (%s) and tpsd_date between '%s' and '%s' group by tpsd_shop_id order by pv_count desc limit 200",$shopId,$start,$end));
                if(!empty($list['data'])){
                    $nowShow = array_column($list['data'],null,'tpsd_shop_id');
                }else{
                    $nowShow = [];
                }
                LibTpl::Set('nowShow',$nowShow);
            }
			LibTpl::Set('shopArr', $shopArr);

			// 店铺状况枚举
			LibTpl::Set('shopStatusDes', ['-1'=>'停用','0'=>'资料填写中','1'=>'待审核','2'=>'正常']);

			// 条件下总数
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
		}
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','店铺列表-跑街的');
		LibTpl::Put();
	}

	/**
	 * [shopDisplay 显示店铺的展示]
	 * @Author   Yangxing
	 * @DateTime 2020-06-01T14:04:35+0800
	 * @return   [view]                   [模板]
	 */
	public function shopDisplay()
	{
		//todo 权限
		$Params = mvc::$URL_PARAMS;
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;
		$model = new BaseDb(mvc::$cfg['DB']['API_TJ']);
		$table = 'tj_pjl_shop_date';
		$field = ["tpsd_date","tpsd_devcode_count","tpsd_pv_count"];
		$where = sprintf(" and tpsd_shop_id=%d",$Params['id']);
		LibTpl::Set('Params', $Params);
		// 获取所有提现人员的名称   自动完成
		$count = $model->get($table,['count(*) as total'],$where,true);
		$total = $count['data']['total'];
		if($total > 0)
		{
			$totalPage = ceil($total/$perPage);
			// 判断当前页码是否大于总页数或小于0
			$realPage = ($nowPage>$totalPage)?$totalPage:$nowPage;
			$realPage = ($realPage<=0)?1:$realPage;

			//计算偏移量
			$start = ($realPage-1)*$perPage;
			$where = sprintf(' %s order by tpsd_date desc limit %s,%s',$where,$start,$perPage);
			$list = $model->get($table,$field,$where,false);
			LibTpl::Set('list',$list['data']);
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
		}
		LibTpl::Put();
	}

	/**
	 * @method 店铺详情
	 * @author xu
	 * @copyright 2017.12.19
	 */
	function detail()
	{
		// LibRule::Check('SL03');
		LibRule::Check('JS03');
		// 店铺基本信息
		$Params = mvc::$URL_PARAMS;
		$error = true;
		if(LibFc::Int($Params['id']))
		{
			$LibYpApi = new LibYpApi();

			// 编辑店铺信息
			if($_SERVER['REQUEST_METHOD'] == 'POST')
			{
				// 店铺ID校验
				$data = $_POST['data'];

				$data['shop_pct_ids'] =  implode(',', array_filter([$data['province'],$data['city'],$data['region']],'LibFc::Int'));

				unset($data['province']);
				unset($data['city']);
				unset($data['region']);
				unset($data['street']);

				if(!empty($data['shop_license']))
					$data['shop_license'] =  json_encode($data['shop_license'],JSON_UNESCAPED_UNICODE);

				if(!empty($data['shop_img']))
					$data['shop_img'] =  implode(',', array_filter($data['shop_img']));

				$LibYpApi->Get('pjl/editShopBase', [], ['shopId'=>$data['shop_id'],'data'=>$data]);
			}

			$shopMsg = $LibYpApi->get('pjl/getShopByWhere',['where'=>'and shop_id='.$Params['id'],'oneRow'=>true]);
			$shopMsg = $shopMsg['data'];
			// print_r($shopMsg);

			//营业信息
			if(!empty($shopMsg['shop_license']))
				$shopMsg['shop_license'] = json_decode($shopMsg['shop_license'],true);

			//审核信息
			if(!empty($shopMsg['shop_checkby']))
				$shopMsg['shop_checkby'] = json_decode($shopMsg['shop_checkby'],true);

			//公司门面图
			if(!empty($shopMsg['shop_img']))
				$shopMsg['shop_img'] = array_filter(explode(',', $shopMsg['shop_img']));
			$shopMsg['shop_img'] = array_pad($shopMsg['shop_img'],5,'');
			//账户余额
			$user = $LibYpApi->Get('pjl/getUserByWhere',['field'=>['pu_money'],'where'=>'and pu_uid='.$shopMsg['shop_pu_id'],'oneRow'=>true]);
			if(!empty($user['data']))
			{
				$shopMsg = array_merge($shopMsg, $user['data']);
			}

			LibTpl::Set('data', $shopMsg);

			//店铺附件信息
			// $res = $B2cShop->get('sh_shop_file',['*'],sprintf('and shf_shop_id=%d order by shf_seq asc,shf_id asc',$Params['id']));
			// LibTpl::Set('fujianArr', $res['data']);
		}else
			$error = false;

		LibTpl::Set('error',$error);
		LibTpl::Set('title','店铺详情-跑街的');
		LibTpl::Put();
	}


	/**
	 * @method 附近谁有
	 * @author soul
	 * @copyright 2019/2/19
	 */
	function shopAddr()
	{
		LibRule::Check('JS03');
		$Params = mvc::$URL_PARAMS;
		if(!empty($_POST['shopId']))
		{
			$PjlProduct = new PjlProduct();
			$addrArr = [];
			foreach($_POST['addr'] as $k=>$v)
			{
				$v['sha_pct_ids'] = implode(',', $v['province']);
				$v['lng_lat'] = explode(',', $v['lng_lat']);
				$v['sha_lng'] = (float) $v['lng_lat'][0];
				$v['sha_lat'] = (float) $v['lng_lat'][1];
				unset($v['province']);
				unset($v['lng_lat']);
				$addrArr[$k] = $v;
			}
			$PjlProduct->setShopAddr($_POST['shopId'], $addrArr);
			LibTpl::Success('操作成功');
		}
		$shopId = (int) $Params['shopId'];
		$PjlBase = new PjlBase();
		$res = $PjlBase->get('pl_shop', ['*'], sprintf(" and shop_id = %d", $shopId), true);
		if(empty($res['data'])) LibTpl::Error("此供应商不存在");
		$shopArr = $res['data'];
		$res = $PjlBase->get('pl_shop_addr', ['*'], sprintf(" and sha_shop_id = %d order by sha_main desc, sha_seq asc", $shopId));
		$addArr = $res['data'];
		LibTpl::Set('shopArr',$shopArr);
		LibTpl::Set('addArr', $addArr);
		LibTpl::Set('title', $shopArr['shop_name'].'-附近谁有');
		LibTpl::Put();
	}

	/**
	 * 获取用户的所在区域
	 * @author xu
	 * @copyright 2017.12.25
	 */
	function initAddr()
	{
		$LibYpApi = new LibYpApi();
		// 省份选择器
		$AllProvince = $LibYpApi->Get('pjl/getProvinceCity',['field'=>['pc_id','pc_name'],'where'=>sprintf(' and pc_pid = 0')]);

		LibTpl::Set('AllProvince',$AllProvince['data']);
		// 市选择器
		if(isset($_POST['province']) && LibFc::Int($province = $_POST['province']))
		{
			LibTpl::Set('province',$province);
			$AllCity = $LibYpApi->Get('pjl/getProvinceCity',['field'=>['pc_id','pc_name'],'where'=>sprintf(' and pc_pid ='.$province)]);
			LibTpl::Set('AllCity',$AllCity['data']);
		}
		// 区选择器
		if(isset($_POST['city']) && LibFc::Int($city = $_POST['city']))
		{
			LibTpl::Set('city',$city);
			$AllRegion = $LibYpApi->Get('pjl/getProvinceCity',['field'=>['pc_id','pc_name'],'where'=>sprintf(' and pc_pid ='.$city)]);
			LibTpl::Set('AllRegion',$AllRegion['data']);
			LibTpl::Set('region',$_POST['region']);
		}
		// // 街道选择器
		// if(isset($_POST['region']) && LibFc::Int($region = $_POST['region']))
		// {
		// 	LibTpl::Set('region',$region);
		// 	$AllStreet = $LibYpApi->Get('pjl/getProvinceCity',['field'=>['pc_id','pc_name'],'where'=>sprintf(' and pc_pid ='.$region)]);
		// 	LibTpl::Set('AllStreet',$AllStreet['data']);
		// }
		// if(isset($_POST['street']) && LibFc::Int($street = $_POST['street'])) LibTpl::Set('street',$street);
		$html = LibTpl::Fetch('pjlShop/initAddr.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}

	/**
	 *@method ajax获取地址
	 * @author 卢 2017/6/7
	 */
	function ajaxGetAddr()
	{
		$Params = mvc::$URL_PARAMS;
		$Pid = isset($Params['pid']) ? (int) $Params['pid']: 0;
		$YpwBase = new YpwBase();
		$Res = $YpwBase->get('yp_province_city', ['pc_id as id', 'pc_name as name'], sprintf(" and pc_pid=%d", $Pid));
		LibFc::ajaxJsonEncode($Res);
	}

	/**
	 * 选择地址
	 * @author xu
	 * @copyright 2017.12.25
	 */
	function selectAddr()
	{
		// 校验地址ID
		if(!LibFc::Int($_POST['id'])) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		$LibYpApi = new LibYpApi();
		// 获取下一级地名列表
		$table='us_address';
		$res = $LibYpApi->Get('pjl/getProvinceCity',['field'=>['pc_id','pc_name'],'where'=>sprintf(' and pc_pid = '.$_POST['id'])]);
		$res = $res['data'];
		if(empty($res)) LibFc::ajaxJsonEncode(['status'=>true,'data'=>""]);
		LibTpl::Set('res',$res);
		// 传递类型用户更改下一级的name属性以及标志当前节点所属省市区层级
		$type = LibFc::Escape($_POST['type']);
		if($type=='city') $nextype = 'region';
		if($type=='region') $nextype = 'end';
		if($type=='street') $nextype = 'end';
		LibTpl::Set('nextype',$nextype);
		LibTpl::Set('type',$type);
		// 返回渲染好的html
		$html = LibTpl::Fetch('pjlShop/selectAddr.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}
	/**
	 * @method    提现列表
	 * @author 卢
	 * @copyright 2018-03-13
	 */
	function tiXianList()
	{
		LibRule::Check('JS04');
		$Params = mvc::$URL_PARAMS;
		LibTpl::Set('Params', $Params);
		// 获取所有提现人员的名称   自动完成
		$LibYpApi = new LibYpApi();
		$userData = $LibYpApi->Get('pjl/getMoneyWithdrawals',['field'=>['mow_u_id'] ,'where'=>'group by mow_u_id']);
		$userIdArr = array_column($userData['data'], 'mow_u_id');

		if(!empty($userIdArr))
		{
			$post = [
				'filed'=>['u_id','u_name'],
				'where'=>sprintf(" and u_id in (%s)", implode(',', $userIdArr)),
				'oneRow'=>false
			];
			$res = $LibYpApi->Get('user/getUser',[], $post);
			$userData = array_column($res['data'], 'u_name', 'u_id');

			LibTpl::Set('userName',$userData[$Params['userId']]);
			LibTpl::Set('userArr',$res['data']);
			LibTpl::Set('userData',$userData);

			$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
			$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;

			//取记录

			$where = '';
			if(LibFc::Int($Params['userId']))
			{
				$where.=sprintf(' and mow_u_id=%d',(int)$Params['userId']);
			}

			//状态筛选
			switch ($Params['status'])
			{
				case 'stop':
					$where.=' and mow_status=-1';
					break;
				case 'wait':
					$where.=' and mow_status=0';
					break;
				case 'done':
					$where.=' and mow_status=1';
			}
			//日期筛选
			if(!empty($Params['time'])&&strpos($Params['time'], ' - '))
			{
				$timeArr=explode(' - ', $Params['time']);
				$startTime=strtotime(trim($timeArr[0]));
				$endTime=strtotime(trim($timeArr[1]));
				$where.=sprintf(' and mow_atime>=%d',$startTime);
				$where.=sprintf(' and mow_atime<=%d',$endTime);
			}

			$res = $LibYpApi->Get('pjl/getMoneyWithdrawals',['field'=>['count(1) total'], 'where'=>$where ,'oneRow'=>true]);
			$total = $res['data']['total'];
			$totalPage = ceil($total/$perPage);
			// 判断当前页码是否大于总页数或小于0
			$realPage = ($nowPage>$totalPage)?$totalPage:$nowPage;
			$realPage = ($realPage<=0)?1:$realPage;
			//计算偏移量
			$start = ($realPage-1)*$perPage;
			$where.='  order by mow_id desc';
			$res = $LibYpApi->Get('pjl/getMoneyWithdrawals',['where'=>sprintf('%s limit %s,%s', $where , $start, $perPage)]);
			foreach($res['data'] as $k=>$v)
			{
				$v = array_merge($v, json_decode($v['mow_acc_data'],true));
				if(!empty($v['uac_weixin'])) $v['uac_weixin'] = json_decode($v['uac_weixin'],true);
				$res['data'][$k] = $v;
			}
			LibTpl::Set('list',$res['data']);
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
		}
		$TimeArr = [
			'all'=>'--所有--',
			'stop'=>'已关闭',
			'wait'=>'处理中',
			'done'=>'转账完成',
		];
		LibTpl::Set('TimeArr', $TimeArr);
		LibTpl::Set('title','提现记录-跑街令后台');
		LibTpl::Put();
	}

	function yaoQingTiXianList()
    {
        //TODO 权限控制
        LibRule::Check('JS04');
        $Params = mvc::$URL_PARAMS;
        LibTpl::Set('Params', $Params);
        // 获取所有提现人员的名称   自动完成

        $LibYpApi = new LibYpApi();
        $PjlBase= new PjlBase();

        $userData = $PjlBase->Get('pl_money_withdrawals_share',['mow_u_id'] ,'group by mow_u_id');
        $userIdArr = array_column($userData['data'], 'mow_u_id');

        if(!empty($userIdArr))
        {
            $post = [
                'filed'=>['u_id','u_name'],
                'where'=>sprintf(" and u_id in (%s)", implode(',', $userIdArr)),
                'oneRow'=>false
            ];
            $res = $LibYpApi->Get('user/getUser',[], $post);
            $userData = array_column($res['data'], 'u_name', 'u_id');

            LibTpl::Set('userName',$userData[$Params['userId']]);
            LibTpl::Set('userArr',$res['data']);
            LibTpl::Set('userData',$userData);

            $nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
            $perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;

            //取记录

            $where = '';
            if(LibFc::Int($Params['userId']))
            {
                $where.=sprintf(' and mow_u_id=%d',(int)$Params['userId']);
            }

            //状态筛选
            switch ($Params['status'])
            {
                case 'stop':
                    $where.=' and mow_status = -1';
                    break;
                case 'wait':
                    $where.=' and mow_status = 0';
                    break;
                case 'donw':
                    $where .= ' and mow_status = 1';
                    break;
            }
            //日期筛选
            if(!empty($Params['time'])&&strpos($Params['time'], ' - '))
            {
                $timeArr=explode(' - ', $Params['time']);
                $startTime=strtotime(trim($timeArr[0]));
                $endTime=strtotime(trim($timeArr[1]));
                $where.=sprintf(' and mow_atime>=%d',$startTime);
                $where.=sprintf(' and mow_atime<=%d',$endTime);
            }

            $res = $PjlBase->get('pl_money_withdrawals_share',['count(1) total'], $where,true);
            $total = $res['data']['total'];
            $totalPage = ceil($total/$perPage);
            // 判断当前页码是否大于总页数或小于0
            $realPage = ($nowPage>$totalPage)?$totalPage:$nowPage;
            $realPage = ($realPage<=0)?1:$realPage;
            //计算偏移量
            $start = ($realPage-1)*$perPage;
            $where.='  order by mow_id desc';
            $res = $PjlBase->Get('pl_money_withdrawals_share',['*'],sprintf('%s limit %s,%s', $where , $start, $perPage));
            foreach($res['data'] as $k=>$v)
            {
                $v = array_merge($v, json_decode($v['mow_acc_data'],true));
                if(!empty($v['uac_weixin'])) $v['uac_weixin'] = json_decode($v['uac_weixin'],true);
                $res['data'][$k] = $v;
            }
            LibTpl::Set('list',$res['data']);
            $Page = LibPage::Show($total, $perPage);
            LibTpl::Set('Page', $Page);
        }
        $TimeArr = [
            'all'=>'--所有--',
            'stop'=>'已关闭',
            'wait'=>'处理中',
            'done' => '已完成',
        ];
        LibTpl::Set('TimeArr', $TimeArr);
        LibTpl::Set('title','提现记录-跑街令后台');
        LibTpl::Put();
    }

    function yaoQingCheckTiXian()
    {
        $Params = mvc::$URL_PARAMS;
        $B2cBase = new B2cBase();
        $mowId=$Params['mowid'];
        $PjlBase = new PjlBase();
        $LibYpApi = new LibYpApi();
        if(LibFc::Int($mowId))
        {
            $res = $PjlBase->Get('pl_money_withdrawals_share',['*'],sprintf(' and mow_id=%d',$mowId),true);
            if(count($res['data']))
            {
                $post = [
                    'filed'=>['u_id','u_name'],
                    'where'=>sprintf(" and u_id =%d", $res['data']['mow_u_id']),
                    'oneRow'=>true
                ];
                $user = $LibYpApi->Get('user/getUser',[], $post);
                LibTpl::Set('user',$user['data']);
                $res['data']['jsonArr']=json_decode($res['data']['mow_acc_data'],true);
                if($res['data']['jsonArr']['acc_type']==0)
                    $res['data']['jsonArrWetChat']=json_decode(base64_decode($res['data']['jsonArr']['acc_weixin_info']),true);
                LibTpl::Set('desArr',$res['data']);
                LibTpl::Set('title','审核提现记录-跑街的后台');
                LibTpl::Put();
            }
            else
            {
                LibTpl::Error('记录不存在！');
            }
            exit();
        }
        elseif(!empty($_POST))
        {
            if(empty($_POST['mow_id']))
            {
                LibTpl::Error('提现记录不存在');
            }
            if(!empty($_POST['mow_status']))
            {
                if(empty($_POST['mow_ramark']))
                {
                    LibTpl::Error('备注不能为空');
                }
                $dataArr=[
                    'mow_id' => $_POST['mow_id'],
                    'mow_check_uid' => mvc::$cfg['LOGUSER']['uid'],
                    'mow_check_remark'=>LibFc::Escape($_POST['mow_ramark']),
                    'mow_check_uname'=>mvc::$cfg['LOGUSER']['urname'],
                ];
                $res = $LibYpApi->Get('pjl/closeWithdrawalsShareMoney',[],$dataArr);
            }
            LibFc::Go(mvc::$cfg['ADMIN_URI'].'pjlShop/yaoQingCheckTiXian?mowid='.$_POST['mow_id']);
        }else{
            LibTpl::Error('记录不存在！');
        }
    }


	/**
	 * @method    提现详情
	 * @author 卢
	 * @copyright 2018-03-13
	 */
	function tiXianDes()
	{
		LibRule::Check('JS02');
		$Params = mvc::$URL_PARAMS;
		$LibYpApi = new LibYpApi();
		if(LibFc::Int($Params['mowId']))
		{
			$res=$LibYpApi->Get('pjl/getMoneyWithdrawals',['where'=>sprintf(' and mow_id=%d',$Params['mowId']),'oneRow'=>true]);
			if(!empty($res['data']))
			{
				$post = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id =%d", $res['data']['mow_u_id']),
					'oneRow'=>true
				];
				$user = $LibYpApi->Get('user/getUser',[], $post);

				$res['data']['userName'] = $user['data']['u_name'];
				$res['data'] = array_merge($res['data'], json_decode($res['data']['mow_acc_data'], true));
			}
			LibTpl::Set('desArr',$res['data']);
		}
		else
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'记录不存在！']);
		}
		$data=LibTpl::Fetch();
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$data]);
	}
	/**
	 * @method    开店申请列表
	 * @author 卢
	 * @copyright 2018-04-10
	 */
	function openShopApply()
	{
		LibRule::Check('JS02');

		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		$nowPage = isset($Params['page']) && $Params['page'] > 0 ? (int) $Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 10;
		$where='';
		$LibYpApi = new LibYpApi();
		if(!empty($Params['status']))
		{
			$where.=sprintf(' and shop_status=%d',$Params['status']);
		}
		if(!empty($Params['shopName']))
		{
			$where.=sprintf(" and shop_name like '%%%s%%'",LibFc::Escape($Params['shopName']));
		}
		if(!empty($Params['etime'])){
			$etime = (int) $Params['etime'];
			if($etime < 0){
				$where .= sprintf(' and shop_vip_etime <= %d', time());
				if($etime !== -365) $where .= sprintf(' and shop_vip_etime >= %d', strtotime($etime.'day'));
			}else if($etime > 0){
				$where .= sprintf(' and shop_vip_etime >= %d', time());
				if($etime !== 1) $where .= sprintf(' and shop_vip_etime <= %d', strtotime('+'.$etime.'day'));
			}
		}
		$apiWhere='';
		if(!empty($Params['user']))
		{
			$apiWhere.=sprintf(" and u_name = '%s'", LibFc::Escape($Params['user']));
		}
		if(LibFc::Int($Params['mobile']))
		{
			$apiWhere.=sprintf(" and u_mobile = '%s'", LibFc::Escape($Params['mobile']));

		}
		if(!empty($apiWhere))
		{
			$post = [
				'filed'=>['u_id'],
				'where'=>$apiWhere,
				'oneRow'=>false
			];
			$res = $LibYpApi->Get('user/getUser',[], $post);
			if(!empty($res['data']))
			{
				$where.=sprintf(' and shop_pu_id in(%s)',implode(',',array_column($res['data'], 'u_id')));
			}
			else
			{
				$where.=' and shop_id <0';
			}
		}
		if(!empty($Params['time']))
		{
			if(strpos($Params['time'], ' - ')!==false)
			{
				$timeArr=explode(' - ', $Params['time']);
				$where.=sprintf(' and shop_apply_time>=%d and shop_apply_time<=%d',strtotime($timeArr[0]),strtotime($timeArr[1]));
			}
			else{
				$where.=' and shop_id <0';
			}
		}
		//计算总数

		$res = $PjlBase->get('pl_shop',['count(*) as count'], $where, true);
		$total=$res['data']['count'];
		if ($total > 0)
		{
			$where .= sprintf('  order by shop_apply_time desc limit %s,%s',($nowPage-1)*$perPage,$perPage);
			$res = $PjlBase->get('pl_shop',['*'], $where);

			$shopArr = array_column($res['data'], null, 'shop_id');
			if(!empty($shopArr))
			{
				foreach ($shopArr as $k => $v)
				{
					$address = $LibYpApi->Get('pjl/getAddrByIds',['ids'=>$v['shop_pct_ids']]);
					$shopArr[$k]['shop_address']=implode('',$address['data']).$v['shop_address'];
					$shopArr[$k]['shop_license'] = json_decode($v['shop_license'], true);
					$shopArr[$k]['shop_checkby'] = json_decode($v['shop_checkby'], true);
				}
				$uidArr=array_column($shopArr, 'shop_pu_id');
				if(!empty($uidArr))
				{
					$post = [
						'filed'=>['u_id','u_name', 'u_mobile'],
						'where'=>sprintf(" and u_id in (%s) ", implode(',', $uidArr)),
						'oneRow'=>false
					];
					$userArr = $LibYpApi->Get('user/getUser',[], $post);
					$userArr=array_column($userArr['data'],null, 'u_id');
					LibTpl::Set('userArr', $userArr);
				}

				$res = $PjlBase->get('pl_shop_vip',['*'], sprintf(" and svip_shop_id in (%s) order by svip_etime desc", implode(',', array_keys($shopArr))));
				foreach($res['data'] as $v)
				{
					$shopArr[$v['svip_shop_id']]['vips'][] = $v;
				}
			}
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
			LibTpl::Set('data', $shopArr);

		}
		$endDayArr = [
			1=>'未过期',
			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('reasonArr', $this->reasonArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','开店申请-跑街令后台');
		LibTpl::Put();
	}
	/**
	 * @method    开店审核
	 * @author 卢
	 * @copyright 2018-04-10
	 */
	function changeApply()
	{
		LibRule::Check('JS02');
		$res=['status'=>false,'data'=>'参数错误'];
		if(LibFc::Int($_POST['shop']))
		{	
			if($_POST['status'])
			{
				switch ($_POST['status'])
				{
					case '2':
						$dataArr['shop_status']=2;
						break;
					case '0':
						$dataArr['shop_status']=0;
						break;
					case '1':
						$dataArr['shop_status']=1;
						break;
					case '-1':
						$dataArr['shop_status']=-1;
						break;
				}
				$LibYpApi = new LibYpApi();
				
				$shopres = $LibYpApi->Get('pjl/getShopByWhere',['where'=>sprintf(' and shop_id=%d',$_POST['shop']),'oneRow'=>true]);
				if(isset($dataArr['shop_status'])&&$shopres['data']['shop_status']!=$dataArr['shop_status'])
				{
					$checkby = [
						'name' => $_SESSION['admin_username'],
						'result' => $dataArr['shop_status']==2 ? 1 : 0,
						'remark' => $this->reasonArr[$_POST['reason_key']]?$this->reasonArr[$_POST['reason_key']][1]:''
					];
					$res = $LibYpApi->Get('pjl/checkShopOpen',[],['shopId'=>$_POST['shop'], 'status'=>$dataArr['shop_status'], 'check'=>$checkby]);
					if(!empty($res['data']))
					{
						$PjlProduct = new PjlProduct();
						$PjlProduct->initShopAddr($_POST['shop']);
						$sendStyle=[
							'-1'=>'pjlShopError',
							'2'=>'pjlShopOk'
						];
		
						if(in_array($dataArr['shop_status'], array_keys($sendStyle)))
						{
							$post = [
								'filed'=>['u_id','u_mobile'],
								'where'=>sprintf(" and u_id =%d ", $_POST['shop']),
								'oneRow'=>true
							];
							$userArr = $LibYpApi->Get('user/getUser',[], $post);
							if(empty($userArr['data']['u_mobile']))
								LibFc::ajaxJsonEncode(['status'=>false,'data'=>'用户手机号码为空,短信发送失败']);
							$dataArr = [
								'sms_type'=>'紧急',
								'sms_from'=>'PJL',
								'sms_style'=>$sendStyle[$dataArr['shop_status']],
								'sms_to_mobile'=>$userArr['data']['u_mobile'],//负责人电话
								'sms_text'=>'{}'
							];
							$LibYpApi->Get('sms/send',[], $dataArr);
						}
					}
				}
			}
			
			$shopData = [];
	
			$shopData['shop_com_name'] = $_POST['shop_com_name']?:'';
			$shopData['shop_com_code'] = $_POST['shop_com_code']?:'';
			
			if(!empty($shopData)){
				$PjlBase = new PjlBase();
				$where = sprintf(" and shop_id = %d",LibFc::Int($_POST['shop']));
				$res = $PjlBase->set('pl_shop',$shopData,$where);
			}
			
		}
		LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method    开店申请详情
	 * @author 卢
	 * @copyright 2018-04-10
	 */
	function applyShopDetail()
	{
		LibRule::Check('JS02');
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['shopId']))
		{
			$LibYpApi = new LibYpApi();
			$res=$LibYpApi->Get('pjl/getShopByWhere',['where'=>sprintf(' and shop_id=%d',$Params['shopId']),'oneRow'=>true]);
			if(!empty($res['data']))
			{
				$addrArr = $LibYpApi->Get('pjl/getAddrByIds',['ids'=>$res['data']['shop_pct_ids']]);
				$res['data']['address']=!empty($addrArr['data'])?implode('',$addrArr['data']):'';
				$res['data']['shop_license'] = json_decode($res['data']['shop_license'], true);
				$res['data']['shop_checkby'] = json_decode($res['data']['shop_checkby'], true);

				if (!empty($res['data']['shop_img']))
				{
					$res['data']['shop_img'] = array_filter(explode(',', $res['data']['shop_img']));
				}
				$post = [
					'filed'=>['u_id','u_name','u_mobile'],
					'where'=>sprintf(" and u_id  =%d ", $res['data']['shop_pu_id']),
					'oneRow'=>true
				];
				$userArr = $LibYpApi->Get('user/getUser',[], $post);
				LibTpl::Set('userArr',$userArr['data']);
			}
		}
		LibTpl::Set('data',$res['data']);
		LibTpl::Set('title','开店申请详情-跑街令后台');
		LibTpl::Put();
	}
	/**
	 * @method    审核提现
	 * @author 卢
	 * @copyright 2018-11-02
	 */
	function checkTiXian()
	{
		$Params = mvc::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$mowId=$Params['mowid'];
		$LibYpApi = new LibYpApi();
		if(LibFc::Int($mowId))
		{
			$res=$LibYpApi->Get('pjl/getMoneyWithdrawals',['where'=>sprintf(' and mow_id=%d',$mowId),'oneRow'=>true]);
			if(count($res['data']))
			{
				$post = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id =%d", $res['data']['mow_u_id']),
					'oneRow'=>true
				];
				$user = $LibYpApi->Get('user/getUser',[], $post);
				LibTpl::Set('user',$user['data']);
				//获取费率
				$rate=$LibYpApi->Get('pjl/getMoneyRate');
				LibTpl::Set('rate',$rate['data']['withdrawRate']);
				$res['data']['jsonArr']=json_decode($res['data']['mow_acc_data'],true);
				if($res['data']['jsonArr']['acc_type']==0)
					$res['data']['jsonArrWetChat']=json_decode(base64_decode($res['data']['jsonArr']['acc_weixin_info']),true);
				LibTpl::Set('desArr',$res['data']);
				LibTpl::Set('title','审核提现记录-跑街的后台');
				LibTpl::Put();
			}
			else
			{
				LibTpl::Error('记录不存在！');
			}
			exit();
		}
		elseif(!empty($_POST))
		{
			if(empty($_POST['mow_id']))
			{
				LibTpl::Error('提现记录不存在');
			}
			if(!empty($_POST['mow_status']))
			{
				if(empty($_POST['mow_ramark']))
				{
					LibTpl::Error('备注不能为空');
				}
				$dataArr=[
					'mow_ok_time'=>(!empty($_POST['mow_ok_time'])?strtotime($_POST['mow_ok_time']):time()),
					'mow_check_remark'=>LibFc::Escape($_POST['mow_ramark']),
					'mow_status'=>(int)$_POST['mow_status'],
					'mow_u_id'=>(int)$_POST['mow_u_id'],
					'mow_id'=>$_POST['mow_id'],
					'mow_check_uid'=>mvc::$cfg['LOGUSER']['uid'],
					'mow_check_uname'=>mvc::$cfg['LOGUSER']['urname'],
				];
				$res = $LibYpApi->Get('pjl/checkWithdraw',[],$dataArr);
			}
			LibFc::Go(mvc::$cfg['ADMIN_URI'].'pjlShop/checkTiXian?mowid='.$_POST['mow_id']);
		}else{
			LibTpl::Error('记录不存在！');
		}
	}
	/**
	 * @method    发送通知短信
	 * @return    [type]        [description]
	 * @author lu
	 * @copyright 2018-12-20
	 */
	function sendNotifyMsg()
	{
		if(!LibFc::Int($_POST['uid']))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'用户id不正确']);
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('pjl/getShopByWhere',['field'=>['shop_status','shop_id'],'where'=>sprintf(' and shop_pu_id=%d',$_POST['uid']),'oneRow'=>true]);
		if(empty($res['data']))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'店铺不存在']);
		$sendStyle=[
			'-1'=>'pjlShopError',
			'2'=>'pjlShopOk'
		];
		$status=$res['data']['shop_status'];
		if(!in_array($status, array_keys($sendStyle)))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'当前店铺状态不需要发送短信通知']);
		$post = [
			'filed'=>['u_id','u_mobile'],
			'where'=>sprintf(" and u_id =%d ", $_POST['uid']),
			'oneRow'=>true
		];
		$userArr = $LibYpApi->Get('user/getUser',[], $post);
		if(empty($userArr['data']['u_mobile']))
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'用户手机号码为空']);
		$dataArr = [
			'sms_type'=>'紧急',
			'sms_from'=>'PJL',
			'sms_style'=>$sendStyle[$status],
			'sms_to_mobile'=>$userArr['data']['u_mobile'],//负责人电话
			'sms_text'=>'{}'
		];
		$res=$LibYpApi->Get('sms/send',[], $dataArr);
		LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method    批量导入产品
	 * @return    [type]      [description]
	 * @author lu
	 * @copyright 2018-12-27
	 */
	function pjlBatchAct()
	{
		LibRule::Check('PJ00');
		$Params = MVC::$URL_PARAMS;
		$shopId = (int) $Params['shopId'];
		$PjlBase=new PjlBase();
		$res = $PjlBase->get('pl_shop', ['shop_id', 'shop_name'], sprintf(" and shop_id=%d", $shopId), true);
		if(empty($res['data'])) LibTpl::Error('店铺不存在');
		$shopData = $res['data'];
		LibTpl::set('shopData', $shopData);
		if(!empty($_POST))
		{
			$dataArr=[];
			if(!empty($_FILES['excel']['tmp_name']))
			{
				$OthExcel = new OthExcel();
				$headArr=['pro_display','pro_name','pro_price','pro_quality','pro_quality_des','pro_model'];
				$headMap=['号码'=>'pro_display','名称'=>'pro_name','价格'=>'pro_price','品质'=>'pro_quality','品质备注'=>'pro_quality_des','适用车型'=>'pro_model'];
				$res = $OthExcel->read($_FILES['excel']['tmp_name'], 0, array_keys($headMap), 1, false);
				if(!empty($res['data']))
				{
					$tproArr = $res['data'];
					foreach($tproArr as $tk=>$tv)
					{
						$temp=[
							'pro_shop_id'=>$shopData['shop_id'],
							'pro_status'=>1,
							'pro_ischeck'=>1,
							'pro_etime'=>time(),
							$headMap['号码']=>$tv['号码'],
							'pro_format'=>LibFc::FormatNum($tv['号码']),
							$headMap['名称']=>$tv['名称'],
							$headMap['价格']=>sprintf("%.2f", $tv['价格']),
							$headMap['品质']=>$tv['品质'],
							$headMap['品质备注']=>$tv['品质备注'],
							$headMap['适用车型']=>LibFc::msubstr($tv['适用车型'], 0, 512)
						];

						if(empty($temp['pro_format'])) continue;

						if(empty($temp['pro_name']))
						{
							LibTpl::Error("第{$tk}行的配件名称不能为空");
							exit;
						}
						if(empty($temp['pro_quality']))
						{
							LibTpl::Error("第{$tk}行的配件品质不能为空");
							exit;
						}
						$dataArr[]=$temp;
					}
				}
			}
			if(!empty($dataArr))
			{
				$numArr=array_column($dataArr, 'pro_format');
				$where=sprintf(" and pro_shop_id=%d and pro_format in('%s')",$shopData['shop_id'],implode("','",$numArr));
				$res=$PjlBase->get('pl_product',['pro_format','pro_id'],$where);
				$existArr=array_column($res['data'],'pro_id', 'pro_format');
				$existIdArr=array_column($res['data'],'pro_format');
				foreach ($dataArr as $k=> $v)
				{
					if(in_array($v['pro_format'], $existIdArr))
					{
						//存在的修改
						$proId=$existArr[$v['pro_format']];
						$PjlBase->set('pl_product',$v,sprintf(' and pro_shop_id=%d and pro_id=%d',$shopData['shop_id'],$proId));
					}else{
						$v['pro_atime']=$v['pro_etime'];
						$PjlBase->add('pl_product',$v);
					}
				}
				LibTpl::Success("导入成功",mvc::$cfg['ADMIN_URI'].'pjlShop/pjlBatchAct?shopId='.$shopData['shop_id']);
			}
			LibTpl::Error("数据为空，导入失败");
		}
		LibTpl::Set('title', $shopData['shop_name'].'-产品批量管理-跑街令');
		LibTpl::Put();
	}
	function clearPro()
	{
		LibRule::Check('PJ00');
		$Params = MVC::$URL_PARAMS;
		if(!LibFc::Int($Params['shopId']))
		{
			LibFc::ajaxJsonEncode(['stauts'=>false,'data'=>'清空失败']);
		}
		$PjlBase=new PjlBase();
		$res=$PjlBase->del('pl_product',sprintf(' and pro_shop_id=%d',$Params['shopId']));
		LibFc::ajaxJsonEncode($res);
	}
	function shopProIndex()
	{
		LibRule::Check('PJ00');
		LibTpl::Set('title','配件列表-跑街令');
		LibTpl::Put();
	}
	function proLists()
	{
		LibRule::Check('PJ00');
		$Params = mvc::$URL_PARAMS;
		$columnArr=[
			'pro_id' => '配件ID',
			'pro_status' => '状态',
			'check_status' => '审核',
			'pro_name'=>'名称',
			'number'=>'号码',
			'quality'=>'品质',
			'proPrice'=>'价格',
			'pro_model'=>'车型',
			'shopUser'=>'店铺',
			'time'=>'时间',
		];

		$columnArrWidth=[
			'pro_id'=>80,
			'pro_status'=>60,
			'check_status'=>60,
			'pro_name'=>150,
			'pro_model'=>200,
			'number'=>150,
			'quality'=>80,
			'proPrice'=>80,
			'shopUser'=>200,
			'time'=>0,
		];
		LibTpl::Set('columnArr',$columnArr);


		$columnShow=[];
		// print_r($_SESSION['pjlShowProColumns']);
		foreach ($columnArr as $k => $v) {
			$columnShow[]=$k;
		}
		LibTpl::Set('columnShow',$columnShow);
		// print_r($_SESSION['pjlShowProColumns']);
		// 显示宽度控制
		LibTpl::Set('columnArrWidth',$columnArrWidth);

		// table宽度
		$width = 0;
		if(isset($_SESSION['pjlShowProColumns'])){
            foreach ($_SESSION['pjlShowProColumns'] as $key => $value) {
                $width+=$columnArrWidth[$value];
            }
        }

		LibTpl::Set('width',($width).'px');
		// print_r($Params);
		$page=!empty($Params['page'])?(int)$Params['page']:1;
		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

		$PjlProduct=new PjlProduct();
		$where='';
		if(isset($Params['status'])&&$Params['status']!='all')
		{
			$where.=sprintf(' and pro_status=%d',(int)$Params['status']);
		}
		if(LibFc::Int($Params['pro_id']))
		{
			$where.=sprintf(' and pro_id=%d',(int)$Params['pro_id']);
		}
		if(!empty($Params['pro_name']))
		{
			$where.=sprintf(" and pro_name like '%%%s%%'",LibFc::FormatNum($Params['pro_name']));
		}
		if(!empty($Params['number']))
		{
			$where.=sprintf(" and pro_format='%s'",LibFc::FormatNum($Params['number']));
		}
		if(isset($Params['check_status'])&&$Params['check_status']!='all')
		{
			$where.=sprintf(' and pro_ischeck=%d',(int)$Params['check_status']);
		}
		if(!empty($Params['quality']))
		{
			$where.=sprintf(" and pro_quality='%s'",LibFc::Escape($Params['quality']));
		}
		if(LibFc::Int($Params['shopId']))
		{
			$where.=sprintf(' and pro_shop_id=%d',(int)$Params['shopId']);
		}
		$where.=(int)strtotime($Params['addTime'])?sprintf(' and pro_etime >=%d',(int)strtotime($Params['addTime'])):'';
		$where.=(int)strtotime($Params['endTime'])?sprintf(' and pro_etime <=%d',(int)strtotime($Params['endTime'])):'';
		$orderby='';
		if(!empty($Params['orderBy']))
		{
			switch ($Params['orderBy']) {
				case 'edesc':
					$orderby='pro_etime desc';
					break;
				case 'easc':
					$orderby='pro_etime asc';
					break;
				case 'ndesc':
					$orderby='pro_format desc';
					break;
				case 'nasc':
					$orderby='pro_format asc';
					break;
				case 'pasc':
					$orderby='pro_price asc';
					break;
				case 'pdesc':
					$orderby='pro_price desc';
					break;
			}
		}
		$res=$PjlProduct->get('pl_product left join pl_shop on shop_id=pro_shop_id',['count(1) count'],$where,true);
		$data['total']=$res['data']['count'];
		if($data['total']>0)
		{
			$res=$PjlProduct->getShopProlists($page,$perPage,$orderby,$where);
			LibTpl::Set('lists', $res['data']);
			if(!empty($res['data']))
			{
				$shopIdArr=array_column($res['data'], 'shop_id');
				$res=$PjlProduct->get('pl_shop',['shop_id','shop_pu_id','shop_name'],sprintf(' and shop_id in(%s)',implode(',',$shopIdArr)));
				$shopArr=array_column($res['data'],null, 'shop_id');
				$userIdArr=array_column($res['data'], 'shop_pu_id');
				LibTpl::Set('shopArr',$shopArr);
				$LibYpApi = new LibYpApi();
				$post = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id in(%s)",implode(',',$userIdArr)),
					'oneRow'=>false
				];
				$uidArr = $LibYpApi->Get('user/getUser',[], $post);
				$userArr=array_column($uidArr['data'], null,'u_id');
				LibTpl::Set('userArr',$userArr);
			}
		}
		$Page = LibPage::Show($data['total'], $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title','配件列表-跑街令');
		LibTpl::Put();
	}
	function proSearch()
	{
		$paramsArr=[
			'id'=>'showColumn',
			'type'=>'checkbox',
			'show_name'=>'name',
			'width'=>80,
			'data_key'=>'id',
			'data_value'=>['key','id'],
			'data_check'=>['pro_id','pro_name','number'],
			'callback'=>'putIntoCheckColumn',
			'unCheckCallback'=>'putIntoCheckColumn',
		];
		$data=[
			['name'=>'配件ID','id'=>'pro_id'],
			['name'=>'配件状态','id'=>'pro_status'],
			['name'=>'审核状态','id'=>'check_status'],
			['name'=>'配件名称','id'=>'pro_name'],
			['name'=>'适用车型','id'=>'pro_model'],
			['name'=>'号码','id'=>'number'],
			['name'=>'品质','id'=>'quality'],
			['name'=>'价格','id'=>'proPrice'],
			['name'=>'店铺信息','id'=>'shopUser'],
			['name'=>'时间','id'=>'time'],
		];
		if(isset($_SESSION['pjlShowProColumns']))
		{
			foreach ($data as $k=> $v)
			{
				if(in_array($v['id'], $_SESSION['pjlShowProColumns']))
				{
					$data[$k]['check']=true;
				}
			}
		}

		$PjlProduct=new PjlProduct();
		$res=$PjlProduct->get('pl_shop',['shop_id','shop_name']);
		LibTpl::Set('shopArr',$res['data']);
		LibTpl::Set('data',$data);
		LibTpl::Set('params',$paramsArr);
		LibTpl::Set('title','配件搜索-跑街令');
		LibTpl::Put();
	}
	/**
	 * @method    选中
	 * @return    [type]       [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function ajaxProCheck()
	{
		if(!empty($_POST))
		{
			$orderId=trim($_POST['ChkIds'],',');
			$notCheck=trim($_POST['NotChkIds'],',');
			if(isset($_SESSION['pjlChkShopProIds']))
			{
				$_SESSION['pjlChkShopProIds']=array_unique(array_merge(explode(',', $orderId),$_SESSION['pjlChkShopProIds']));
				foreach ($_SESSION['pjlChkShopProIds'] as $k => $v)
				{
					if(in_array($v, explode(',', $notCheck)))
					{
						unset($_SESSION['pjlChkShopProIds'][$k]);
					}
				}
			}
			else
			{
				$_SESSION['pjlChkShopProIds']=explode(',', $orderId);
			}
			$_SESSION['pjlChkShopProIds']=array_filter($_SESSION['pjlChkShopProIds']);
			$data = array('status'=>true,'data'=>array('check'=>$_SESSION['pjlChkShopProIds']));
			LibFc::ajaxJsonEncode($data);
		}
	}
	/**
	 * @method    更新选中
	 * @return    [type]      [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function updateCheck()
	{
		if(!is_array($_POST['checkOrderId']))
		{
			$orderId=trim($_POST['checkOrderId'],',');
			$orderId=[$orderId];
		}
		else
		{
			$orderId=$_POST['checkOrderId'];
		}
		if(isset($_SESSION['pjlChkShopProIds']))
		{
			foreach ($_SESSION['pjlChkShopProIds'] as $k => $v)
			{
				if(in_array($v, $orderId))
				{
					unset($_SESSION['pjlChkShopProIds'][$k]);
				}
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>true,'data'=>true));
	}
	function clearAll()
	{
		unset($_SESSION['pjlChkShopProIds']);
		LibFc::ajaxJsonEncode(array('status'=>true,'data'=>true));
	}
	/**
	 * @method    上架配件
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function publishPro()
	{
		if(!empty($_POST['proId']))
		{
			$proArr=array_filter($_POST['proId'],'LibFc::Int');
			if(!empty($proArr))
			{
				$PjlProduct=new PjlProduct();
				$res=$PjlProduct->set('pl_product',['pro_status'=>1],sprintf(' and pro_id in(%s)',implode(',',$proArr)));
				LibFc::ajaxJsonEncode($res);
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'配件上架失败'));
	}
	/**
	 * @method    下架配件
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function bandPro()
	{
		if(!empty($_POST['data']))
		{
			parse_str($_POST['data'],$data);
			if(!empty($data))
			{
				$proArr=array_filter($data['proId'],'LibFc::Int');
				if(!empty($proArr))
				{
					$PjlProduct=new PjlProduct();
					$res=$PjlProduct->set('pl_product',['pro_status'=>0],sprintf(' and pro_id in(%s)',implode(',',$proArr)));
					LibFc::ajaxJsonEncode($res);
				}
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'配件下架失败'));
	}
	/**
	 * @method    删除配件
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function delPro()
	{
		if(!empty($_POST['proId']))
		{
			$proArr=array_filter($_POST['proId'],'LibFc::Int');
			if(!empty($proArr))
			{
				$PjlProduct=new PjlProduct();
				$res=$PjlProduct->del('pl_product',sprintf(' and pro_id in(%s)',implode(',',$proArr)));
				if(!empty($_SESSION['pjlChkShopProIds']))
				{
					foreach ($_SESSION['pjlChkShopProIds'] as $k => $v)
					{
						if(in_array($v, $proArr))
						{
							unset($_SESSION['pjlChkShopProIds'][$k]);
						}
					}
				}
				LibFc::ajaxJsonEncode($res);
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'配件删除失败'));
	}
	/**
	 * @method    审核配件
	 * @return    [type]     [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function checkPro()
	{
		if(!empty($_POST)&&!empty($_POST['data'])&&isset($_POST['status'])&&!empty($_POST['remark']))
		{
			parse_str($_POST['data'],$proArr);
			if(!empty($proArr))
			{
				$proArr=is_array($proArr['proId'])?array_filter($proArr['proId'],'LibFc::Int'):[(int)$proArr['proId']];
				if(!empty($proArr))
				{
					$where=sprintf(' and pro_id in(%s)',implode(',',$proArr));
					$dataArr=[
						'pro_ischeck'=>((int)$_POST['status']),
						'pro_check'=>json_encode([
							'uid'=>mvc::$cfg['LOGUSER']['uid'],
							'uname'=>mvc::$cfg['LOGUSER']['urname'],
							'remark'=>$_POST['remark'],
							'time'=>time()
						],JSON_UNESCAPED_UNICODE)
					];
					$PjlProduct=new PjlProduct();
					$res=$PjlProduct->set('pl_product',$dataArr,$where);
					LibFc::ajaxJsonEncode($res);
				}
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'配件审核失败'));
	}
	/**
	 * @method    配件详细
	 * @return    [type]      [description]
	 * @author lu
	 * @copyright 2018-12-28
	 */
	function shopProInfo()
	{
		$Params = mvc::$URL_PARAMS;
		if(!LibFc::Int($Params['proId']))
			LibTpl::Error('配件不存在');
		$PjlProduct=new PjlProduct();
		$res=$PjlProduct->getShopProInfo($Params['proId']);
		$lists=$res['data'];
		$lists['checkInfo']=json_decode($lists['pro_check'],true);
		LibTpl::Set('lists',$lists);
		if(!empty($lists))
		{
			$shopId=$lists['shop_id'];
			$res=$PjlProduct->get('pl_shop',['shop_id','shop_pu_id','shop_name','shop_logo','shop_style','shop_status'],sprintf(' and shop_id =%d',$shopId),true);
			$res['data']['shop_logo']=!empty($res['data']['shop_logo'])?mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=shop&f='.$res['data']['shop_logo'].mvc::$cfg['FILE_CENTER']['pjl']['get_uri']:mvc::$cfg['ADMIN_URL'].'static/images/no_img.gif';
			$shopArr=$res['data'];

			$userId=$res['data']['shop_pu_id'];
			LibTpl::Set('shopArr',$shopArr);
			$LibYpApi = new LibYpApi();
			$post = [
				'filed'=>['u_id','u_name'],
				'where'=>sprintf(" and u_id =%d",$userId),
				'oneRow'=>true
			];
			$uidArr = $LibYpApi->Get('user/getUser',[], $post);
			LibTpl::Set('userArr',$uidArr['data']);
		}
		LibTpl::Set('title','配件详情-跑街令');
		LibTpl::Put();
	}

	function tongJi()
	{
		$Params = mvc::$URL_PARAMS;
		$menu=[
			'Android'=>'PJLAND',
			'IOS'=>'PJLIOS',
			'PC'=>'PJLPC',
			'H5'=>'PJLH5',
			'软件'=>'PJLSOFT'
		];
		LibTpl::Set('menu',$menu);
		$PjlBase= new PjlBase();
		$from=!empty($Params['from'])?$Params['from']:'PJLAND';
		$Params['from']=$from;
		LibTpl::Set('Params',$Params);
		$dateArr=[
			'今天'=>'now',
			'昨天'=>'yes',
			'7天'=>'',
			'14天'=>'half',
			'30天'=>'month'
		];
		LibTpl::Set('dateArr',$dateArr);
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page=!empty($Params['page'])?(int)$Params['page']:1;
		$where=sprintf(" and da_from='%s'",$from);
		if(empty($Params['range']))
		{
			// $endTime=date('Ymd');
			$endTime='';
			switch ($Params['limit'])
			{
				case 'now':
					$date=date('Ymd',time());
					$endTime='';
					break;
				case 'yes':
					$date=date('Ymd',strtotime('-1 day'));
					break;
				case 'half':
					$date=date('Ymd',strtotime('-13 days'));
					break;
				case 'month':
					$date=date('Ymd',strtotime('-29 days'));
					break;
				default:
					$date=date('Ymd',strtotime('-6 days',time()));//默认7天
					break;
			}
			$where.=sprintf(" and da_date>=%d",$date);
			$where.=!empty($endTime)?sprintf(' and da_date<%d',$endTime):'';
		}else
		{
			$date=explode(' ~ ',$Params['range']);
			$where.=sprintf(" and da_date>=%d and da_date<=%d",date('Ymd',strtotime($date[0])),date('Ymd',strtotime($date[1])));
		}
		$res=$PjlBase->get('tj_date',['count(1) count'],$where,true);
		$total=$res['data']['count'];
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page',$Page);
		if($total>0)
		{
			$where.=sprintf(' order by da_date desc limit %d,%d',($page-1)*$perPage,$perPage);
			$res=$PjlBase->get('tj_date',['*'],$where);
			$lists=$res['data'];
			LibTpl::Set('lists',$lists);
		}
		LibTpl::Set('title','统计-跑街令');
		LibTpl::Put();
	}
	function checkVinError()
	{
		LibRule::Check('CA03');
		$Params = mvc::$URL_PARAMS;
		$statusArr=[
			-1=>'无效',
			0=>'待核对',
			1=>'有效'
		];
		LibTpl::Set('statusArr',$statusArr);
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page=!empty($Params['page'])?(int)$Params['page']:1;
		$PjlBase= new PjlBase();
		$where = '';
		if(!isset($Params['status'])) $Params['status'] = '0';
		if(!empty($Params['vin']))
		{
			$where.=sprintf(" and ve_vin LIKE '%s'",LibFc::Escape($Params['vin']));
		}
		if(isset($Params['status']) && $Params['status'] !== '')
		{
			$where.=sprintf(' and ve_status=%d',(int)$Params['status']);
		}

		$res=$PjlBase->get('pl_vin_error',['count(1) count'],$where,true);
		$total=$res['data']['count'];
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page',$Page);
		if($total>0)
		{
			$where.=sprintf(' order by ve_atime desc limit %s,%s',($page-1)*$perPage,$perPage);
			$res=$PjlBase->get('pl_vin_error',['*'],$where);
			$userId=array_column($res['data'], 've_uid');
			if(!empty($res['data']))
			{
				foreach ($res['data'] as $k=>$v)
				{
					if(!empty($v['ve_imgs']))
					{
						$v['imgArr']=explode(',',$v['ve_imgs']);
					}
					$v['checkArr']=json_decode($v['ve_check'],true);
					if(!empty($v['checkArr']['uid']))
					{
						$userId[]=$v['checkArr']['uid'];
					}
					$lists[$k]=$v;
				}

				//其他图
				$YpwBase= new YpwBase();
				$res = $YpwBase->get('stand_vin_imgs', ['*'], sprintf(" and vii_vin in ('%s')", implode("','", array_column($lists, 've_vin'))));
				$othimg = [];
				foreach($res['data'] as $v){
					$othimg[$v['vii_vin']][] = $v;
				}

				$res = $YpwBase->get('stand_model_any', ['*'], sprintf(" and sma_vin in ('%s')", implode("','", array_column($lists, 've_vin'))));
				$smaArr = array_column($res['data'], null, 'sma_vin');
				LibTpl::Set('othimg', $othimg);
				LibTpl::Set('smaArr', $smaArr);
			}
			LibTpl::Set('lists', $lists);
			
			if(!empty($userId))
			{
				$LibYpApi = new LibYpApi();
				$post = [
					'filed'=>['u_id','u_name'],
					'where'=>sprintf(" and u_id in(%s)",implode(',',$userId)),
					'oneRow'=>false
				];
				$uidArr = $LibYpApi->Get('user/getUser',[], $post);
				LibTpl::Set('userArr',array_column($uidArr['data'],null, 'u_id'));
			}
		}
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','VIN纠错-跑街令');
		LibTpl::Put();
	}
	function checkVin()
	{
		LibRule::Check('CA03');
		if(!isset($_POST['status'])||!LibFc::Int($_POST['vId']))
		{
			LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'VIN审核失败'));
		}
		$PjlBase= new PjlBase();
		$dataArr=[
			've_status'=>((int)$_POST['status']),
			've_check'=>json_encode(['uid'=>mvc::$cfg['LOGUSER']['uid'],'remark'=>$_POST['remark'],'time'=>time()],JSON_UNESCAPED_UNICODE),
		];
		$res=$PjlBase->set('pl_vin_error',$dataArr,sprintf(' and ve_id=%d',$_POST['vId']));
		LibFc::ajaxJsonEncode($res);
	}
	function delCheckVin()
	{
		LibRule::Check('CA03');
		if(!LibFc::Int($_POST['vId']))
		{
			LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'删除失败'));
		}
		$PjlBase= new PjlBase();
		$res=$PjlBase->del('pl_vin_error',sprintf(' and ve_id=%d',$_POST['vId']));
		LibFc::ajaxJsonEncode($res);
	}


	//VIN识别图片收集
	function collVinImgs()
	{
		LibRule::Check('CA09');
		$rule = LibRule::Check('CA04', false);
		$Params = mvc::$URL_PARAMS;

		$h = date('H');
		$engine6Work = $h < 8 || $h >= 20? false: true;

		$YpwBase= new YpwBase();
		$PjlBase= new PjlBase();
		$res = $YpwBase->get('stand_vin_imgs', ['distinct vii_check_uid'], ' ');
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user', ['au_uid', 'au_name'], sprintf(" and au_uid in (%s) order by au_status desc, au_name", implode(',', array_column($res['data'], 'vii_check_uid'))));
		LibTpl::Set('userArr', array_column($res['data'], 'au_name', 'au_uid'));

		$statusArr=[
			0=>'待核对',
			1=>'有效',
			-2=>'疑难',
			-3=>'日期[待]',
			-5=>'待OCR',
		];

		$res = $YpwBase->get('stand_vin_imgs', ['vii_year'], ' and vii_year > 0 group by vii_year order by vii_year desc');
		$yearArr = array_column($res['data'], 'vii_year');
		LibTpl::Set('yearArr',$yearArr);

		LibTpl::Set('statusArr',$statusArr);

		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 16;
		$page=!empty($Params['page'])?(int)$Params['page']:1;

		$YpcBase= new YpcBase();
		$res = $YpcBase->get('yp_vin JOIN yp_make ON m_id = vin_m_id', ['vin_vin3, m_name'], ' GROUP BY vin_vin3, m_name ORDER BY m_initial, vin_vin3, COUNT(*) DESC');
		$wmiToMake = [];
		$makeToWmi = [];
		foreach($res['data'] as $v)
		{
			$wmiToMake[$v['vin_vin3']] = $v['m_name'];
			$makeToWmi[$v['m_name']][] = $v['vin_vin3'];
		}
		LibTpl::Set('wmiToMake', $wmiToMake);
		LibTpl::Set('makeToWmi', $makeToWmi);

		$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
		$where = '';
		$table = 'stand_vin_imgs';
		if(!empty($_POST['vin']))
		{
			$perPage = null;
			LibTpl::Set('hidePage', 1);
			$Params = $_POST;
		}
		else
		{
			if(!$rule)
			{
				unset($Params['uid']);
				unset($Params['wmis']);
			}
			$Params['vin'] = LibFc::FormatNum(strtr($Params['vin'], $ReLike), '%_');

			//查询条件有指定WMI
			if(preg_match('/^([0-9A-Z]{3})/', $Params['vin'], $match))
			{
				$wmiW = $match[0];
				if(preg_match('/^([0-9A-Z]{8})/', $Params['vin'], $match))
				{
					$where .= sprintf(" and vii_vin1_8 = '%s'", $match[0]);
				}
				else
				{
					$where .= sprintf(" and vii_vin1_3 = '%s'", $wmiW);
				}
				//有忽略
				if($Params['ignore'] == 1)
				{
					$res = $YpwBase->get('stand_vin_imgs_ignore', ['viig_byear, viig_eyear'], sprintf(" and viig_wmi='%s'", $wmiW), true);
					if(!empty($res['data']))
					{
						if($res['data']['viig_byear'] > 0) $where .= sprintf(" and vii_year < %d", $res['data']['viig_byear']);
						if($res['data']['viig_eyear'] > 0) $where .= sprintf(" and vii_year > %d", $res['data']['viig_eyear']);
						//全部忽略
						if($res['data']['viig_byear'] == 0 && $res['data']['viig_eyear'] == 0) $where .= ' and 1=0';
					}
				}

				$res = $YpwBase->get('stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi', ['*'], sprintf(" and vta_status = 1 AND vtu_uid=%d and vta_wmi = '%s'", $_SESSION['admin_userid'], $wmiW), true);
				if(!empty($res['data']))
				{
					$tarArr = $res['data'];
					if(!$rule)
					{
						if(!empty($Params['vii_istask']))
						{
							$where.= $tarArr['vta_js']? ' and vii_istask > 0': ' and 1=0';
						}
						else
						{
							if(!empty($tarArr['vta_wait'])) $where .= sprintf(" and vii_atime < %d", time()-$tarArr['vta_wait']*60);
							if(!empty($tarArr['vta_only']))
							{
								$tor = [];
								foreach(explode(',', $tarArr['vta_only']) as $reg)
								{
									$tor[] = sprintf(" vii_vin like '%s'", $reg);
								}
								$where .= sprintf(" and (%s)", implode(' or ', $tor));
							}
							else if(!empty($tarArr['vta_ignore']))
							{
								foreach(explode(',', $tarArr['vta_ignore']) as $reg)
								{
									$where .= sprintf(" and vii_vin not like '%s'", $reg);
								}
							}

							if($tarArr['vta_byear'] > 0 && (empty($Params['byear']) || $Params['byear'] < $tarArr['vta_byear']))
							{
								$Params['byear'] = $tarArr['vta_byear'];
							}
							if($tarArr['vta_eyear'] > 0 && (empty($Params['eyear']) || $Params['eyear'] > $tarArr['vta_eyear']))
							{
								$Params['eyear'] = $tarArr['vta_eyear'];
							}
						}
					}
				}
				else if(!$rule)
				{
					LibTpl::Error($wmiW.'任务已处理完毕或者尚未分配');
				}
			}
			else
			{
				if(!$rule)
				{
					if($Params['vii_istask']){
					}else{
						$tArr = [];
						$res = $YpwBase->get('stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi', ['group_concat(vta_wmi) AS vta_wmi, vta_byear, vta_eyear, vta_ignore, vta_only, vta_wait'], sprintf(" and vta_status = 1 and vtu_uid=%d group by vta_byear, vta_eyear, vta_ignore, vta_only, vta_wait", $_SESSION['admin_userid']));
						foreach($res['data'] as $v)
						{
							$t = sprintf(" (vii_vin1_3 in ('%s')", implode("','", explode(',', $v['vta_wmi'])));
							if(!empty($v['vta_wait'])) $t .= sprintf(" and vii_atime < %d", time()-$v['vta_wait']*60);
							if(!empty($v['vta_only']))
							{
								$tor = [];
								foreach(explode(',', $v['vta_only']) as $reg)
								{
									$tor[] = sprintf(" vii_vin like '%s'", $reg);
								}
								$t .= sprintf(" and (%s)", implode(' or ', $tor));
							}
							else if(!empty($v['vta_ignore']))
							{
								foreach(explode(',', $v['vta_ignore']) as $reg)
								{
									$t .= sprintf(" and vii_vin not like '%s'", $reg);
								}
							}
							if($v['vta_byear'] > 0) $t .= ' and vii_year >='.$v['vta_byear'];
							if($v['vta_eyear'] > 0) $t .= ' and vii_year <='.$v['vta_eyear'];
							$tArr[] = $t.')';
						}
						if(empty($tArr))
						{
							$where .= sprintf(" and vii_status =1 and vii_check_uid=%d", $_SESSION['admin_userid']);
						}
						else
						{
							$where .= sprintf(" and ((vii_status =1 and vii_check_uid=%d) OR (vii_status != 1 and (%s)))", $_SESSION['admin_userid'], implode(' OR ', $tArr));
						}
					}
				}
				else
				{
					//过滤忽略
					$ignorWhere = '';
					if($Params['ignore'] == 1)
					{
						$res =  $YpwBase->get('stand_vin_imgs_ignore', ['group_concat(viig_wmi) AS viig_wmi, viig_byear, viig_eyear'], ' group by viig_byear, viig_eyear');
						foreach( $res['data'] as $v)
						{
							if($v['viig_byear'] == 0 && $v['viig_eyear'] == 0)
							{
								$ignorWhere .= ' and vii_vin1_3 not in (select viig_wmi from stand_vin_imgs_ignore where viig_byear = 0 and viig_eyear = 0)';
							}
							else
							{
								$ignorWhere .= sprintf(" and vii_id NOT IN (SELECT vii_id FROM stand_vin_imgs WHERE vii_vin1_3 in ('%s')", implode("','", explode(',', $v['viig_wmi'])));
								if($v['viig_byear'] > 0) $ignorWhere .= ' and vii_year >='.$v['viig_byear'];
								if($v['viig_eyear'] > 0) $ignorWhere .= ' and vii_year <='.$v['viig_eyear'];
								$ignorWhere .= ')';
							}
						}
					}
					$where .= $ignorWhere;
				}
			}
		}
		$urlParams = $Params;
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if($v == '') continue;
			switch($k)
			{
				case 'uid':
					$where.=sprintf(' and vii_check_uid=%d', (int) $v);
				break;
				case 'vin':
					if(stripos($v, "\r\n"))
					{
						$anyNum = array_unique(explode("\r\n", str_replace(';', "\r\n", trim($v))));		
						if(count($anyNum) > 50) unset($urlParams['vin']);
						foreach($anyNum as $kk=>$vv)
						{
							$anyNum[$kk] = LibFc::FormatVin($vv);
						}
						$where .= sprintf(" and vii_vin IN ('%s')", implode("','", $anyNum));
					}
					else if(preg_match('/^([0-9A-Z]{3})\%?$/', $v, $match) || preg_match('/^([0-9A-Z]{8})\%?$/', $v, $match))
					{}
					else
					{
						$where.=sprintf(" and vii_vin LIKE '%s%%'", rtrim($v, '%'));
					}
				break;
				case 'vii_imgocr':
					$v = str_replace('　',' ',$v);
					foreach(explode(' ', $v) as $tv)
					{
						$tv = trim($tv);
						if(!empty($tv))
							$where.=sprintf(" and vii_imgocr like '%%%s%%' AND vii_vin not like '%%%s%%'", LibFc::Escape($tv), LibFc::Escape($tv));
					}
				break;
				case 'vin1':
					if($v == 'L') $where.= " and (vii_vin1_3 LIKE 'L%' OR vii_vin1_3 LIKE 'H%')";
					else if($v == '!L') $where.= " AND vii_vin1_3 NOT LIKE 'L%' AND vii_vin1_3 NOT LIKE 'H%'";
				break;
				case 'status':
					$where.=sprintf(' and vii_status=%d', (int) $v);
				break;
				case 'vii_imgtype':
					$where.=sprintf(' and vii_imgtype=%d', (int) $v);
				break;
				case 'byear':
					if($v > 1949) $where.=sprintf(' and vii_year >= %d', $v);
				break;
				case 'eyear':
					if($v > 1949) $where.=sprintf(' and vii_year <= %d', $v);
				break;
				case 'wmis':
					$where.= sprintf(" and left(vii_vin, 3) in ('%s')", implode("','", explode(',', $v)));
				break;
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and vii_atime >= %d and vii_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
				case 'vii_anygxb':
					if(!empty($v) && stripos($where, 'vii_anygxb') === false) $where.= ' and vii_anygxb=1';
				break;
				case 'vii_istask':
					if(!empty($v) && stripos($where, 'vii_istask') === false) 
						$where.= $rule? ' and vii_istask > 0': sprintf("  and vii_istask > 0 and vii_vin1_3 in (select vta_wmi from stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi where vtu_uid=%d and vta_js =1)", $_SESSION['admin_userid']);
				break;
				case 'smayear': 
					if(empty($Params['vin'])) break;
					$twhereArr = [];
					$smawhere = sprintf(" and sma_vin LIKE '%s%%' AND sma_year != ''", rtrim($Params['vin'], '%'));
					if(!empty($Params['byear'])) $smawhere .=sprintf(' and sma_vyear >= %d', $Params['byear']);
					if(!empty($Params['eyear'])) $smawhere .=sprintf(' and sma_vyear <= %d', $Params['eyear']);
					$sres = $YpwBase->get('stand_model_any',['sma_vin1_8, sma_vin10, LEFT(sma_year, 7) syear, MIN(RIGHT(sma_vin, 7)) min1317, MAX(RIGHT(sma_vin, 7)) max1317'], $smawhere." GROUP BY sma_vin1_8, sma_vin10, syear ORDER BY sma_vin1_8, sma_vin10_12, min1317, syear");
					if(empty($sres['data'])) break;
					$hasvin812 = [];
					foreach($sres['data'] as $sv)
					{
						$tkey = $sv['sma_vin1_8'].$sv['sma_vin10'];
						if(empty($hasvin812Arr[$tkey])) $hasvin812Arr[$tkey] = ['base'=>$sv, 'items'=>[]];
						$hasvin812Arr[$tkey]['items'][] = $sv;
					}
					foreach($hasvin812Arr as $tkey=>$svs)
					{
						$scomwhere = sprintf("vii_vin1_8='%s' and vii_vin10_12 like'%s%%'", $svs['base']['sma_vin1_8'], $svs['base']['sma_vin10']);
						$items = $svs['items'];
						$itemCount = count($items);
						if($itemCount == 1)
						{
							//$twhereArr[] = sprintf("(%s and (RIGHT(vii_vin, 7) < '%s' OR RIGHT(vii_vin, 7) >'%s'))", $scomwhere, $items[0]['min1317'], $items[0]['max1317']);
							continue;
						}

						foreach($items as $sk=>$sv)
						{
							if($sk+1 == $itemCount)
							{
								//$twhereArr[] = sprintf("(%s and RIGHT(vii_vin, 7) > '%s')", $scomwhere, $sv['max1317']);
							}
							else
							{
								/*if($sk == 0)
									$twhereArr[] = sprintf("(%s and RIGHT(vii_vin, 7) < '%s')", $scomwhere, $sv['min1317']);*/
								if($sv['syear'] == $items[$sk+1]['syear']) continue;
								if(date('Y-m', strtotime('+1 month', strtotime($sv['syear'].'-01'))) == $items[$sk+1]['syear']) continue;
								$twhereArr[] = sprintf("(%s and RIGHT(vii_vin, 7) > '%s' and RIGHT(vii_vin, 7) < '%s')", $scomwhere, $sv['max1317'], $items[$sk+1]['min1317']);
							}
						}
					}
					if(!empty($twhereArr))
					{
						$table .= ' left join yp_allvin_base on vii_vin = alb_vin';
						$where .= " and alb_vin is null";
						$where .= sprintf(" and (%s)", implode(" or ", $twhereArr));
					}
					else
					{
						$where .= ' and 1=0';
					}
				break;
			}
		}
		if(!$rule && (date('H') >= 20 || date('H') < 8)) $where .= " and vii_imgtype != 1";

		$orderArr=[
			'null'=>['','不排序'],
			'vin'=>['order by vii_vin1_8,vii_vin10_12,vii_vin13_17','车架号'],
			'yearvin'=>['order by vii_year desc,vii_vin1_8,vii_vin10_12,vii_vin13_17', '综合排序'],
			'chktime'=>['order by vii_check_time desc', '处理时间'],
			'new'=>['order by vii_id desc', '添加新到旧'],
			'old'=>['order by vii_id asc', '添加旧到新'],
		];
		LibTpl::Set('orderArr', $orderArr);
		if(empty($orderArr[$Params['order']])) $Params['order'] = 'null';
		$res=$YpwBase->get($table,['count(1) count'], $where,true);
		$total=$res['data']['count'];
		if($perPage === null) $perPage = $total;
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page',$Page);
		$lists = [];$eng6NullVins = [];
		if($total>0)
		{
			$where.= sprintf(' %s limit %s,%s', $orderArr[$Params['order']][0], ($page-1)*$perPage,$perPage);
			$res=$YpwBase->get($table, ['*'], $where);
			$lists = $res['data'];
			foreach($lists as $tv){
				if($tv['vii_year'] > 2016) $eng6NullVins[] = $tv['vii_vin'];
			}
			if($eng6NullVins){
				$eng6NullVins = array_unique($eng6NullVins);
				$res = $YpwBase->get('stand_catch_list',['distinct sce_vin'], sprintf(" and sce_reg_code='engine6' AND sce_status=-2 and sce_vin in ('%s') AND sce_error LIKE '#end#未公开%%'", implode("','", $eng6NullVins)));
				$eng6NullVins = array_column($res['data'], 'sce_vin');
			}
			$userId = array_column($lists, 've_uid');
		}
		LibTpl::Set('eng6NullVins', $eng6NullVins);
		LibTpl::Set('imgtypeArr', ['1'=>'证件','2'=>'铭牌', '0'=>'普通']);
		LibTpl::Set('lists', $lists);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('urlParams',$urlParams);
		LibTpl::Set('rule', $rule);
		LibTpl::Set('title','VIN识别图');
		LibTpl::Put();
	}



	//我的VIN任务
	function collVinImgsMyTarget()
	{
		LibRule::Check('CA09');
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		$YpwBase= new YpwBase();
		$res =  $YpwBase->get('stand_vin_imgs_task_user JOIN stand_vin_imgs_task ON vta_wmi = vtu_vta_wmi', ['*'], sprintf(" and vta_status = 1 AND vtu_uid=%d order by vta_wmi", $_SESSION['admin_userid']));
		$tarArr = array_column($res['data'], null, 'vta_wmi');
		if(!empty($tarArr))
		{
			$total = [];
			$wmiBrandLink = $this->getWmiBrandLink(array_column($tarArr, 'vta_wmi'));
			$sort = [];
			foreach($tarArr as $k=>$v)
			{
				$t = sprintf(" and vii_status=0 and vii_vin1_3='%s'", $v['vta_wmi']);
				//计算任务
				if($v['vta_js'])
				{
					$res = $YpwBase->get('stand_vin_imgs', ['count(*) as count'], $t.' and vii_istask > 0', true);
					$v['wait_count_js'] = $res['data']['count'];
				}
				else
				{
					$v['wait_count_js'] = 0;
				}
				$total['wait_count_js'] += $v['wait_count_js'];

				if($v['vta_byear'] > 0) $t .= ' and vii_year >='.$v['vta_byear'];
				if($v['vta_eyear'] > 0) $t .= ' and vii_year <='.$v['vta_eyear'];

				if(!empty($v['vta_wait'])) $t .= sprintf(" and vii_atime < %d", time()-$v['vta_wait']*60);
				if(!empty($v['vta_only']))
				{
					$tor = [];
					foreach(explode(',', $v['vta_only']) as $reg)
					{
						$tor[] = sprintf(" vii_vin like '%s'", $reg);
					}
					$t .= sprintf(" and (%s)", implode(' or ', $tor));
				}
				else if(!empty($v['vta_ignore']))
				{
					foreach(explode(',', $v['vta_ignore']) as $reg)
					{
						$t .= sprintf(" and vii_vin not like '%s'", $reg);
					}
				}
				$res = $YpwBase->get('stand_vin_imgs', ['count(*) as count'], $t, true);
				$v['wait_count'] = $res['data']['count'];
				$total['wait_count'] += $v['wait_count'];

				/*$res = $YpwBase->get('stand_vin_imgs', ['count(*) as count'], sprintf(" and vii_vin1_3='%s' and vii_status=1 and vii_check_uid=%d", $v['vta_wmi'], $_SESSION['admin_userid']), true);
				$v['ok_count'] = $res['data']['count'];
				$total['ok_count'] += $v['ok_count'];*/

				$v['brands'] = empty($wmiBrandLink['wmi'][$v['vta_wmi']])? []: $wmiBrandLink['wmi'][$v['vta_wmi']];
				$v['wait_all'] = $v['wait_count'] + $v['wait_count_js'];
				$sort[$k] = $v['wait_all'];
				$tarArr[$k] = $v;
			}
			array_multisort($sort, SORT_DESC, $tarArr);
		}
		LibTpl::Set('total', $total);
		LibTpl::Set('tarArr', $tarArr);
		LibTpl::Set('title','我的VIN工作台');
		LibTpl::Put();
	}


	private function getWmiBrandLink($wmiArr)
	{
		$arr = [];
		if(!empty($wmiArr))
		{
			$wmiArr = array_unique($wmiArr);
			$YpcBase= new YpcBase();
			$table = '`yp_model3`
			JOIN `yp_vin_model3_link` ON vm3_m3_id = m3_id
			JOIN `yp_vin` ON vin_id = vm3_vin_id
			JOIN `yp_model2` ON m3_m2_id = m2_id
			JOIN `yp_model1` ON m2_m1_id = m1_id
			JOIN `yp_make` ON m_id = m1_m_id';
			$len = strlen($wmiArr[0]);
			$res = $YpcBase->get($table, ['left(vin_full, '.$len.') as vin, m_name'], sprintf(" and left(vin_full, %d) in('%s') GROUP BY vin, m_id ORDER BY COUNT(*) DESC", $len,implode("','", $wmiArr)));
			foreach($res['data'] as $v)
			{
				$arr['wmi'][$v['vin']][] = $v['m_name'];
				$arr['make'][$v['m_name']][] = $v['vin'];
			}
		}
		return $arr;
	}


	//删除VIN识别图片
	function collVinImgsDel()
	{
		LibRule::Check('CA09');
		$YpwBase= new YpwBase();
		$res = $YpwBase->get('stand_vin_imgs', ['vii_id', 'vii_imghost', 'vii_img'], sprintf(' and vii_id in (%s)', implode(',', $_POST['viiids'])));
		if(!empty($res['data']))
		{
			$delFileArr = [];
			foreach($res['data'] as $v)
			{
				$delFileArr[$v['vii_imghost']][] = $v['vii_img'];
			}
			if(!empty($delFileArr[1]))
			{
				//删除图片
				$OthFileCenter = new OthFileCenter();
				$delArr = [
					'cate'=>'vinimg',
					'files'=>$delFileArr[1]
				];
				$OthFileCenter->del($delArr, 'yp');
			}

			if(!empty($delFileArr[2]))
			{
				//删除本地的
				$delArr = [
					'token'=>mvc::$cfg['FILE_CENTER']['yp']['token'],
					'files'=>$delFileArr[2]
				];
				$LibHttp = new LibHttp();
				$LibHttp->timeout = 1;
				$LibHttp->fetch(mvc::$cfg['HOST']['VINADMIN67'].'VinTj/delVinOcrImg', $delArr);
			}
			$ids = array_column($res['data'], 'vii_id');
			$YpwBase->del('stand_vin_imgs', sprintf(' and vii_id in (%s)', implode(',', $ids)));
			$YpwBase->del('stand_vin_imgs_retask', sprintf(' and vir_vii_id in (%s)', implode(',', $ids)));
		}
		LibFc::ajaxJsonEncode($res);
	}

	//转为待处理 VIN识别图片
	function collVinImgsWait()
	{
		LibRule::Check('CA09');
		$YpwBase= new YpwBase();
		$res = $YpwBase->set('stand_vin_imgs', ['vii_status'=>0], sprintf(' and vii_id in (%s) and vii_status !=1', implode(',', $_POST['viiids'])));
		LibFc::ajaxJsonEncode($res);
	}


	function checkVinOcrImg()
	{
		LibRule::Check('CA09');
		if(!isset($_POST['status'])||!LibFc::Int($_POST['vId']))
		{
			LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'VIN审核失败'));
		}
		$YpwBase= new YpwBase();
		$dataArr=[
			'vii_status'=>((int)$_POST['status']),
			'vii_check'=>json_encode(['uid'=>mvc::$cfg['LOGUSER']['uid'],'remark'=>$_POST['remark'],'time'=>time()], JSON_UNESCAPED_UNICODE),
		];
		$res=$YpwBase->set('stand_vin_imgs',$dataArr,sprintf(' and vii_id=%d',$_POST['vId']));
		LibFc::ajaxJsonEncode($res);
	}

	//vin识别图处理统计
	function collVinImgsTj()
	{
		$rule = LibRule::Check('CA07', false);
		$Params = mvc::$URL_PARAMS;
		$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('fastTime', $fastTime);

		$YpwBase= new YpwBase();
		if($rule)
		{
			$res = $YpwBase->get('stand_vin_imgs', ['DISTINCT vii_check_uid'], '');
			$uids = implode(',', array_column($res['data'], 'vii_check_uid'));
		}
		else
		{
			$Params['uid'] = $_SESSION['admin_userid'];
			$uids = $Params['uid'];
		}

		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user', ['au_uid', 'au_name'], sprintf(" and au_uid in (%s) order by au_status desc, au_name asc", $uids));
		LibTpl::Set('userArr', array_column($res['data'], 'au_name', 'au_uid'));

		$where = ' and vii_status=1';

		$Params['betime'] = empty($Params['betime'])? $fastTime['本月']: $Params['betime'];
		foreach($Params as $k=>$v)
		{
			$v = trim($v);
			if($v == '') continue;
			switch($k)
			{
				case 'uid':
					$where.=sprintf(' and vii_check_uid=%d', (int) $v);
				break;
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and vii_check_time >= %d and vii_check_time < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
			}
		}

		$res = $YpwBase->get('stand_vin_imgs', ["vii_check_uid, count(*) as vii_count"], $where." group by vii_check_uid order by count(*) desc");
		$allTj = [];
		foreach($res['data'] as $v)
		{
			$allTj[$v['vii_check_uid']]['vii_count'] += $v['vii_count'];
			$total['vii_count'] += $v['vii_count'];
		}

		$res = $YpwBase->get('stand_vin_imgs', ["vii_check_uid, FROM_UNIXTIME(vii_check_time,'%Y-%m-%d') as vii_date, count(*) as vii_count"], $where." group by vii_check_uid, FROM_UNIXTIME(vii_check_time,'%Y-%m-%d') order by FROM_UNIXTIME(vii_check_time,'%Y-%m-%d') desc");
		$tjArr = [];
		foreach($res['data'] as $v)
		{
			$allTj[$v['vii_check_uid']]['vii_date'] += 1;
			$tjArr[$v['vii_date']][$v['vii_check_uid']] = $v;
		}

		LibTpl::Set('allTj', $allTj);
		LibTpl::Set('total', $total);
		LibTpl::Set('tjArr',$tjArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','识别图处理统计');
		LibTpl::Put();
	}


	function collVin18Tj()
	{
		LibRule::Check('CA04');
		$Params = mvc::$URL_PARAMS;
		$YpwBase= new YpwBase();
		$res = $YpwBase->get('stand_vin_imgs', ['DISTINCT vii_year as year'], ' and vii_year > 0 ORDER BY vii_year DESC');
		LibTpl::Set('yearArr', array_column($res['data'], 'year'));
		$lists = [];
		if(isset($Params['vin']))
		{
			$vinbit = empty($Params['vinbit'])? 8: (int) $Params['vinbit'];
			$vincount = empty($Params['vincount'])? 100: (int) $Params['vincount'];
			$where = '';

			if($Params['vin1'] == '!L') $where.= " and vii_vin not LIKE 'L%' and vii_vin not LIKE 'H%'";
			if($Params['vin1'] == 'L') $where.= " and (vii_vin LIKE 'L%' OR vii_vin LIKE 'H%')";
			if(!empty($Params['byear'])) $where .= sprintf(" and vii_year>=%d", $Params['byear']);
			if(!empty($Params['eyear'])) $where .= sprintf(" and vii_year<=%d", $Params['eyear']);

			$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
			if(!empty($Params['vin'])) $where.=sprintf(" and vii_vin LIKE '%s'",  LibFc::FormatNum(strtr($Params['vin'], $ReLike), '%_'));

			//过滤忽略
			$ignorWhere = '';
			$Params['ignore'] = $Params['ignore'] == -1? -1: 1;
			if($Params['ignore'] == 1)
			{
				$res =  $YpwBase->get('stand_vin_imgs_ignore', ['group_concat(viig_wmi) AS viig_wmi, viig_byear, viig_eyear'], ' group by viig_byear, viig_eyear');
				foreach( $res['data'] as $v)
				{
					if($v['viig_byear'] == 0 && $v['viig_eyear'] == 0)
					{
						$ignorWhere .= ' and vii_vin1_3 not in (select viig_wmi from stand_vin_imgs_ignore where viig_byear = 0 and viig_eyear = 0)';
					}
					else
					{
						$ignorWhere .= sprintf(" and vii_id NOT IN (SELECT vii_id FROM stand_vin_imgs WHERE vii_vin1_3 in ('%s')", implode("','", explode(',', $v['viig_wmi'])));
						if($v['viig_byear'] > 0) $ignorWhere .= ' and vii_year >='.$v['viig_byear'];
						if($v['viig_eyear'] > 0) $ignorWhere .= ' and vii_year <='.$v['viig_eyear'];
						$ignorWhere .= ')';
					}
				}
			}
			$where .= $ignorWhere;

			$res = $YpwBase->get('stand_vin_imgs', ['left(vii_vin, '.$vinbit.') as vin18, count(*) as  count, count(case when vii_status = 1 then 1 else null end) as ok_count, count(case when vii_status = 0 then 1 else null end) as wait_count, count(case when vii_status = -2 then 1 else null end) as yinan_count'], $where." and vii_status != -1 group by vin18 having count(*) >= ".$vincount." order by count(*) desc");
			$lists = array_column($res['data'], null, 'vin18');
			if(!empty($lists))
			{
				$wmiBrandLink = $this->getWmiBrandLink(array_column($lists, 'vin18'));
				foreach($lists as $k=>$v)
				{
					$v['brands'] = empty($wmiBrandLink['wmi'][$v['vin18']])? []: $wmiBrandLink['wmi'][$v['vin18']];
					$lists[$k] = $v;
				}
			}
		}
		LibTpl::Set('lists', $lists);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','VIN1-8识别图统计');
		LibTpl::Put();
	}


	//任务分配
	function collVinTask()
	{
		LibRule::Check('CA08');
		$Params = mvc::$URL_PARAMS;
		$YpwBase= new YpwBase();
		$res = $YpwBase->get('stand_vin_imgs', ['DISTINCT vii_year as year'], ' and vii_year > 0 ORDER BY vii_year DESC');
		LibTpl::Set('yearArr', array_column($res['data'], 'year'));

		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user JOIN an_user_rule ON au_uid = aur_au_uid', ['au_uid', 'au_name'], " and aur_arule_id IN ('CA09') ORDER BY au_status DESC, CONVERT(au_name USING gbk)");
		$workerArr = array_column($res['data'], 'au_name', 'au_uid');
		LibTpl::Set('workerArr', $workerArr);

		$vincount = empty($Params['vincount'])? 100: (int) $Params['vincount'];
		$Params['ignore'] = $Params['ignore'] == -1? -1: 1;
		$lists = [];
		if(isset($Params['vin']))
		{
			$where = '';
			if(!empty($Params['byear'])) $where .= sprintf(" and vii_year>=%d", $Params['byear']);
			if(!empty($Params['eyear'])) $where .= sprintf(" and vii_year<=%d", $Params['eyear']);

			$ReLike = array('*'=>'%', '?'=>'_', '？'=>'_');
			if(!empty($Params['vin'])) $where.=sprintf(" and vii_vin1_3 LIKE '%s'",  LibFc::FormatNum(strtr($Params['vin'], $ReLike), '%_'));

			//过滤忽略
			$ignorWhere = '';
			if($Params['ignore'] == 1)
			{
				$res =  $YpwBase->get('stand_vin_imgs_ignore', ['group_concat(viig_wmi) AS viig_wmi, viig_byear, viig_eyear'], ' group by viig_byear, viig_eyear');
				foreach( $res['data'] as $v)
				{
					if($v['viig_byear'] == 0 && $v['viig_eyear'] == 0)
					{
						$ignorWhere .= ' and vii_vin1_3 not in (select viig_wmi from stand_vin_imgs_ignore where viig_byear = 0 and viig_eyear = 0)';
					}
					else
					{
						$ignorWhere .= sprintf(" and vii_id NOT IN (SELECT vii_id FROM stand_vin_imgs WHERE vii_vin1_3 in ('%s')", implode("','", explode(',', $v['viig_wmi'])));
						if($v['viig_byear'] > 0) $ignorWhere .= ' and vii_year >='.$v['viig_byear'];
						if($v['viig_eyear'] > 0) $ignorWhere .= ' and vii_year <='.$v['viig_eyear'];
						$ignorWhere .= ')';
					}
				}
			}
			$where .= $ignorWhere;

			$res = $YpwBase->get('stand_vin_imgs', ['vii_vin1_3, count(*) as count, count(case when vii_status = 1 then 1 else null end) as ok_count, count(case when vii_status = 0 then 1 else null end) as wait_count, count(case when vii_status = -2 then 1 else null end) as yinan_count'], $where." and vii_status != -1 group by vii_vin1_3 having count(*) >= ".$vincount." order by count(*) desc");
			$lists = array_column($res['data'], null, 'vii_vin1_3');
			if(!empty($lists))
			{
				$wmiBrandLink = $this->getWmiBrandLink(array_column($lists, 'vii_vin1_3'));
				foreach($lists as $k=>$v)
				{
					$v['brands'] = empty($wmiBrandLink['wmi'][$v['vii_vin1_3']])? []: $wmiBrandLink['wmi'][$v['vii_vin1_3']];
					$lists[$k] = $v;
				}
			}
		}

		//计算任务数
		$userTar = [];
		$res = $YpwBase->get('stand_vin_imgs_task', ['*'], '');
		$taskArr = array_column($res['data'], null, 'vta_wmi');
		foreach($taskArr as $wmi=>$v)
		{
			$twhere = sprintf(" and vii_status=0 and vii_vin1_3='%s'", $wmi);
			if($v['vta_js'])
			{
				$res = $YpwBase->get('stand_vin_imgs', ['count(*) as wait_count'], $twhere.' and vii_istask > 0', true);
				$v['wait_count_js'] = $res['data']['wait_count'];
			}
			else
			{
				$v['wait_count_js'] = 0;
			}
			if($v['vta_byear'] > 0){
				$twhere .= ' and vii_year >='.$v['vta_byear'];
			}else{
				$v['vta_byear'] = '';
			}
			if($v['vta_eyear'] > 0){
				$twhere .= ' and vii_year <='.$v['vta_eyear'];
			}else{
				$v['vta_eyear'] = '';
			}

			if(!empty($v['vta_wait'])) $twhere .= sprintf(" and vii_atime < %d", time()-$v['vta_wait']*60);
			if(!empty($v['vta_only']))
			{
				$t = [];
				foreach(explode(',', $v['vta_only']) as $reg)
				{
					$t[] = sprintf(" vii_vin like '%s'", $reg);
				}
				$twhere .= sprintf(" and (%s)", implode(' or ', $t));
			}
			else if(!empty($v['vta_ignore']))
			{
				foreach(explode(',', $v['vta_ignore']) as $reg)
				{
					$twhere .= sprintf(" and vii_vin not like '%s'", $reg);
				}
			}
			$res = $YpwBase->get('stand_vin_imgs', ['count(*) as wait_count'], $twhere, true);
			$v['wait_count'] = $res['data']['wait_count'];
			$v['wait_all'] = $v['wait_count']+$v['wait_count_js'];
			$taskArr[$wmi] = $v;
		}

		$res = $YpwBase->get('stand_vin_imgs_task_user join stand_vin_imgs_task on vta_wmi = vtu_vta_wmi', ['*'], '');
		foreach($res['data'] as $v)
		{
			if($v['vta_status']) $userTar[$v['vtu_uid']] += $taskArr[$v['vtu_vta_wmi']]['wait_all'];
			$taskArr[$v['vtu_vta_wmi']]['user'][] = $v['vtu_uid'];
		}

		$res =  $YpwBase->get('stand_vin_imgs_ignore', ['*'], ' order by viig_wmi, viig_byear');
		foreach($res['data'] as $v)
		{
			if($v['viig_byear'] == 0) $v['viig_byear'] ='';
			if($v['viig_eyear'] == 0) $v['viig_eyear'] ='';
			if(!empty($lists[$v['viig_wmi']])) $lists[$v['viig_wmi']]['ignore'][$v['viig_id']] = $v;
		}
		arsort($userTar);
		LibTpl::Set('userTar', $userTar);

		LibTpl::Set('taskArr', $taskArr);
		LibTpl::Set('lists', $lists);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','车架号图任务分配');
		LibTpl::Put();
	}



	//获取wmi的任务规则
	function collVinWmiTask()
	{
		$Params = mvc::$URL_PARAMS;
		$YpwBase= new YpwBase();
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('an_user JOIN an_user_rule ON au_uid = aur_au_uid', ['au_uid', 'au_name'], " and aur_arule_id IN ('CA09') ORDER BY au_status DESC, CONVERT(au_name USING gbk)");
		$workerArr = array_column($res['data'], 'au_name', 'au_uid');
		LibTpl::Set('workerArr', $workerArr);

		$res = $YpwBase->get('stand_vin_imgs_task', ['*'], sprintf(" and vta_wmi='%s'", $Params['wmi']), true);
		$arr = $res['data'];
		$arr['user'] = [];
		if(!empty($arr['vta_wmi']))
		{
			$res = $YpwBase->get('stand_vin_imgs_task_user', ['vtu_uid'], sprintf(" and vtu_vta_wmi='%s'", $Params['wmi']));
			$arr['user'] = array_column($res['data'], 'vtu_uid');
		}
		LibTpl::Set('Params', $Params);
		LibTpl::Set('arr', $arr);
		$html = LibTpl::Fetch();
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$html]);
	}

	//保存任务
	function collVinWmiTaskSave()
	{
		LibRule::Check('CA08');
		if(!empty($_POST['task']['vta_wmi']))
		{
			$YpwBase= new YpwBase();
			$addArr = $_POST['task'];
			$addArr['vta_js'] = (int) $addArr['vta_js'];
			$addArr['vta_byear'] = (int) $addArr['vta_byear'];
			$addArr['vta_eyear'] = (int) $addArr['vta_eyear'];
			$addArr['vta_wait'] = (int) $addArr['vta_wait'];
			$addArr['vta_ignore'] = strtoupper(LibFc::formatFenge($addArr['vta_ignore']));
			$addArr['vta_only'] = strtoupper(LibFc::formatFenge($addArr['vta_only']));
			$res = $YpwBase->get('stand_vin_imgs_task', ['vta_wmi'], sprintf(" and vta_wmi = '%s'", $addArr['vta_wmi']), true);
			if(!empty($res['data']))
			{
				$YpwBase->set('stand_vin_imgs_task', $addArr, sprintf(" and vta_wmi = '%s'", $addArr['vta_wmi']));
			}
			else
			{
				$YpwBase->add('stand_vin_imgs_task', $addArr);
			}
			$YpwBase->del('stand_vin_imgs_task_user', sprintf(" and vtu_vta_wmi = '%s'", $addArr['vta_wmi']));
			foreach($_POST['user'] as $uid)
			{
				$YpwBase->add('stand_vin_imgs_task_user', ['vtu_vta_wmi'=>$addArr['vta_wmi'], 'vtu_uid'=>(int) $uid, 'vtu_atime'=>time()]);
			}
			LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);
		}
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数获取失败！']);
	}

	//删除任务
	function collVinWmiTaskDel()
	{
		LibRule::Check('CA08');
		$Params = mvc::$URL_PARAMS;
		$YpwBase= new YpwBase();
		$YpwBase->del('stand_vin_imgs_task', sprintf(" and vta_wmi = '%s'", $Params['wmi']));
		$YpwBase->del('stand_vin_imgs_task_user', sprintf(" and vtu_vta_wmi = '%s'", $Params['wmi']));
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);
	}


	function setViiVin()
	{
		LibRule::Check('CA09');
		$Params = mvc::$URL_PARAMS;
		$YpwUser = new YpwUser();
		$res = $YpwUser->setViiVin($Params['vii_vin'], $Params['vii_id'], $Params['sma_id']);
		LibFc::ajaxJsonEncode($res);
	}


	//删除忽略
	function delIgnoreVin()
	{
		LibRule::Check('CA08');
		$Params = mvc::$URL_PARAMS;
		$viig_id = (int) $Params['viig_id'];
		$YpwBase= new YpwBase();
		$res = $YpwBase->del('stand_vin_imgs_ignore', ' and viig_id='.$viig_id);
		LibFc::ajaxJsonEncode($res);
	}


	//添加忽略
	function addIgnoreVin()
	{
		LibRule::Check('CA08');
		if(!empty($_POST['viig_wmi']))
		{
			$YpwBase= new YpwBase();
			$addArr = [
				'viig_wmi'=>$_POST['viig_wmi'],
				'viig_byear'=>(int) $_POST['viig_byear'],
				'viig_eyear'=>(int) $_POST['viig_eyear']
			];

			$where = sprintf(" and viig_wmi='%s' and viig_byear=%d and viig_eyear=%d", $addArr['viig_wmi'], $addArr['viig_byear'], $addArr['viig_eyear']);
			$res = $YpwBase->get('stand_vin_imgs_ignore', ['viig_id'], $where, true);
			if(!empty($res['data']))
			{
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'忽略记录已存在！']);
			}
			else
			{
				$res = $YpwBase->add('stand_vin_imgs_ignore', $addArr);
				LibFc::ajaxJsonEncode($res);
			}
		}
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数获取失败！']);
	}

	/**
	 * [displayRanking 展示排行榜]
	 * @Author   Yangxing
	 * @DateTime 2020-06-01T14:57:24+0800
	 * @return   [view]                   [视图]
	 */
	public function displayRanking()
	{
        LibRule::Check('AP00');
		LibTpl::Put();
	}

	public function displayRankings()
    {
        $params = mvc::$URL_PARAMS;
        $where = '';
        if(empty($params['tpsd_date'])){
            //最近三个月
            $where .= sprintf(" and tpsd_date between '%s' and '%s'",date('Ymd',strtotime("-3 month")),date('Ymd',time()));
            $params['tpsd_date'] =  date('Y-m',strtotime("-3 month"))." ~ ".date('Y-m',time());
        }else{
            $temp = explode(" ~ ", $params['tpsd_date']);
            $where .= sprintf(" and tpsd_date between '%s' and '%s'",date("Ymd",strtotime($temp['0'])),date("Ymd",strtotime($temp['1'])));
        }
        $table = 'tj_pjl_shop_date';
        $field = ["tpsd_shop_id","sum(tpsd_devcode_count) as devcode_count","sum(tpsd_pv_count) as pv_count"];
        $list = (new BaseDb(mvc::$cfg['DB']['API_TJ']))->get($table,$field,sprintf(" %s group by tpsd_shop_id order by pv_count desc limit 200",$where));

        if(!empty($list['data'])){
            $shop = (new PjlBase())->get('pl_shop', ["shop_id","shop_name"], sprintf(" and shop_id in(%s)",implode(",", array_column($list['data'],'tpsd_shop_id'))),false);
            $shop = array_column($shop['data'],null,'shop_id');
            foreach ($list['data'] as $key => &$value) {
                $value['shop_name'] = isset($shop[$value['tpsd_shop_id']]) ? $shop[$value['tpsd_shop_id']]['shop_name'] : '';
//			    unset($value['tpsd_shop_id']);
            }
        }

        unset($shop);
        LibTpl::Set('Params',$params);
        LibTpl::Set('list',$list['data']);
        LibTpl::Put();
    }

    //日期识别列表
    public function dateImage()
    {
        LibRule::Check('CA11');
        $Params = mvc::$URL_PARAMS;

        $YpwBase = new YpwBase();


        $userArr = [];
        $aUid = $YpwBase->get("stand_vin_dateocr",['svd_by'],sprintf(" and svd_by > 0 group by svd_by"));
        if(!empty($aUid['data'])){
            $temp = array_column($aUid['data'],'svd_by');
            $temp = implode(',',$temp);
            $res = (new B2cBase)->get('an_user', ['au_uid', 'au_name'], sprintf(" and au_uid in (%s) order by au_status desc, au_name",$temp));
            $userArr = array_column($res['data'], 'au_name', 'au_uid');
        }


        LibTpl::Set('userArr',$userArr);

        $perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 16;
        $page =! empty($Params['page']) ? (int)$Params['page'] : 1;

        $ReLike = array('*' => '%', '?' => '_', '？' => '_');
        $where = '';
        $Params['vin'] = LibFc::FormatNum(strtr($Params['vin'], $ReLike), '%_');

        foreach($Params as $k => $v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
                case 'uid':
                    $where .= sprintf(' and svd_by=%d', (int) $v);
                    break;
                case 'vin':
                    $where .= sprintf(" and svd_fromvin LIKE '%s'", $v);
                    break;
                case 'status':
                    $where .= sprintf(' and svd_status=%d', (int) $v);
                    break;
            }
        }


        $table = 'stand_vin_dateocr';
        $res = $YpwBase->get($table,['count(1) count'], $where,true);
        $total = $res['data']['count'];
        $Page = LibPage::Show($total, $perPage);
        //统计各个状态的数量
        $statistics = $YpwBase->get($table,['svd_status','count(*) as count'],sprintf(" group by svd_status"));
        LibTpl::Set('statistics',$statistics['data'] ? array_column($statistics['data'],'count','svd_status') : []);
        LibTpl::Set('Page',$Page);
        if($total > 0)
        {
            $where .= sprintf(' ORDER BY LEFT(svd_fromvin, 8), RIGHT(svd_fromvin, 8) limit %s,%s', ($page-1)*$perPage,$perPage);
            $list = $YpwBase->get($table,['*'],$where);
            LibTpl::Set('lists',$list['data']);
        }

        LibTpl::Set('statusArr',[0 => '待处理', 1 => '完成', -1 => '异常','-2' => '忽略']);
        LibTpl::Set('Params',$Params);
        LibTpl::Set('title','日期识别');
        LibTpl::Put();
    }

    public function edit()
    {
        LibRule::Check('CA11');
        $Params = MVC::$URL_PARAMS;
        $where = sprintf(" and svd_id = %d order by svd_id asc",$Params['svd_id']);
        $table = 'stand_vin_dateocr';
        $YpwBase = new YpwBase;
        $list = $YpwBase->get($table,['*'],$where,true);
        $data = $list['data'];
        if($data['svd_by'] > 0){
            $res = (new B2cBase)->get('an_user', ['au_uid', 'au_name'], sprintf(" and au_uid=%d",$data['svd_by']),true);
            $data['au_name'] = $res['data']['au_name'];
        }


        if(!empty($_POST)){
            unset($Params['from']);
            if($_POST['operation_status'] == 1 || $_POST['operation_status'] == 3){
                $res = $this->saveDateImage();
                if(!$res['status']){
                    LibTpl::Error($res['data'],mvc::$cfg['ADMIN_URI'].'PjlShop/edit?'.http_build_query($Params),1);
                }
                foreach($Params as $k => $v)
                {
                    $v = trim($v);
                    if($v == '') continue;
                    switch($k)
                    {
                        case 'uid':
                            $wheres .= sprintf(' and svd_by=%d', (int) $v);
                            break;
                        case 'vin':
                            $wheres .= sprintf(" and svd_fromvin LIKE '%s'", $v);
                            break;
                    }
                }
                $wheres .= sprintf(" and svd_id != %d and svd_status=0", $Params['svd_id']);
                $Params['status'] = 0;
                $wheres .= sprintf("  ORDER BY LEFT(svd_fromvin, 8), RIGHT(svd_fromvin, 8) limit 1");
                $nextId = $YpwBase->get($table,['svd_id'],$wheres,true);
                $Params['svd_id'] = $nextId['data']['svd_id'];
				if(!empty($Params['svd_id']))
					LibFc::Go(mvc::$cfg['ADMIN_URI'].'pjlShop/edit?'.http_build_query($Params));
            }
            if($_POST['operation_status'] == 2){

                $_POST['viiids']['0'] = $_POST['svd_id'];
                $this->dateImgsDel();
                foreach($Params as $k => $v)
                {
                    $v = trim($v);
                    if($v == '') continue;
                    switch($k)
                    {
                        case 'uid':
                            $wheres .= sprintf(' and svd_by=%d', (int) $v);
                            break;
                        case 'vin':
                            $wheres .= sprintf(" and svd_fromvin LIKE '%s'", $v);
                            break;
                    }
                }
                $wheres .= sprintf(" and svd_id != %d and svd_status=0", $Params['svd_id']);
                $wheres .= sprintf("  ORDER BY LEFT(svd_fromvin, 8), RIGHT(svd_fromvin, 8) limit 1");
                $nextId = $YpwBase->get($table,['svd_id'],$wheres,true);
                $Params['svd_id'] = $nextId['data']['svd_id'];
				if(!empty($Params['svd_id']))
				{
					unset($Params['from']);
					$Params['status'] = 0;
					LibFc::Go(mvc::$cfg['ADMIN_URI'].'pjlShop/edit?'.http_build_query($Params));
				}
            }
			LibTpl::Success('操作成功');
        }
		$ttime = !empty($data['svd_status']) && !empty($data['svd_etime'])? $data['svd_etime']: time();
        $lastId = $YpwBase->get($table,['svd_id'],sprintf(" and svd_by=%d and svd_status=1 and svd_etime < %d order by svd_etime desc limit 1", $_SESSION['admin_userid'], $ttime),true);
        $last['last_id'] = $lastId['data']['svd_id'] ?: 0;

        $vin = $data['svd_fromvin'];
        $vin18 = substr($vin, 0, 8);
        $v10_11 = substr($vin, 9, 2);
        $v10_12 = substr($vin, 9, 3);
        $v12_17 = substr($vin, 11, 6);
        $v13_17 = substr($vin, 12, 5);
		$twhere = sprintf(" and svd_status=1 and svd_fromvin like '%s_%s%%' and svd_date != ''", $vin18, $v10_12);
		//上面的最小日期
		$res = $YpwBase->get('stand_vin_dateocr', ['svd_date'], $twhere.sprintf(" and right(svd_fromvin, 5) >= '%s' order by right(svd_fromvin, 5) asc limit 1", $v13_17), true);
		if (!empty($res['data']['svd_date']))
		{
			$td = $res['data']['svd_date'];
			$nd = date('Y-m-d', strtotime($td.' -1days'));
			$data['match_date'][$td] = $td;
			$data['match_date'][$nd] = $nd;
		}

		//下面的最大日期
		$res = $YpwBase->get('stand_vin_dateocr', ['svd_date'], $twhere.sprintf(" and right(svd_fromvin, 5) <= '%s' order by right(svd_fromvin, 5) desc limit 1", $v13_17), true);
		if (!empty($res['data']['svd_date']))
		{
			$td = $res['data']['svd_date'];
			$nd = date('Y-m-d', strtotime($td.' +1days'));
			$data['match_date'][$nd] = $nd;
			$data['match_date'][$td] = $td;
		}


			$whereArr = [
				['sma_vin13_17', $v13_17, sprintf(" and sma_vin1_8='%s' and sma_vin10_12='%s' and sma_year != ''", $vin18, $v10_12)],
				['sma_vin12_17', $v12_17, sprintf(" and sma_vin1_8='%s' and sma_vin10_11='%s' and sma_year != ''", $vin18, $v10_11)]
			];
			foreach ($whereArr as $tv)
			{
				$res = $YpwBase->get('stand_model_any', ['sma_year'], $tv[2] . sprintf(" and %s <= '%s' order by %s desc limit 1", $tv[0], $tv[1], $tv[0]), true);
				if (!empty($res['data']['sma_year'])) $data['match_date'][$res['data']['sma_year']] = $res['data']['sma_year'];
				$res = $YpwBase->get('stand_model_any', ['sma_year'], $tv[2] . sprintf(" and %s >= '%s' order by %s asc limit 1", $tv[0], $tv[1], $tv[0]), true);
				if (!empty($res['data']['sma_year'])) $data['match_date'][$res['data']['sma_year']] = $res['data']['sma_year'];
				if (!empty($data['match_date'])) break;
			}

			$res = $YpwBase->get('yp_allvin_base', ['alb_date'], sprintf(" and alb_vin = '%s' and length(alb_date) > 4", $vin), true);
			if(!empty($res['data']['alb_date']) && strlen($res['data']['alb_date']) > 6) $data['match_date'][$res['data']['alb_date']] = $res['data']['alb_date'];

		krsort($data['match_date']);
        LibTpl::Set('last',$last);
        LibTpl::Set('statusArr',[0 => '待处理', 1 => '完成', -1 => '异常']);
        LibTpl::Set('data',$data);
        LibTpl::Set('title','日期识别');
        LibTpl::Set('Params',$Params);
        LibTpl::Put();
    }

    //删除
    public function dateImgsDel()
    {
        LibRule::Check('CA11');
        $id = (int)$_POST['viiids']['0'];
        if($id <= 0) LibFc::ajaxJsonEncode(['status' => 'false','data' => '参数错误']);
        $YpwBase = new YpwBase;
        $table = 'stand_vin_dateocr';
        $imgMd5 = $YpwBase->get($table,['svd_imgmd5'],sprintf(" and svd_id=%d",$id),true);
        if(empty($imgMd5['data']['svd_imgmd5'])) LibFc::ajaxJsonEncode(['status' => 'false','data' => '参数错误']);
        $res = $YpwBase->del($table,sprintf(" and svd_id=%d",$id));
        $res = $YpwBase->del('stand_vin_dateocr_list',sprintf(" and svdl_svd_imgmd5='%s'",$imgMd5['data']['svd_imgmd5']));
        LibFc::ajaxJsonEncode($res);
    }

    //保存
    public function saveDateImage()
    {
     //   LibRule::Check('CA11');
        $id = (int)$_POST['svd_id'];
        if($id <= 0) return ['status' => false,'data' => '参数错误'];
        if(empty($_POST['svd_date']) && $_POST['operation_status'] == 1) return ['status' => false,'data' => '日期不可为空'];
        if(!empty($_POST['svd_date'])){
            $_POST['svd_date'] = date('Y-m-d',strtotime($_POST['svd_date']));
        }
        $data = [
            'svd_date' => $_POST['svd_date'],
            'svd_date_type' => $_POST['svd_date_type'],
            'svd_status' => $_POST['operation_status'] == 1 ? 1 : -1,
            'svd_by' => $_SESSION['admin_userid'],
            'svd_etime' => time()
        ];
        return (new YpwBase)->set('stand_vin_dateocr',$data,sprintf(" and svd_id=%d",$id));

    }

	/**
	 * @method 开店申请详情
	 * @author zhengweihua 
	 * @copyright 2022-07-21
	 */
	public function openShopDetail()
	{
		$Params = mvc::$URL_PARAMS;
		if(empty(LibFc::Int($Params['shop_id'])))
		{
			$error = false;
		}
		$LibYpApi = new LibYpApi();
		// 编辑店铺信息
		if($_SERVER['REQUEST_METHOD'] == 'POST'&&LibFc::Int($_POST['data']['shop_id']))
		{
		}

		$shopMsg = $LibYpApi->get('pjl/getShopByWhere',['where'=>'and shop_id='.$Params['shop_id'],'oneRow'=>true]);
		$shopMsg = $shopMsg['data'];

		//营业信息
		if(!empty($shopMsg['shop_license']))
			$shopMsg['shop_license'] = json_decode($shopMsg['shop_license'],true);

		//审核信息
		if(!empty($shopMsg['shop_checkby']))
			$shopMsg['shop_checkby'] = json_decode($shopMsg['shop_checkby'],true);

		//公司门面图
		if(!empty($shopMsg['shop_img']))
			$shopMsg['shop_img'] = array_filter(explode(',', $shopMsg['shop_img']));
		
		//下一个
		$where = '';
		if($Params['status']){

			$where .=sprintf(' and shop_status=%d',$Params['status']);
		}

		$PjlBase= new PjlBase();
		$where1 = $where.sprintf(" and shop_id>%d  order by shop_id asc limit 1",LibFc::Int($Params['shop_id']));
		$afterOne =$PjlBase->get('pl_shop',['shop_id'],$where1,true);
		$where2 = $where.sprintf(" and shop_id<%d  order by shop_id desc limit 1",LibFc::Int($Params['shop_id']));
		$prevOne = $PjlBase->get('pl_shop',['shop_id'],$where2,true);

		$statusArr = [
			'2'=>'审核通过',
			'-1'=>'审核不通过',
			'0'=>'填写资料中',
			'1' =>'等待审核',
		];
		LibTpl::Set('statusArr',$statusArr);
		LibTpl::Set('prevOne',$prevOne['data']['shop_id']?:0);
		LibTpl::Set('afterOne',$afterOne['data']['shop_id']?:0);
		LibTpl::Set('reasonArr',$this->reasonArr);
		LibTpl::Set('data', $shopMsg);
		LibTpl::Set('error',$error);
		LibTpl::Set('title','开店申请详情');
		LibTpl::Put();
	}

	/**
	 * @method 批量删除VIN纠错记录
	 * @author zhengweihua 
	 * @copyright 2022-09-21
	 */
	public function batchDelVinError()
	{
		LibRule::Check('CA03');
		if($_SERVER['REQUEST_METHOD'] != "POST")  LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'请求错误'));
		
		if(empty($_POST['veids']))
		{
			LibFc::ajaxJsonEncode(array('status'=>false,'data'=>'删除失败'));
		}
		$vidArr = $_POST['veids'];
		if(!is_array($_POST['veids'])){
			$vidArr = [$_POST['veids']];
		}
		$PjlBase= new PjlBase();
		$res=$PjlBase->del('pl_vin_error',sprintf(' and ve_id in (%s)',implode(',',$vidArr) ));
		LibFc::ajaxJsonEncode($res);	
	}

	/**
	 * @method 报价分类
	 * @author zhengweihua 
	 * @copyright 2023-04-08
	 */
	public function bjPart()
	{	
		$Params = mvc::$URL_PARAMS;	
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		
		$PjlBase= new PjlBase();
	
		$partArr = [];
		$sres = $PjlBase->get('pl_part', ['*']," order by part_parent asc");
		foreach ($sres['data'] as $key => $val) {
			if(!$val['part_parent']){
				$partArr[$val['part_id']] = $val;
			}else{
				$partArr[$val['part_parent']]['children'][] = $val;
			}
		}
		array_multisort(array_column($partArr,'part_seq'),SORT_ASC,$partArr);
		LibTpl::Set('partArr', $partArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','报价分类列表');
		LibTpl::Put();
	}

	/**
	 * @method 编辑报价分类
	 * @author zhengweihua 
	 * @copyright 2023-04-08
	 */
	public function setBjPart()
	{	
		$PjlBase= new PjlBase();
		if($_SERVER['REQUEST_METHOD']=='POST' && $_POST){
			$reArr = ["\r\n", "\n",'，', ',', '；'];

			$data = [
				'part_parent'=>$_POST['part_parent'],
				'part_name'=>$_POST['part_name'],
				'part_keyword'=> str_replace($reArr, ',', $_POST['part_keyword']),
				'part_seq'=>$_POST['part_seq']??999
			];
			if($_POST['part_id']){
				$recordRes = $PjlBase->get('pl_part',['count(*) as count'],sprintf(" and part_parent =%d",LibFc::Int($_POST['part_id'])),true);
				if($recordRes['data']['count']>0 && $data['part_parent']>0){
					return LibFc::ReturnJson(false,'当前仅支持二级分类,该分类存在下级分类，请先移除下级分类');
				}
				$res = $PjlBase->set('pl_part',$data,sprintf(" and part_id=%d",LibFc::Int($_POST['part_id'])));
			}else{
				$res = $PjlBase->add('pl_part',$data);
			}
			LibFc::ajaxJsonEncode($res);
		}
		
		$Params = mvc::$URL_PARAMS;
		$partInfo = [
			'part_parent'=>isset($Params['part_parent'])?$Params['part_parent']:0
		];
		if($Params['part_id']){
			$res = $PjlBase->get('pl_part',['*'],sprintf(" AND part_id=%d",LibFc::Int($Params['part_id'])),true);
			$partInfo = $res['data'];
		}
		LibTpl::Set('partInfo',$partInfo);
		$res = $PjlBase->get('pl_part', ['part_id,part_name'], " AND part_parent=0");
		LibTpl::Set('parentArr', $res['data']?array_column($res['data'],'part_name','part_id'):[]);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','编辑报价分类');
		LibTpl::Put();
	}

	/**
	 * @method 删除报价配件
	 * @author zhengweihua 
	 * @copyright 2023-04-08
	 */
	public function delBjPart()
	{
		$Params = mvc::$URL_PARAMS;
		if(!$Params['part_id']) return LibFc::ReturnJson(false,'参数错误');
		$part_id = LibFc::Int($Params['part_id']);
		$PjlBase= new PjlBase();
		$res =	$PjlBase->del('pl_part',sprintf(" AND part_id = %d",$part_id));
		LibFc::ajaxJsonEncode($res);	
	}

	/**
	 * @method 更改排序
	 * @author zhengweihua 
	 * @copyright 2023-04-08
	 */
	public function changePartSeq()
	{
		$Params = MVC::$URL_PARAMS;
		if($Params['part_id']&&$Params['part_seq'])
		{
			$PjlBase = new PjlBase();
			$res = $PjlBase->set('pl_part',['part_seq'=>$Params['part_seq']],sprintf(" and part_id=%d",LibFc::Int($Params['part_id'])));
			LibFc::ajaxJsonEncode($res);
		}
		return LibFc::ReturnJson('false','参数错误');
	}

	/**
	 * @method 业务员跟进统计
	 * @author zhengweihua 
	 * @copyright 2023-05-30
	 */
	public function followTj()
	{
		$Params = mvc::$URL_PARAMS;
		$data  = ['atime'=>date('Y-m-1').' ~ '.date('Y-m-d')];
		if($Params['atime'])
		{
			$data['atime'] = $Params['atime'];
		}else{
			$Params['atime'] = $data['atime'];
		}
		$listArr = [];
		$LibCrmApi = new LibCrmApi();
		$res = $LibCrmApi->Get('cus/getFollowTj',$data);
		$listArr = $res['data'];
		LibTpl::Set('listArr',$listArr);
		LibTpl::Set('Params', $Params);
		LibTpl::Set('title','业务员跟进统计');
		LibTpl::Put();
	}

	/**
	 * @method 通过接口开通微信机器人
	 * @author zhengweihua 
	 * @copyright 2024-06-14
	 */
	public function openWxRobot()
	{
		if($_SERVER['REQUEST_METHOD']=='POST'){
			$shop_id =	(int)$_POST['shop_id'];
			if(!$shop_id) LibFc::ReturnJson(false,'参数错误');
			$LibYpApi = new LibYpApi();
			$res = $LibYpApi->Get('pjl/autoSetWxRobot',['shop_id'=>$shop_id],[]);
			LibFc::ajaxJsonEncode($res);
		}
	}
}
