<?php

// require './vendor/autoload.php';
// use PhpOffice\PhpSpreadsheet\Spreadsheet;
// use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class pjlProductAction extends baseAction
{
	/**
	 * @产品主页
	 * @author 卢
	 * @copyright 2017.7.31
	 */
	function index()
	{
		LibRule::Check('JP01');
		LibTpl::Set('title','询价列表-跑街令');

		LibTpl::Put();
	}
	/**
	* @产品列表
	* @author 卢
	* @copyright 2017.7.31
	 */
	function productList()
	{
		LibRule::Check('JP01');
		$Params = MVC::$URL_PARAMS;
		$columnArr=[
			['name'=>'ID','key'=>'pur_id','width'=>50],
			['name'=>'状态','key'=>'pur_status','width'=>50],
			['name'=>'报价单','key'=>'po_count','width'=>60],
            ['name'=>'电话','key'=>'call_count','width'=>40],
			['name'=>'标题','key'=>'pur_title','width'=> 250],
			['name'=>'车型','key'=>'pur_model','width'=> 350],
			['name'=>'产品数','key'=>'count','width'=>50],
			['name'=>'图片','key'=>'pur_imgs','width'=>300],
			['name'=>'发布者','key'=>'pur_pu_id','width'=>200],
            ['name' => '时间','key' => 'time','width' => 120]
		];
		// -1已关闭 0询价中 1已完成-2已过期
		$statusColor = [
			'-2'=>'red',
			'-1'=>'orange',
			'0'=>'#009bdcc4',
			'1'=>'green',
		];
		LibTpl::Set('statusColor',$statusColor);

		LibTpl::Set('columnArr',$columnArr);
		$page=isset($Params['page']) ? $Params['page'] : 1;
		$where='';
		//var_dump($Params);exit();
		//状态
		$where.=(isset($Params['status'])&&$Params['status']!=='all') ? ' and pur_status='.$Params['status']: '';
		//id
	//	$where.=(!empty($Params['pur_pu_id'])) ? ' and pur_pu_id='.(int)$Params['pur_pu_id']: '';
		$where.=(!empty($Params['pur_id'])) ? ' and pur_id='.(int)$Params['pur_id']: '';
		//添加时间
		$where.=!empty($Params['addTime'])?sprintf(' and pur_atime>=%d',strtotime($Params['addTime'])):'';
		$where.=!empty($Params['endTime'])?sprintf(' and pur_atime<=%d',strtotime($Params['endTime'])):'';
	    $where .= !empty($Params['pur_title']) ? sprintf(" and pup_name like '%%%s%%'",LibFc::Escape($Params['pur_title'])) : '';
	    if(isset($Params['baojia']) && $Params['baojia'] > 0){
	        if($Params['baojia'] == 1){
	            $where .= sprintf(" and pur_id in(select po_pur_id from pl_purchase_offer)");
            }elseif ($Params['baojia'] == 2){
                $where .= sprintf(" and pur_id not in(select po_pur_id from pl_purchase_offer)");
            }
        }
        if(isset($Params['iphone']) && $Params['iphone'] > 0){
            if($Params['iphone'] == 1){
                $where .= sprintf(" and pur_id in(select puca_pur_id from pl_purchase_call)");
            }elseif ($Params['iphone'] == 2){
                $where .= sprintf(" and pur_id not in(select puca_pur_id from pl_purchase_call)");
            }
        }
        $LibYpApi = new LibYpApi();
	    if(LibFc::Escape($Params['pur_pu_id'])){

            $post = [
                'filed'=>['u_id'],
                'where'=>sprintf(" and u_name like '%%%s%%' or u_mobile like '%%%s%%'", LibFc::Escape($Params['pur_pu_id']), LibFc::Escape($Params['pur_pu_id'])),
                'oneRow'=>true
            ];
            $res = $LibYpApi->Get('user/getUser',[], $post);
            if($res['data']['u_id']){
                $where .= sprintf(" and pur_pu_id=%d",$res['data']['u_id']);
            }else{
                $where .= sprintf(" and pur_pu_id > 0");
            }
        }

		//排序
		$orderBy=isset($Params['orderBy']) ? $Params['orderBy'] : 'tdesc';
		switch ($orderBy) {
			case 'tdesc':
				$order=' order by pur_atime desc';
				break;
			case 'tasc':
				$order=' order by pur_atime asc';
				break;
			case 'wasc':
				$order=' order by pur_ok_time asc';
				break;
			case 'wdesc':
				$order=' order by pur_ok_time desc';
				break;
			default :
				$order=' orcer by pur_atime desc';
		}
		if(isset($_SESSION['pjlChkIds'])&&$Params['select'])
		{
			$idsArr=array_filter($_SESSION['pjlChkIds']);
			if(!empty($idsArr))
			{
				$where=sprintf(' and pur_id in (%s)',implode(',',$idsArr));
			}
		}

		$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;

        $PjlBase = new PjlBase();
        $res = $PjlBase->get(sprintf("(SELECT count(*) count FROM pl_purchase LEFT JOIN pl_purchase_product ON pur_id = pup_pur_id WHERE 1 = 1 %s GROUP BY pur_id) as tt",$where), ['count(*) as count'],'',true);
        $Page = LibPage::Show($res['data']['count'], $perPage);
		if($res['data']['count']>0)
		{

            $where .= ' group by pur_id '.$order;

            $where .= sprintf(' limit %d,%d',($page-1)*$perPage,$perPage);

            $res = $PjlBase->get('pl_purchase left join pl_purchase_product on pur_id=pup_pur_id',['pl_purchase.*,group_concat(pup_name) as pur_title'],$where);


			$list = $res['data'];
			$purIdArr = array_column($res['data'], 'pur_id');

			$brandIdArr = array_column($list, 'pur_brand_id');

			$userIdArr = array_column($list, 'pur_pu_id');

			$LibYpApi = new LibYpApi();
			//品牌
			if(!empty($brandIdArr))
			{
				$postArr = [
					'filed'=>['brand_id', 'brand_name', 'brand_code'],
					'where'=>sprintf(" and brand_id in(%s)", implode(',',$brandIdArr)),
					'oneRow'=>false
				];
				$res = $LibYpApi->Get('ypc2/getBrand', [], $postArr);
				$brandArr=array_column($res['data'], null,'brand_id');
			}
			//发布者
			if(!empty($userIdArr))
			{
				$post = [
					'filed'=>['u_name','u_id'],
					'where'=>sprintf(" and u_id in(%s)", implode(',',$userIdArr)),
					'oneRow'=>false
				];
				$res = $LibYpApi->Get('user/getUser',[], $post);

				$userArr = array_column($res['data'],null, 'u_id');
			}

			//报价数量
			$res = $LibYpApi->Get('pjl/getPurchaseOfferByWhere',['where'=>sprintf(' and po_pur_id in(%s) group by po_pur_id',implode(',',$purIdArr)),'fields'=>'count(1) count,po_pur_id']);
			$offerTotal = array_column($res['data'],'count' ,'po_pur_id');


            //询价单配件
            $proArr=[];
            $res = $LibYpApi->Get('pjl/getPurchaseProductByIds',['ids'=>$purIdArr]);
            foreach ($res['data'] as $v)
            {
                $proArr[$v['pup_pur_id']][]=$v;
            }

			LibTpl::Set('offerTotal',$offerTotal);
			$nowtime=time();

			$res = (new PjlBase)->get('pl_purchase_call',['count(*) as count','puca_pur_id'],sprintf(' and puca_pur_id in(%s) group by puca_pur_id',implode(',',$purIdArr)));
			if(!empty($res['data'])){
			    $productCall = array_column($res['data'],'count','puca_pur_id');
            }else{
			    $productCall = [];
            }
			foreach ($list as $k=> $v)
			{
			    if(isset($productCall[$v['pur_id']])){
                    $list[$k]['call_count'] = $productCall[$v['pur_id']];
                }
				//图片
				if(!empty($v['pur_imgs']))
				{
					$imgArr=array_filter(explode(',',$v['pur_imgs']));
					$list[$k]['pur_imgs'] = array_map(function($value){
							return mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=purchase&f='.$value.mvc::$cfg['FILE_CENTER']['pjl']['get_uri'];
						}, $imgArr);
				}
				//品牌
				if(!empty($brandArr[$v['pur_brand_id']]))
				{
					$list[$k]['brand_name']=$brandArr[$v['pur_brand_id']]['brand_name'];
				}
				//发布者
				if(!empty($userArr[$v['pur_pu_id']]))
				{
					$list[$k]['u_name']=$userArr[$v['pur_pu_id']]['u_name'];
				}
				$res = $LibYpApi->Get('pjl/getAddrByIds',['ids'=>$v['pur_pct_ids']]);
				if(!empty($res['data']))
				{
					$list[$k]['city']= implode(' ', $res['data']);
				}
				if(!empty($proArr[$v['pur_id']])){
                    $list[$k]['count'] = array_sum(array_column($proArr[$v['pur_id']], 'pup_count'));
                }else{
                    $list[$k]['count' ]= 0;

                }
				//计算距离今天天数
				$list[$k]['addDay']=round(($nowtime-$v['pur_atime'])/(24*60*60));

				$list[$k]['editDay']=round(($nowtime-$v['pur_close_time'])/(24*60*60));

				$list[$k]['okDay']=round(($nowtime-$v['pur_ok_time'])/(24*60*60));
			}

			LibTpl::Set('productList',$list);
		}
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title','配件列表-跑街的');
		LibTpl::Put();
	}
	/**
	* @搜索页面
	* @author 卢
	* @copyright 2017.7.31
	 */
	function  productSearch ()
	{
		LibRule::Check('JP01');
		$data=[
			['name'=>'报价单数','id'=>'po_count'],
			['name'=>'图片','id'=>'pur_imgs'],
			['name'=>'VIN','id'=>'pur_vin'],
			['name'=>'品牌','id'=>'pur_brand_id'],
			['name'=>'车型','id'=>'pur_model'],
			['name'=>'地区','id'=>'pur_pct_ids'],
			['name'=>'发布者','id'=>'pur_pu_id'],
			['name'=>'产品数量','id'=>'count'],
			['name'=>'时间','id'=>'time'],
			// ['name'=>'标题','id'=>'pur_title'],

		];
		$paramsArr=[
			'id'=>'showColumn',
			'type'=>'checkbox',
			'show_name'=>'name',
			'width'=>85,
			'data_key'=>'id',
			'data_value'=>['key','id'],
			'data_check'=>['pur_id','pur_status','pur_title','pur_imgs','pur_vin','pur_brand_id','pur_model','pur_pct_ids','pur_pu_id','count','time'],
			'callback'=>'putIntoCheckColumn',
			'unCheckCallback'=>'putIntoCheckColumn',
		];
		$columnArrDefault=[
			'pur_id',
			'pur_status',
			'pur_title',
			'pur_imgs',
			'pur_model',
			'pur_pct_ids',
			'pur_pu_id',
			'time'
		];
		if(isset($_COOKIE['showColumn']))
		{
			foreach ($data as $k=> $v)
			{
				if(in_array($v['id'], explode(',', $_COOKIE['showColumn'])))
				{
					$data[$k]['check']=true;
				}
			}
		}else
		{
			foreach ($data as $k=> $v)
			{
				if(in_array($v['id'], $columnArrDefault))
				{
					$data[$k]['check']=true;
				}
			}
		}
		LibTpl::Set('params',$paramsArr);
		LibTpl::Set('data',$data);
		// LibTpl::Set('shopArr',$shopData['data']);
		LibTpl::Set('partArr',$res['data']);
		LibTpl::Set('title','产品列表-跑街的');
		LibTpl::Put();
	}
	/**
	* @ajax 处理选中产品
	* @author 卢
	* @copyright 2017.7.31
	 */
	function ajaxProCheck()
	{
		$proId=trim($_POST['ChkIds'],',');
		$notCheck=trim($_POST['NotChkIds'],',');
		if(isset($_SESSION['pjlChkIds']))
		{
			$_SESSION['pjlChkIds']=array_unique(array_merge(explode(',', $proId),$_SESSION['pjlChkIds']));
			foreach ($_SESSION['pjlChkIds'] as $k => $v)
			{
				if(in_array($v, explode(',', $notCheck)))
				{
					unset($_SESSION['pjlChkIds'][$k]);
				}
			}
		}
		else
		{
			$_SESSION['pjlChkIds']=explode(',', $proId);
		}

		$purIdArr = array_filter($_SESSION['pjlChkIds']);
		if(!empty($purIdArr))
		{
			$LibYpApi = new LibYpApi();
			$res = $LibYpApi->Get('pjl/getPurchaseByIds',['ids'=>$purIdArr]);
			$proArr = $LibYpApi->Get('pjl/getPurchaseProductByIds',['ids'=>$purIdArr]);
			$proArr = $proArr['data'];
			$tempArr = [];
			if(!empty($proArr))
			{
				foreach ($proArr as $v)
				{
					$tempArr[$v['pup_pur_id']][]=$v;
				}
			}
			foreach ($res['data'] as $k=>$v)
			{
				if(!empty($tempArr[$v['pur_id']]))
				{
					$res['data'][$k]['title']=implode(',',array_column($tempArr[$v['pur_id']], 'pup_name'));
				}
			}
		}
		$data=array('status'=>true,'data'=>array('check'=>$res['data']));
		LibFc::ajaxJsonEncode($data);
	}
	/**
	* @ajax 改变产品状态
	* @author 卢
	* @copyright 2017.7.31
	 */
	function ajaxChangePro()
	{
		LibRule::Check('PL02');
		if(isset($_POST['status']))
		{
			$B2cProduct=new B2cProduct();
			$proId=$_POST['proId'];
			$remark=$_POST['remark'];
			$B2cProduct->adminChangePro($proId,$_POST['status'],$remark);
		}
		LibFc::ajaxJsonEncode(array('status'=>true,'data'=>true));
	}
	function deleteCheck()
	{
		$proArr=$_POST['proId'];
		$remark=$_POST['remark'];
		if(!empty($proArr))
		{
			$postArr=[
				'purArr'=>$proArr,
				'remark'=>$remark
			];
			$LibYpApi=new LibYpApi();
			$res = $LibYpApi->Get('pjl/deletePur', [], $postArr);
			LibFc::ajaxJsonEncode($res);
		}
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'询价单ID不能为空']);
	}
	/**
	* @ajax更新选中产品的session
	* @author 卢
	* @copyright 2017.7.31
	 */
	function updateCheck()
	{
		if(!is_array($_POST['proId']))
		{
			$proId=trim($_POST['proId'],',');
			$proId=[$proId];
		}
		else
		{
			$proId=$_POST['proId'];
		}
		if(isset($_SESSION['pjlChkIds']))
		{
			foreach ($_SESSION['pjlChkIds'] as $k => $v)
			{
				if(in_array($v, $proId))
				{
					unset($_SESSION['pjlChkIds'][$k]);
				}
			}
		}
		LibFc::ajaxJsonEncode(array('status'=>true,'data'=>true));
	}


	/**
	* @刷新关键词
	* @author xu
	* @copyright 2017.12.20
	 */
	function  refreKeyword ()
	{
		LibRule::Check('KW01');
		LibTpl::Set('title','刷新关键词-跑街的');
		LibTpl::Put();
	}


	/**
	* @刷新店铺关键字
	* @author xu
	* @copyright 2017.12.20
	 */
	function resetShopKeyword()
	{
		LibRule::Check('KW03');
		// 店铺ID
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_shop',['shop_id'],sprintf(" and shop_status>0 "));
		$shopId = array_column($res['data'], 'shop_id');
		// 接口刷新
		$B2cKeyword = new B2cKeyword();
		$B2cKeyword->resetShopKeyword($shopId);

		echo "刷新店铺关键字成功！";
	}


	/**
	* @刷新产品关键字
	* @author xu
	* @copyright 2017.12.20
	 */
	function resetAllProductKeyword()
	{
		LibRule::Check('KW02');
		$time = time();
		$B2cKeyword = new B2cKeyword();
		$B2cKeyword->resetProductKeyword([], 'all');
		//$B2cKeyword->resetProductKeyword([223014], 'shopId');
		echo time() - $time;
		echo "刷新产品关键字完毕！";
	}


	/**
	 * @method 根据配件的主号码更新配件的互换号
	 * @author soul
	 * @copyright 2018/3/17
	 */
	function resetNumByMainNum()
	{
		$B2cProduct=new B2cProduct();
		$res = $B2cProduct->resetNumByMainNum(explode(',', $_POST['proIds']), $_POST['keep']);
		LibFc::ajaxJsonEncode($res);
	}


	/**
	 * @method 批量整理产品
	 * @author soul
	 * @copyright 2018/3/17
	 */
	function batchAct()
	{
		LibRule::Check('KW04');
		$Params = MVC::$URL_PARAMS;
		$shopId = (int) $Params['shopId'];
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('sh_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);

		$excelType = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
		if(!empty($_POST['type']))
		{
			switch($_POST['type'])
			{
				case 'proData':
					if(!empty($_FILES['excel']['tmp_name']) && in_array($_FILES['excel']['type'], $excelType))
					{
						$OthExcel = new OthExcel();
						$colHeader = [
							'pro_id'=>['name'=>'配件ID'],
							'pro_name'=>['name'=>'配件名称'],
							'part_name'=>['name'=>'配件分类'],
							'part_param'=>['name'=>'配件分类参数'],
							'pro_brand'=>['name'=>'配件品牌'],
							'pri_code'=>['name'=>'自编号'],
							'main_number'=>['name'=>'主号码'],
							'pro_number'=>['name'=>'互换号'],
							'pro_param'=>['name'=>'自定义参数'],
							'pro_sale_price'=>['name'=>'销售价'],
							'pro_count'=>['name'=>'库存'],
							'shop_sort'=>['name'=>'店铺分类'],
							'pro_sel_des'=>['name'=>'卖点'],
							'pri_des'=>['name'=>'描叙'],
							'freight'=>['name'=>'运费模板'],
							'publish'=>['name'=>'发布时间']
						];
						$res = $OthExcel->read($_FILES['excel']['tmp_name'], 0, array_keys($colHeader));
						$proArr = $res['data'];
						$B2cProduct = new B2cProduct();
						$res = $B2cProduct->importProduct($shopData['shop_id'], $proArr, $_POST['unique']);
						$result = $res['data'];
						LibTpl::set('result', $result);
					}
					else
					{
						LibTpl::Error('获取上传表格失败！');
					}
				break;
				case 'proImg':
					if(empty($_POST['imgfile']))
					{
						LibTpl::Error('获取图片压缩包失败！');
					}
					if(!empty($_FILES['excel']['tmp_name']) && in_array($_FILES['excel']['type'], $excelType))
					{
						$OthExcel = new OthExcel();
						$colHeader = [
							'pro_id'=>['name'=>'配件ID'],
							'pri_code'=>['name'=>'自编号'],
							'main_number'=>['name'=>'主号码'],
							'images'=>['name'=>'图片名称']
						];
						$res = $OthExcel->read($_FILES['excel']['tmp_name'], 0, array_keys($colHeader));
						$proArr = $res['data'];
						$B2cProduct = new B2cProduct();
						$res = $B2cProduct->importProductImg($shopData['shop_id'], mvc::$cfg['PATH_ROOT'].'tmp/'.$_POST['imgfile'], $proArr);
						$result = $res['data'];
						LibTpl::set('result', $result);
					}
					else
					{
						LibTpl::Error('获取上传表格失败！');
					}
				break;
			}

		}
		LibTpl::Set('title', $shopData['shop_name'].'-产品批量管理-跑街的');
		LibTpl::Put();
	}

	/**
	 * @method    获取车型
	 * @author 卢
	 * @copyright 2018-04-26
	 */
	function getModel()
	{
		$Params = MVC::$URL_PARAMS;
		$ComModel=new ComModel();
		if(empty($Params['level'])||false===LibFc::Int($Params['pid']))
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误']);
		}
		// print_r($res);
		$where='';
		switch ($Params['level'])
		{
			case '1':
				$res=$ComModel->getAllBrand(false);
				if(!empty($res['data']))
				{
					$sort=array_column($res['data'], 'brand_initial');
					array_multisort($sort,SORT_ASC,$res['data']);
				}
			break;
			case '2':
				$res=$ComModel->getModel(1,['distinct make_id','make_name'],sprintf(' and mod1_brand_id=%d order by brand_seq, brand_initial',$Params['pid']));
				// $where=sprintf(' and mod2_mod1_id=%d',$Params['pid']);
				break;
			case '3':
				$res=$ComModel->getModel(1,['*'],sprintf(' and mod1_make_id=%d order by brand_seq, brand_initial, make_seq, make_initial, mod1_name',$Params['pid']));
				break;
			case '4':
				$res=$ComModel->getModel(2,['*'],sprintf(' and mod2_mod1_id=%d order by mod1_name, mod2_name, mod2_start_year',$Params['pid']));
				break;
			case '5':
				$res=$ComModel->getModel(3,['*'],sprintf(' and mod3_mod2_id=%d order by mod2_name, mod2_start_year, mod3_name, mod3_start_year',$Params['pid']));
				//LibFc::formatViewYear($v['MOD3_START_YEAR'], $v['MOD3_END_YEAR'], 2)
				if(!empty($res['data']))
				{
					foreach ($res['data'] as $k => $v)
					{
						$res['data'][$k]['year']=LibFc::formatViewYear($v['mod3_start_year'], $v['mod3_end_year'], 2);
					}
				}
				break;
		}
		LibFc::ajaxJsonEncode($res);
	}
	/**
	 * @method    配件基本信息
	 * @author 卢
	 * @copyright 2018-04-27
	 */
	function productInfo()
	{
		$Params = MVC::$URL_PARAMS;
		$B2cBase = new B2cBase();
		$B2cBrand=new B2cBrand();
		$B2cProduct = new B2cProduct();
		$B2cPart  = new B2cPart();
		$B2cShopSort = new B2cShopSort();
		if(!empty($Params['proId']))
		{
			$proId = (int) $Params['proId'];
			$res = $B2cProduct->getProduct(['*'], sprintf(" and pro_id = %d", $proId), true);
			$proArr['base'] = $res['data'];
			//产品不存在
			if(empty($proArr['base']))
			{
				LibTpl::Error('配件不存在');
				exit();
			}
			//配件品牌
			if($proArr['base']['pro_prb_id'])
			{
				$brandNowData=$B2cBase->get('bc_probrand',['prb_id','prb_name'],sprintf(' and prb_id=%d',$proArr['base']['pro_prb_id']),true);
				$proArr['nowBrand']=$brandNowData['data'];
			}
			$brandData=$B2cBrand->get('sh_probrand_link left join bc_probrand on sprl_prb_id=prb_id',['prb_id','prb_name'],sprintf(' and sprl_shop_id=%d order by sprl_seq asc',$_SESSION['_shopid']));
			if(count($brandData['data']))
			{
				$proArr['brandArr']=$brandData['data'];
			}
			$res = $B2cPart->getAllPart();
			$AllPart = $res['data'];

			$proArr['partNames'] = [];
			foreach(explode(',', $proArr['base']['pro_part_path']) as $v)
			{
				if(!empty($AllPart[$v]))
				{
					$proArr['partNames'][] = $AllPart[$v]['part_name'];
				}
			}
			//分类参数
			$res = $B2cPart->getPartParam($proArr['base']['pro_part_id']);
			// print_r($res);
			$ParaArr=$res['data'];
			$sort=array();
			if(count($ParaArr))
			{
				$sort=array_column($ParaArr, 'ppl_seq');
				array_multisort($sort, SORT_ASC, $ParaArr);
				// print_r($ParaArr);
				// die;
				$valRes=array_column($ParaArr, 'pal_id');
				$res=$B2cPart->get('bc_param_value',['pav_id','pav_part_id','pav_pal_id','pav_seq','pav_value'],sprintf(' and pav_pal_id IN(%s)',implode(',', $valRes)));
				$sort=[];
				$valRes=[];
				if(count($res['data']))
				{
					foreach ($res['data'] as $v)
					{
						$valRes[$v['pav_pal_id']][]=$v;
						$sort[$v['pav_pal_id']][]=$v['pav_seq'];
					}
					// print_r($valRes);
					foreach($ParaArr as $K=>$V)
					{
						if(isset($valRes[$V['pal_id']]))
						{
							array_multisort($sort[$V['pal_id']], SORT_ASC, $valRes[$V['pal_id']]);
							$ParaArr[$K]['valArr']=$valRes[$V['pal_id']];
						}
					}
				}
			}
			// print_r($ParaArr);
			$proArr['partParam'] = $ParaArr;
			$proArr['modelId'] = ['m1'=>[], 'm2'=>[], 'm3'=>[]];

			//配件已有数据
			if($proArr['base']['pro_id'] > 0)
			{
				//参数
				$res = $B2cProduct->getProductParam($proArr['base']['pro_id']);
				$proArr['param'] = $res['data'];
				// print_r($proArr['param']);
				//图片
				$res = $B2cProduct->getProductPic($proId, true);
				$proArr['imgs'] = $res['data'];



				//店铺分类
				$res = $B2cBase->getFieldUniVal('bc_product_sort', 'prs_sort_id', sprintf(" and prs_pro_id=%d", $proId));
				$hasShopSortId = $res['data'];
				$res=$B2cShopSort ->getAllShopSort($proArr['base']['pro_shop_id'],false);
				$sortNameArr=[];
				if(!empty($hasShopSortId))
				{
					foreach ($hasShopSortId as $id)
					{
						$sortNameArr[]=$res['data'][$id]['sort_name'];
					}
				}
				LibTpl::Set('sortNameArr',$sortNameArr);
			}
			$proArr['base']['pri_publish_time'] = isset($proArr['base']['pri_publish_time'])? $proArr['base']['pri_publish_time']: time();

			$imgCount = !empty($proArr['imgs']) ? count($proArr['imgs']): 0;
			for($i = $imgCount; $i < 5; $i++)
			{
				$proArr['imgs'][$i] = [];
			}
			LibTpl::Set('proArr', $proArr);
			// print_r($proArr);
			// $res=$B2cBase->get('bc_product',['pro_ppt_id'],sprintf(' and pro_shop_id=%d and pro_id=%d',$_SESSION['_shopid'],$Params['proId']),true);
			if($proArr['base']['pro_ppt_id'])
			{
				$tplId=$proArr['base']['pro_ppt_id'];
				$proId=$Params['proId'];
				//有值的
				$feild = ['prpv_prl_id', 'prpv_pru_id', 'prpv_value','prl_name','pru_name'];
				$res=$B2cBase->get('bc_product_para_val join bc_product on pro_id= prpv_pro_id left join bc_product_label on prl_id=prpv_prl_id left join bc_product_unit on pru_id=prpv_pru_id', $feild, sprintf(" and pro_id=%d and pro_ppt_id =%d and pro_shop_id=%d and (prpv_value is not null or prpv_value!='')", $proId, $tplId, $proArr['base']['pro_shop_id']));
				// print_r($res);
				$oldValArr = [];
				$oldValArr=array_column($res['data'], null,'prpv_prl_id');
				// print_r($oldValArr);
				//新的
				$fieldArr=['pptl_ppt_id','prl_id','pru_id','pptl_seq','prl_name','pru_name'];
				$newlink=$B2cBase->get('bc_product_para_tpl_link left join bc_product_label on prl_id=pptl_prl_id left join bc_product_unit on pru_id=pptl_pru_id',$fieldArr,sprintf(' and pptl_ppt_id=%d order by pptl_seq asc,pptl_prl_id asc',$tplId));
				$newArr=array_column($newlink['data'], null,'prl_id');
				// print_r($newArr);
				if(count($oldValArr))
				{
					foreach ($oldValArr as $k => $v)
					{
						$newArr[$k]=isset($newArr[$k])?array_merge($v,$newArr[$k]):$v;
					}
				}
				// print_r($newArr);
			}
			LibTpl::Set('paramArr', $newArr);
			// 会员等级信息
			$B2cShop = new B2cShop();
			$res = $B2cShop->getMemberSetting($proArr['base']['pro_shop_id']);
			// var_dump($res);
			LibTpl::Set('memberSetting',$res['data']);
			$is_show = array_filter(array_column($res['data'], 'mem_status'));
			LibTpl::Set('memberSettingHide',empty($is_show)?1:0);
			//运费获取
			$templateId=$proArr['base']['pri_frt_id'];
			if((int)$templateId)
			{
				$B2cFreight=new B2cFreight();
				$YpwAddr= new YpwAddr();
				$res=$B2cFreight->getSellerTemplateList($proArr['base']['pro_shop_id'],$templateId);
				// print_r($res);
				$tplData=[];
				if(!empty($res['data']))
				{
					$tplArr=$res['data'][0];
					$data=$YpwAddr->getAddrByIds($tplArr['frt_send_pct']);
					$tplData['cityName']=implode('',$data['data']);
					$tplData['frt_is_free']=$tplArr['frt_is_free'];
					$tplData['frt_name']=$tplArr['frt_name'];
					$tplData['frt_valuation_method']=$tplArr['frt_valuation_method'];
					$tplData['frt_send_hour']=$tplArr['frt_send_hour'];
					$tplData['frt_send_pct']=$tplArr['frt_send_pct'];
					foreach ($tplArr['link'] as $k => $v)
					{
						$tplData['link'][$v['ftl_shipping_method']][]=$v;
					}
				}
				// print_r($tplData);
				LibTpl::Set('tplData',$tplData);
			}
			//售后模板
			if($proArr['base']['pri_service_pdt_id'])
			{
				$res=$B2cBase->get('bc_product_desc_tpl',['pdt_name','pdt_id'],sprintf(' and pdt_id=%d',$proArr['base']['pri_service_pdt_id']),true);
				LibTpl::Set('serviceTpl',$res['data']);
			}
			//橱窗数量
			$res = $B2cBase->get('sh_shop', ['shop_window_count'], sprintf(" and shop_id=%d", $proArr['base']['pro_shop_id']), true);
			$shopInfo = $res['data'];

			LibTpl::Set('shopInfo', $shopInfo);
			LibTpl::Set('title','配件信息-跑街的');
			LibTpl::Put();
			exit();
		}
		LibTpl::Error('配件不存在');
	}
	/**
	 * @method    配件车型/号码
	 * @author 卢
	 * @copyright 2018-04-27
	 */
	function productNum()
	{
		$Params = MVC::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cBase = new B2cBase();
			$res=$B2cBase->get('bc_product',['count(1) count'],sprintf(' and pro_id=%d',$Params['proId']),true);
			if($res['data']['count'])
			{
				$proArr['base']['pro_id']=$Params['proId'];
				//号码
				$res = $B2cBase->get('bc_number', ['num_id', 'num_factory', 'num_display', 'num_format', 'num_ismain','num_self'], sprintf(" and num_self=0 and num_pro_id=%s order by num_factory, num_format", $Params['proId']));
				$proArr['nums'] = $res['data'];
				$total=count($proArr['nums']);
				if($total>=4)
				{
					$keyArr=[];
					$chunk=floor($total/4);
					$less=$total%4;
					$keyArr=[1=>$chunk,2=>2*$chunk,3=>3*$chunk];
					if($less>0)
					{
						switch ($less)
						{
							case 1:
								$keyArr=[1=>$chunk+1,2=>2*$chunk+1,3=>3*$chunk+1];
								break;

							case 2:
								$keyArr=[1=>$chunk+1,2=>2*$chunk+2,3=>3*$chunk+2];
								break;
							case 3:
								$keyArr=[1=>$chunk+1,2=>2*$chunk+2,3=>3*$chunk+3];
								break;
						}
					}
					// print_r($keyArr);
					LibTpl::Set('keyArr',$keyArr);
				}
				//车型
				$res = $B2cBase->getFieldUniVal('bc_product_model3_link', 'pml3_mod3_id', sprintf(" and pml3_pro_id=%d", $Params['proId']));
				$proArr['modelId']['m3'] = $res['data'];
				if(!empty($res['data']))
				{
					$ComModel=new ComModel();
					$res=$ComModel->getModel(3,['mod3_name','mod3_start_year','mod3_end_year','mod3_engine','mod3_transmission','mod3_fuel','mod3_body','mod3_drive','brand_name','make_name','mod2_name'],sprintf(' and mod3_id in(%s) order by brand_seq, brand_initial, make_seq, make_initial, mod1_name, mod2_name, mod3_name',implode(',',$res['data'])));
					$proArr['modelArr']=$res['data'];
				}
				// print_r($proArr['modeArr']);
				LibTpl::Set('proArr',$proArr);
				LibTpl::Set('title','配件号码/车型-跑街的');
				LibTpl::Put();
				exit();
			}
		}
		LibTpl::Error('配件不存在');
	}
	/**
	 * @method    配件订单记录
	 * @author 卢
	 * @copyright 2018-04-27
	 */
	function proOrder()
	{
		$Params = MVC::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cBase = new B2cBase();
			$nowPage=isset($Params['page'])?$Params['page']:1;
			$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
			$res=$B2cBase->get('or_order_product',['count(1) total'],sprintf(' and orp_pro_id=%d',$Params['proId']),true);
			$total=$res['data']['total'];
			$where =sprintf(" and orp_pro_id=%d order by ord_add_time desc limit %d, %d",$Params['proId'], ($nowPage-1)*$nowPage, $perPage);
			$res=$B2cBase->get('or_order_product left join or_order on orp_ord_id=ord_id',['ord_id','orp_pro_name','orp_status','ord_pay_money','orp_sale_price','orp_price','orp_count','orp_money','ord_add_time','ord_uid','ord_shop_id'], $where);
			if(!empty($res['data']))
			{
				//买家
				$buyArr=array_column($res['data'], 'ord_uid');
				$uRes=$B2cBase->get('us_user_base',['ub_username','ub_uid'],sprintf(' and ub_uid in(%s)',implode(',',$buyArr)));
				if(!empty($uRes['data']))
				{
					$uArr=array_column($uRes['data'],null, 'ub_uid');
				}
				foreach ($res['data'] as $k => $v)
				{
					$res['data'][$k]['buyer']=isset($uArr[$v['ord_uid']])?$uArr[$v['ord_uid']]['ub_username']:'';
				}
			}
			// print_r($res);
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
			LibTpl::Set('proId',$Params['proId']);
			LibTpl::Set('ordList',$res['data']);
			LibTpl::Set('title','购买记录-跑街的');
			LibTpl::Put();
			exit();
		}
		LibTpl::Error('配件不存在');
	}
	/**
	 * @method    配件评论记录
	 * @author 卢
	 * @copyright 2018-04-27
	 */
	function proEval()
	{
		$Params = MVC::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cBase = new B2cBase();
			$where=sprintf(' and evp_pro_id=%d',$Params['proId']);
			$nowPage=isset($Params['page'])?$Params['page']:1;
			$perPage=isset($_COOKIE['perPage'])? $_COOKIE['perPage'] : 20;
			$count = $B2cBase->get('or_evaluate_product',['count(1) as count'],$where,true);
			$total = $count['data']['count'];
			$dataArr = $B2cBase->get('or_evaluate_product', ['*'], $where);
			if(!empty($dataArr['data']))
			{
				$dataArr['data']=array_column($dataArr['data'],null, 'evp_id');
				//取图片
				$imgIdArr=array_column($dataArr['data'], 'evp_id');
				if(count($imgIdArr))
				{
					$res=$B2cBase->get('or_evaluate_img',['evi_path','evi_name','evi_ext','evi_evi_id'],sprintf(' and evi_evi_id in(%s)',implode(',',$imgIdArr)));
					if(!empty($res['data']))
					{
						foreach ($res['data'] as $v)
						{
							$dataArr['data'][$v['evi_evi_id']]['imgArr'][]=$v;
						}
					}
				}
				//取用户
				$uArr=array_column($dataArr['data'], 'evp_uid');
				$res=$B2cBase->get('us_user_base',['ub_uid','ub_username'],sprintf(' and ub_uid in(%s)',implode(',',$uArr)));
				if(!empty($res['data']))
				{
					$res['data']=array_column($res['data'],null, 'ub_uid');
					foreach ($dataArr['data'] as $k => $v)
					{
						$dataArr['data'][$k]['uName']=isset($res['data'][$v['evp_uid']])?$res['data'][$v['evp_uid']]['ub_username']:'';
					}
				}
			}
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
			LibTpl::Set('proId',$Params['proId']);
			LibTpl::Set('dataArr',$dataArr['data']);
			LibTpl::Set('title','评价记录-跑街的');
			LibTpl::Put();
			exit();
		}
		LibTpl::Error('配件不存在');
	}

	/**
	 * @method    配件描述
	 * @author 卢
	 * @copyright 2018-04-27
	 */
	function productDesc()
	{
		$Params = MVC::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cBase = new B2cBase();
			$res=$B2cBase->get('bc_product_info',['pri_des','pri_pro_id'],sprintf(' and pri_pro_id=%d',$Params['proId']),true);
			LibTpl::Set('data',$res['data']);
			LibTpl::Set('proId',$Params['proId']);
			LibTpl::Set('title','配件描述-跑街的');
			LibTpl::Put();
			exit();
		}
		LibTpl::Error('配件不存在');
	}

	/**
	 * @method    数据批量导入规范
	 * @author    xu
	 * @copyright 2018-06-04
	 */
	function createModel() {
	    $spreadsheet = new Spreadsheet();
	    $sheet = $spreadsheet->getActiveSheet();

	    $cols = [
			['name' =>'配件ID','key' =>'pro_id','notice' =>'非必填|整数'],
			['name' => '配件名称','key' => 'pro_name','notice' => '必填|字符串'],
			['name' => '宜配零件分类','key' => 'part_name','notice' => '必填|官网零件分类|单个'],
			['name' => '宜配零件参数','key' => 'part_param','notice' =>'位置:前;位置:后;厚度:16.5 mm|以分号分隔，冒号前面是参数名，后面是参数值'],
			['name' => '配件品牌','key' => 'pro_brand','notice' => 'yiparts'],
			['name' => '配件自编号','key' => 'pri_code','notice' => '非必填'],
			['name' => '主号码','key' => 'main_number','notice' => 'OE:D123-544D'],
			['name' => '配件互换号码','key' => 'pro_number','notice' => 'OE:D123-544D;AB:OE:D123-556|可多个，英文分号分割'],
			['name' => '配件自定义参数','key' => 'pro_param','notice' => '位置:前轮;制动系统:ATE;宽度:94.8 mm;|英文分号分隔符'],
			['name' => '售价','key' => 'pro_sale_price','notice' => '数字|默认售价9999'],
			['name' => '库存','key' => 'pro_count','notice' => '整数|默认1'],
			['name' => '店铺分类','key' => 'sort','notice' => '宝马;奔驰；法拉利'],
			['name' => '配件卖点','key' => 'pro_sel_des','notice' => '非必填'],
			['name' => '配件描述','key' => 'pri_des','notice' => '非必填'],
			['name' => '发布时间','key' => 'publish','notice' => '不填则表示放入仓库|2018-08-08 08:08:08|严格按照示例填写'],
		];

		// 添加单元格
		foreach ($cols as $k => $v) {
		    $sheet->setCellValue(LibFc::IntToChr($k).'1',$v['name']);
		    $sheet->setCellValue(LibFc::IntToChr($k).'2',$v['key']);
		    $sheet->setCellValue(LibFc::IntToChr($k).'3',$v['notice']);
		}

	    // 设置背景色
	    $sheet->getStyle('A1:'.LibFc::IntToChr(count($cols)-1).'3')->getFill()
	    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
	    ->getStartColor()->setARGB('FFEC8B');

	    // 列宽
		foreach ($cols as $k => $v) {
			$sheet->getColumnDimension(LibFc::IntToChr($k))->setAutoSize(true);
		}

	    // 输出模板
	    $writer = new Xlsx($spreadsheet);
	    $writer->save('宜配B2C商城数据批量导入规范.xls');

	    // 下载文件
	    header('Location:'.mvc::$cfg['ADMIN_URL'].'宜配B2C商城数据批量导入规范.xls');
	    exit;

	}
	/**
	 * @method    询价单详情
	 * @return    [type]       [description]
	 * @author 卢
	 * @copyright 2018-09-25
	 */
	function purchaseInfo()
	{
		LibRule::Check('JP02');
		$Params = MVC::$URL_PARAMS;
		if(!LibFc::Int($Params['purId']))
		{
			LibTpl::Error('询价单不存在');
			exit();
		}

		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('pjl/getPurchaseByIds',['ids'=>[$Params['purId']],'oneRow'=>true]);
		$data = $res['data'];
		LibTpl::Set('data',$data);
		//品牌
		if(!empty($data['pur_brand_id']))
		{
			$postArr = [
				'filed'=>['brand_id', 'brand_name', 'brand_code'],
				'where'=>sprintf(" and brand_id =%d", $data['pur_brand_id']),
				'oneRow'=>true
			];
			$res = $LibYpApi->Get('ypc2/getBrand', [], $postArr);
			$brand=$res['data']['brand_name'];
			LibTpl::Set('brand',$brand);
		}
		//发布者
		if(!empty($data['pur_pu_id']))
		{
			$post = [
				'filed'=>['u_name','u_id'],
				'where'=>sprintf(" and u_id =%d", $data['pur_pu_id']),
				'oneRow'=>true
			];
			$res = $LibYpApi->Get('user/getUser',[], $post);

			$user=$res['data'];
			LibTpl::Set('user',$user);
		}
		if(!empty($data['pur_imgs']))
		{
			$imgArr=array_filter(explode(',',$data['pur_imgs']));
			$imgArr = array_map(function($value){
					return mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=purchase&f='.$value.mvc::$cfg['FILE_CENTER']['pjl']['get_uri'];
				}, $imgArr);
		}
		LibTpl::Set('imgArr',$imgArr);
		//地区
		$res = $LibYpApi->Get('pjl/getAddrByIds',['ids'=>$data['pur_pct_ids']]);
		if(!empty($res))
		{
			$area=implode(' ', $res['data']);
			LibTpl::Set('area',$area);
		}

		//询价单配件
		$res = $LibYpApi->Get('pjl/getPurchaseProductByIds',['ids'=>[$Params['purId']]]);
		$data = $res['data'];
		if(!empty($data))
		{
			$partArr = array_filter(array_column($data, 'pup_part_id'),'LibFc::Int');
			if(!empty($partArr))
			{
				$res = $LibYpApi->Get('pjl/getPartByIds',['ids'=>$partArr]);
				$partArr=array_column($res['data'],null, 'part_id');
			}
		}
		foreach ($data as $k=>$v)
		{
			if(!empty($partArr[$v['pup_part_id']]))
			{
				$v['part_name']=$partArr[$v['pup_part_id']]['part_name'];
				$data[$k]=$v;
			}
		}
		LibTpl::Set('prodata',$data);
        $PjlBase= new PjlBase();
        $res = $PjlBase->get('pl_purchase_call',['*'],sprintf(' and puca_pur_id=%d',$Params['purId']));

        $uidArr = [];
        if(!empty($res['data'])){
            $uidArr = array_column($res['data'], 'puca_by_uid');
            LibTpl::Set('productCallData',$res['data']);
        }
		//询价单的报价单
		$res = $LibYpApi->Get('pjl/getPurchaseOfferByWhere',['where'=>sprintf('and po_pur_id=%d', $Params['purId'])]);
		$data = $res['data'];
		if(!empty($data))
		{
			$uidArr = array_merge($uidArr,array_column($data, 'po_opu_uid'));
			array_unique($uidArr);
			$shopIdArr=array_column($data, 'po_shop_id');


			$where = sprintf('and shop_id in (%s)', implode(',', $shopIdArr));
			$res = $LibYpApi->Get('pjl/getShopByWhere',['where'=>$where]);
			$shopArr=array_column($res['data'],null, 'shop_id');

			LibTpl::Set('shopArr',$shopArr);
		}

        if(!empty($uidArr)){
            $post = [
                'filed'=>['u_name','u_id'],
                'where'=>sprintf(" and u_id in(%s)", implode(',',$uidArr)),
                'oneRow'=>false
            ];
            $res = $LibYpApi->Get('user/getUser',[], $post);
            $uArr = array_column($res['data'], null,'u_id');
            LibTpl::Set('uArr',$uArr);
        }
		LibTpl::Set('offerData',$data);

		LibTpl::Set('title','询价单详情-跑街令');
		LibTpl::Put();
	}
	function purchaseProduct()
	{
		LibRule::Check('JP02');
		$Params = MVC::$URL_PARAMS;
		if(!LibFc::Int($Params['purId']))
		{
			LibTpl::Error('询价单不存在');
			exit();
		}
		LibTpl::Set('Params',$Params);
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('pjl/getPurchaseProductByIds',['ids'=>[$Params['purId']]]);
		$data = $res['data'];
		if(!empty($data))
		{
			$partArr = array_filter(array_column($data, 'pup_part_id'),'LibFc::Int');
			if(!empty($partArr))
			{
				$res = $LibYpApi->Get('pjl/getPartByIds',['ids'=>$partArr]);
				$partArr=array_column($res['data'],null, 'part_id');
			}
		}
		foreach ($data as $k=>$v)
		{
			if(!empty($partArr[$v['pup_part_id']]))
			{
				$v['part_name']=$partArr[$v['pup_part_id']]['part_name'];
				$data[$k]=$v;
			}
		}
		LibTpl::Set('data',$data);
		LibTpl::Set('title','询价单产品-跑街令');
		LibTpl::Put();
	}
	function purchaseOffer()
	{
		LibRule::Check('JP03');
		$Params = MVC::$URL_PARAMS;
		if(!LibFc::Int($Params['purId']))
		{
			LibTpl::Error('询价单不存在');
			exit();
		}
		LibTpl::Set('Params',$Params);

		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('pjl/getPurchaseOfferByWhere',['where'=>sprintf('and po_pur_id=%s', $Params['purId'])]);
		$data = $res['data'];
		if(!empty($data))
		{
			$uidArr=array_column($data, 'po_opu_uid');
			$shopIdArr=array_column($data, 'po_shop_id');
			$post = [
				'filed'=>['u_name','u_id'],
				'where'=>sprintf(" and u_id in(%s)", implode(',',$uidArr)),
				'oneRow'=>false
			];
			$res = $LibYpApi->Get('user/getUser',[], $post);
			$uArr = array_column($res['data'], null,'u_id');

			$where = sprintf('and shop_id in (%s)', implode(',', $shopIdArr));
			$res = $LibYpApi->Get('pjl/getShopByWhere',['where'=>$where]);
			$shopArr=array_column($res['data'],null, 'shop_id');
			LibTpl::Set('uArr',$uArr);
			LibTpl::Set('shopArr',$shopArr);
		}
		LibTpl::Set('data',$data);
		LibTpl::Set('title','报价单-跑街令');
		LibTpl::Put();
	}

	public function purchaseOfferView()
	{
		$Params = MVC::$URL_PARAMS;
		if(!LibFc::Int($Params['poId']))
		{
			LibTpl::Error('报价单不存在');
			exit();
		}
		$LibYpApi = new LibYpApi();
		//获取报价单信息
		$res = $LibYpApi->Get('pjl/getPurchaseOfferByWhere',['where'=>sprintf('and po_id=%s', $Params['poId']),'oneRow'=>true]);
		LibTpl::Set('offer', $res['data']);

		$purId = $res['data']['po_pur_id'];

		if (LibFc::Int($purId))
		{
			//获取询价单信息
			$res = $LibYpApi->Get('pjl/getPurchaseByIds',['ids'=>[$purId],'oneRow'=>true]);
			if (!empty($res['data']['pur_imgs']))
			{
				$res['data']['pur_imgs'] = array_map(function($value){ return mvc::$cfg['FILE_CENTER']['pjl']['url_get'].'&c=purchase&f='.$value.mvc::$cfg['FILE_CENTER']['pjl']['get_uri']; }, array_filter(explode(',', $res['data']['pur_imgs'])));
			}
			LibTpl::Set('data', $res['data']);

			if(!empty($res['data']['pur_brand_id']))
			{
				$postArr = [
					'filed'=>['brand_id', 'brand_name', 'brand_code'],
					'where'=>sprintf(" and brand_id =%d", $res['data']['pur_brand_id']),
					'oneRow'=>true
				];
				$res = $LibYpApi->Get('ypc2/getBrand', [], $postArr);
				LibTpl::Set('brand',$res['data']['brand_name']);
			}
			//获取询价配件
			$res = $LibYpApi->Get('pjl/getPurchaseProductByIds',['ids'=>[$purId]]);
			LibTpl::Set('pro',array_column($res['data'], null, 'pup_id'));

			//获取报价价格
			$res = $LibYpApi->Get('pjl/getOfferProductByIds',['ids'=>[$Params['poId']]]);
			$res = array_column($res['data'], null, 'pop_pup_id');

			foreach ($res as $key => $value)
			{
				$res[$key]['pop_price'] = json_decode($value['pop_price'], true);
			}
			LibTpl::Set('offPro',$res);

		}

		LibTpl::Set('title','报价单详情-跑街令');
		LibTpl::Put();
	}

	public function purchaseOfferOrder()
	{
		LibRule::Check('JO02');
		$Params = MVC::$URL_PARAMS;
		if(!LibFc::Int($Params['poId']))
		{
			LibTpl::Error('订单不存在');
			exit();
		}
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->get('pjl/getOrderCount',['where'=>sprintf(' and ord_po_id=%d',$Params['poId'])]);
		if($res['data']['count'] > 0)
		{
			$res = $LibYpApi->Get('pjl/getOrderByWhere',['where'=>sprintf(' and ord_po_id=%d',$Params['poId']),'oneRow'=>true]);
			//订单信息
			$proRes = $LibYpApi->Get('pjl/getOrderProductByWhere',['where'=>sprintf(' and odp_ord_id=%d',$res['data']['ord_id'])]);
			$res['data']['proArr'] = $proRes['data'];

			//订单图片
			if(!empty($res['data']['ord_pur_imgs']))
				$res['data']['ord_pur_imgs'] = array_filter(explode(',', $res['data']['ord_pur_imgs']));

			//获取店铺信息
			$shop = $LibYpApi->Get('pjl/getShopByWhere', ['where'=>sprintf('and shop_id=%d',$res['data']['ord_shop_id']),'oneRow'=>true,'field'=>['shop_name','shop_tel']]);

			//获取用户信息
			$post = [
				'filed'=>['u_id','u_name','u_nickname','u_real_name'],
				'where'=>sprintf(" and u_id = %d ", $res['data']['ord_pu_uid']),
				'oneRow'=>true
			];
			$user = $LibYpApi->Get('user/getUser',[], $post);

			$orderStatusDes = array(
				'completed' => '交易完成',
				'creat' => '等待付款',
				'paied' => '等待发货',
				'send' => '等待收货',
				'cancel' => '订单已取消',
				'refund' => '退款中',
			);
			LibTpl::Set('orderStatusDes',$orderStatusDes);

			//基本信息
			LibTpl::Set('orderInfo',array_merge($res['data'],$shop['data'],$user['data'],json_decode($res['data']['ord_addr'],true),json_decode($res['data']['ord_model_info'],true)));
		}
		LibTpl::Set('title','订单详情-跑街令');
		LibTpl::Put();
	}


	//询价单改名
	function setPupName()
	{
		LibRule::Check('JP04');
		$Params = mvc::$URL_PARAMS;
		$PjlBase= new PjlBase();
		if(!empty($_POST['pup_name']))
		{
			foreach($_POST['pup_name'] as $id=>$val)
			{
				if(!empty($id) && !empty($val))
				{
					$PjlBase->set('`pl_purchase_product`', ['pup_name'=>$val], sprintf(" and pup_id=%d", $id));
				}
			}
		}

		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$page=!empty($Params['page'])?(int)$Params['page']:1;

		$where =' and pur_status = 0';
		if(!empty($Params['t'])) $where .= sprintf(" and pur_atime > %d", time()-$Params['t']*3600);
		$table = '`pl_purchase_product` JOIN `pl_purchase` ON pur_id = pup_pur_id';
		$res=$PjlBase->get($table,['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 pur_id desc limit %s,%s', ($page-1)*$perPage,$perPage);
			$res = $PjlBase->get($table, ['*'], $where);
			$pupArr = $res['data'];
		}
		LibTpl::Set('pupArr',$pupArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','询价单改名-跑街令');
		LibTpl::Put();
	}
}
