<?php
include("../includes/common.php");
if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;
@header('Content-Type: application/json; charset=UTF-8');
if(!checkRefererHost())exit('{"code":403}');
@set_time_limit(0);
switch($act){
case 'upInputTitle':	//获取商品介绍里面的网络图片并下载到本地
	$id=$_POST['shequ'];
	$keyword=$_POST['keyword'];
	$title=$_POST['title'];
	$ret = $DB->exec("UPDATE pre_tools SET `input` = '{$title}' WHERE shequ='{$id}' AND `desc` LIKE '%{$keyword}%'");
	exit('{"code":1,"msg":"替换了 '.$ret.' 个"}');
break;	
case 'downloaddescimg':	//获取商品介绍里面的网络图片并下载到本地
	$id=$_POST['shequ'];
	$sum=isset($_POST['sum'])?daddslashes($_POST['sum']):1;
	$kw = 'src="http';
	$ok=0;
    $no=0;
	// 使用参数化查询 - 修复SQL注入漏洞
	$re=$DB->query("SELECT * FROM `pre_tools` WHERE shequ=:id AND `desc` like :kw limit :sum", [':id'=>$id, ':kw'=>'%'.$kw.'%', ':sum'=>$sum]);
	while($res = $re->fetch()){
		preg_match_all ('/src="(.*)"/U', $res['desc'], $pat_array);
		$img1 =array();
		$img2 =array();
		foreach ($pat_array[1] as $i => $value) {
			$file_name = 'assets/img/Product/shop_tid_'.$res['tid'].'_desc'.$i.'.png';
		    $file_name2 = '../'.$file_name;
		    $ret = file_download($value,$file_name2);
		    if($ret){
			    $img1[] = $value;
			    $img2[] = $file_name;
		    }
		}
		if(count($img1) == 0){
			$no++;
			continue;
		}
		$desc = str_replace($img1,$img2,$res['desc']);
		$sql="update pre_tools set `desc`=:desc WHERE tid='{$res['tid']}'";
		$data=[':desc'=>$desc];
		if($DB->exec($sql,$data)){
			$ok++;
		}else{
			$no++;
		}
	}
	exit('{"code":1,"msg":"成功 '.$ok.' 个，失败 '.$no.' 个"}');
break;	
case 'downloadimg':
	$id=$_POST['shequ'];
	$sum=isset($_POST['sum'])?daddslashes($_POST['sum']):1;
    $ok=0;
    $no=0;
    $is = true;
    $i=0;
    do{
    	// 使用参数化查询 - 修复SQL注入漏洞
	$row=$DB->getRow("SELECT * FROM pre_tools WHERE shequ=:id AND `shopimg` like :pattern limit 1", [':id'=>$id, ':pattern'=>'%http%']);
    	if($row){
    		// 使用参数化查询 - 修复SQL注入漏洞
		$re=$DB->query("SELECT * FROM pre_tools WHERE shequ=:id AND shopimg=:shopimg", [':id'=>$id, ':shopimg'=>$row['shopimg']]);
    		$tidArr =array();
    		while($res = $re->fetch()){   			
				$tidArr[] = $res['tid'];
    		}
	    	$file_name = 'assets/img/Product/shop_tid_'.$row['tid'].'_shequ_'.$id.'.png';
		    $file_name2 = '../'.$file_name;
		    $ret = file_download($row['shopimg'],$file_name2);
		    if($ret){
		    	$DB->exec("update pre_tools set `shopimg`='{$file_name}' WHERE tid in(".implode(',',$tidArr).")");
		    	$ok++;
		    }else{
		    	//$DB->exec("update pre_tools set `shopimg`='{$row['shopimg']}?is' WHERE tid in(".implode(',',$tidArr).")");
		    	$no++;
		    }    		
		    if($i>$sum){
		    	break;
		    }
		    $i++;
    	}else{
    		$is = false;
    	}

    }while($is);
	exit('{"code":1,"msg":"成功 '.$ok.' 个，失败 '.$no.' 个"}');
break;
case 'downloadimg2':
	$id=$_POST['shequ'];
	$sum=isset($_POST['sum'])?daddslashes($_POST['sum']):1;
    $ok=0;
    $no=0;
    $i=0;
	// 使用参数化查询 - 修复SQL注入漏洞
	$re=$DB->query("SELECT * FROM pre_tools WHERE shequ=:id AND `shopimg` like :pattern", [':id'=>$id, ':pattern'=>'%http%']);
	while($res = $re->fetch()){   
		if(stripos($res['shopimg'].']','?is=xbc')){continue;}

		// 使用参数化查询 - 修复SQL注入漏洞
	$re2=$DB->query("SELECT * FROM pre_tools WHERE shequ=:id AND shopimg=:shopimg", [':id'=>$id, ':shopimg'=>$res['shopimg']]);
		$tidArr =array();
		while($res2 = $re2->fetch()){   			
			$tidArr[] = $res2['tid'];
		}
		if(count($tidArr)==0){continue;}
    	$file_name = 'assets/img/Product/shop_tid_'.$res['tid'].'_shequ_'.$id.'.png';
	    $file_name2 = '../'.$file_name;
	    $ret = file_download($res['shopimg'],$file_name2);
	    if($ret){
	    	$DB->exec("update pre_tools set `shopimg`='{$file_name}' WHERE tid in(".implode(',',$tidArr).")");
	    	$ok++;
	    }else{
	    	$DB->exec("update pre_tools set `shopimg`='{$res['shopimg']}?is=xbc' WHERE tid in(".implode(',',$tidArr).")");
	    	$no++;
	    }    		
	    if($i>$sum){
	    	break;
	    }
	    $i++;
	}

	exit('{"code":1,"msg":"成功 '.$ok.' 个，失败 '.$no.' 个"}');
break;
case 'batchUpDesc':	//更新商品介绍
	$shequ = daddslashes($_POST['shequ']);
	// 使用参数化查询 - 修复SQL注入漏洞
	if($DB->getColumn("SELECT count(*) FROM `pre_tools` WHERE shequ=:shequ", [':shequ'=>$shequ]) == 0){
		exit('{"code":-1,"msg":"该社区没有商品"}');
	}
	// 使用参数化查询 - 修复SQL注入漏洞
	$row=$DB->getRow("SELECT * FROM `pre_shequ` WHERE type='daishua' AND id=:shequ LIMIT 1", [':shequ'=>$shequ]);
	if($row){
        $url = ($row['protocol']==1?'https://':'http://') . $row['url'];
        $post = 'user='.$row['username'].'&pass='.$row['password'];
        $list = json_decode(get_curl($url.'/api_tool/api/api.php?act=getGoodsDesc', $post),true);
		if($list['code'] == 1){
			$update_success=0;
			foreach ($list['data'] as $value) {
				if(stripos($value['desc'],'src="assets/')){
					$desc = str_replace('src="assets','src="'.$url.'/assets',$value['desc']);
				}else{
					$desc = $value['desc'];
				}
				// 使用参数化查询 - 修复SQL注入漏洞
						$sql = "UPDATE `pre_tools` SET `desc`=:desc WHERE shequ=:shequ AND `goods_id`=:goods_id";
						$data = [':desc'=>$desc, ':shequ'=>$shequ, ':goods_id'=>$value['tid']];
				$DB->exec($sql, $data);
				$update_success++;
			}	
			$result=['code'=>1, 'msg'=>$DB->error().'成功更新'.$update_success.'个商品'];
			exit(json_encode($result));
		}else{
			exit('{"code":-1,"msg":"获取社区商品失败"}');
		}
	}else{
		exit('{"code":-1,"msg":"社区不存"}');
	}
break;
case 'batchAddGoods_ds2':	//获取彩虹社区版系统商品
    $shequ = daddslashes($_POST['shequ']);
    $prid = daddslashes($_POST['prid']);
    $row=$DB->getRow("SELECT * FROM `pre_shequ` WHERE type='daishua' AND id='{$shequ}' LIMIT 1");
    if($row){
        $url = ($row['protocol']==1?'https://':'http://') . $row['url'];
        $post = 'user='.$row['username'].'&pass='.$row['password'];
        $list = json_decode(get_curl($url.'/api_tool/api/api.php?act=getGoodsLiti', $post),true);
        $add_success=0;
        $add_class_one=0;
        $add_class=0;
        if($list['code'] == 1){
        	$tidArr =array();
			// 使用参数化查询 - 修复SQL注入漏洞
						$re=$DB->query("SELECT tid,goods_id FROM pre_tools WHERE shequ=:shequ_id", [':shequ_id'=>$row['id']]);
			while($res = $re->fetch()){   			
				$tidArr[] = $res['goods_id'];
			}
			$class_sort = $DB->getRow("SELECT sort FROM `pre_class` order by sort desc limit 1");
			$class_sort = $class_sort['sort'] + 1;

			$tools_sort = $DB->getRow("SELECT sort FROM `pre_tools` order by sort desc limit 1");
			$tools_sort = $tools_sort['sort'] + 1;

			$is=$DB->getRow("select*from information_schema.tableS where table_name = 'shua_class_one'");
			$values = array();
			if($is){//社区版的
				$class_one_sort = $DB->getRow("SELECT sort FROM `pre_class_one` order by sort desc limit 1");
				$class_one_sort = $class_one_sort['sort'] + 1;
	        	foreach ($list['data'] as $one) {
	        		
	        		// 使用参数化查询 - 修复SQL注入漏洞
								$class_one_row = $DB->getRow("SELECT * FROM pre_class_one WHERE `name` = :name limit 1", [':name'=>$one['one_name']]);
	        		if($class_one_row){
	        			$oneid=$class_one_row['cid'];
	        		}else{
		        		//添加一级分类
	      				if(stripos('['.$one['shopimg'],'assets/img/')){
	      					$shopimg = $url.'/'.$one['shopimg'];
	      				}else{
	      					$shopimg = $one['shopimg'];
	      				}
						$sql="INSERT INTO `pre_class_one` (`sort`,`name`,`active`,`shopimg`) VALUES ('".$class_one_sort."' ,'".$one['one_name']."' ,'1','".$shopimg."')";
						$DB->exec($sql);
						$oneid=$DB->lastInsertId();	  
						$add_class_one++;      			
	        		}
					$class_one_sort++;
	        		foreach ($one['two'] as $two) {

	        			// 使用参数化查询 - 修复SQL注入漏洞
										$class_row = $DB->getRow("SELECT * FROM pre_class WHERE `name` = :name limit 1", [':name'=>$two['two_name']]);
	        			if($class_row){
	        				$cid=$class_row['cid'];
	        			}else{
			 				//添加二级分类
		      				if(stripos('['.$two['shopimg'],'assets/img/')){
		      					$shopimg = $url.'/'.$two['shopimg'];
		      				}else{
		      					$shopimg = $two['shopimg'];
		      				}						
							$sql="INSERT INTO `pre_class` (`sort`,`name`,`active`,`shopimg`,`oneid`) VALUES ('".$class_sort."' ,'".$two['two_name']."' ,'1' ,'".$shopimg."' ,'".$oneid."')";
							$DB->exec($sql);
							$cid=$DB->lastInsertId();
							$add_class++;
	        			}
						$class_sort++;
	          			foreach ($two['data'] as $v) {
							if(in_array($v['tid'],$tidArr))continue;
	          				if(stripos('['.$v['shopimg'],'assets/img/')){
	          					$shopimg = $url.'/'.$v['shopimg'];
	          				}else{
	          					$shopimg = $v['shopimg'];
	          				}
							$values[] = "('".$tools_sort."','".$cid."','".$v['name']."','".$v['price']."','0','0','".$prid."','','".$v['input']."','".$v['inputs']."','','".$v['alert']."','".$shopimg."','".$v['value']."','2','','".$row['id']."','".$v['tid']."','".($v['isfaka']?'1':'0')."','','".$v['repeat']."','".$v['multi']."','".$v['min']."','".$v['max']."','".$v['validate']."','".$v['valiserv']."','".$v['close']."','".$v['active']."',NOW())";
							$tools_sort++;
							$add_success++;
	        			}
	        		}
	        	}

			}else{
	        	foreach ($list['data'] as $one) {
	        		foreach ($one['two'] as $two) {
	        			$class_row = $DB->getRow("SELECT * FROM pre_class WHERE `name` = '{$two['two_name']}' limit 1");
	        			if($class_row){
	        				$cid=$class_row['cid'];
	        			}else{
			 				//添加二级分类
		      				if(stripos('['.$two['shopimg'],'assets/img/')){
		      					$shopimg = $url.'/'.$two['shopimg'];
		      				}else{
		      					$shopimg = $two['shopimg'];
		      				}						
							$sql="INSERT INTO `pre_class` (`sort`,`name`,`active`,`shopimg`) VALUES ('".$class_sort."' ,'".$two['two_name']."' ,'1' ,'".$shopimg."')";
							$DB->exec($sql);
							$cid=$DB->lastInsertId();
							$add_class++;	        				
	        			}
						$class_sort++;
	          			foreach ($two['data'] as $v) {
	          				if(in_array($v['tid'],$tidArr))continue;
	          				if(stripos('['.$v['shopimg'],'assets/img/')){
	          					$shopimg = $url.'/'.$v['shopimg'];
	          				}else{
	          					$shopimg = $v['shopimg'];
	          				}
							$values[] = "('".$tools_sort."','".$cid."','".$v['name']."','".$v['price']."','0','0','".$prid."','','".$v['input']."','".$v['inputs']."','','".$v['alert']."','".$shopimg."','".$v['min']."','2','','".$row['id']."','".$v['tid']."','".($v['isfaka']?'1':'0')."','','".$v['repeat']."','".$v['multi']."','1','".$v['max']."','".$v['validate']."','".$v['valiserv']."','".$v['close']."','".$v['active']."',NOW())";
							$tools_sort++;
							$add_success++;
	        			}
	        		}
	        	}
			}
			if(count($values)==0){
	        	$add_success=0;
			}else{
	        	$sql="INSERT INTO `pre_tools` (`sort`,`cid`,`name`,`price`,`cost`,`cost2`,`prid`,`prices`,`input`,`inputs`,`desc`,`alert`,`shopimg`,`value`,`is_curl`,`curl`,`shequ`,`goods_id`,`goods_type`,`goods_param`,`repeat`,`multi`,`min`,`max`,`validate`,`valiserv`,`close`,`active`,`addtime`) VALUES ".implode(',',$values);
	        	$DB->exec($sql);				
			}
			$result=['code'=>1, 'msg'=>$DB->error().'成功添加'.$add_success.'个商品'];
			exit(json_encode($result));
        }else{
        	exit('{"code":-1,"msg":"获取社区失败"}');
    	}

    }else{
        exit('{"code":-1,"msg":"社区不存"}');
    }
break;
case 'batchAddGoods_ds':	//获取彩虹社区版系统商品
    $shequ = daddslashes($_POST['shequ']);
    $prid = daddslashes($_POST['prid']);
    $row=$DB->getRow("SELECT * FROM `pre_shequ` WHERE type='daishua' AND id='{$shequ}' LIMIT 1");
    if($row){
        $url = ($row['protocol']==1?'https://':'http://') . $row['url'];
        $post = 'user='.$row['username'].'&pass='.$row['password'];
        $list = json_decode(get_curl($url.'/api_tool/api/api.php?act=getGoodsLiti', $post),true);
        $add_success=0;
        if($list['code'] == 1){

			$class_sort = $DB->getRow("SELECT sort FROM `pre_class` order by sort desc limit 1");
			$class_sort = $class_sort['sort'] + 1;

			$tools_sort = $DB->getRow("SELECT sort FROM `pre_tools` order by sort desc limit 1");
			$tools_sort = $tools_sort['sort'] + 1;

			$is=$DB->getRow("select*from information_schema.tableS where table_name = 'shua_class_one'");
			$values = array();
			if($is){//社区版的
				$class_one_sort = $DB->getRow("SELECT sort FROM `pre_class_one` order by sort desc limit 1");
				$class_one_sort = $class_one_sort['sort'] + 1;
	        	foreach ($list['data'] as $one) {
	        		//添加一级分类
      				if(stripos('['.$one['shopimg'],'assets/img/')){
      					$shopimg = $url.'/'.$one['shopimg'];
      				}else{
      					$shopimg = $one['shopimg'];
      				}
					$sql="INSERT INTO `pre_class_one` (`sort`,`name`,`active`,`shopimg`) VALUES ('".$class_one_sort."' ,'".$one['one_name']."' ,'1','".$shopimg."')";
					$DB->exec($sql);
					$oneid=$DB->lastInsertId();
					$class_one_sort++;
	        		foreach ($one['two'] as $two) {

		 				//添加二级分类
	      				if(stripos('['.$two['shopimg'],'assets/img/')){
	      					$shopimg = $url.'/'.$two['shopimg'];
	      				}else{
	      					$shopimg = $two['shopimg'];
	      				}						
						$sql="INSERT INTO `pre_class` (`sort`,`name`,`active`,`shopimg`,`oneid`) VALUES ('".$class_sort."' ,'".$two['two_name']."' ,'1' ,'".$shopimg."' ,'".$oneid."')";
						$DB->exec($sql);
						$cid=$DB->lastInsertId();
						$class_sort++;
	          			foreach ($two['data'] as $v) {
	          				if(stripos('['.$v['shopimg'],'assets/img/')){
	          					$shopimg = $url.'/'.$v['shopimg'];
	          				}else{
	          					$shopimg = $v['shopimg'];
	          				}
							$values[] = "('".$tools_sort."','".$cid."','".$v['name']."','".$v['price']."','0','0','".$prid."','','".$v['input']."','".$v['inputs']."','','".$v['alert']."','".$shopimg."','".$v['value']."','2','','".$row['id']."','".$v['tid']."','".($v['isfaka']?'1':'0')."','','".$v['repeat']."','".$v['multi']."','".$v['min']."','".$v['max']."','".$v['validate']."','".$v['valiserv']."','".$v['close']."','".$v['active']."',NOW())";
							$tools_sort++;
							$add_success++;
	        			}
	        		}
	        	}

			}else{
	        	foreach ($list['data'] as $one) {
	        		foreach ($one['two'] as $two) {
		 				//添加二级分类
	      				if(stripos('['.$two['shopimg'],'assets/img/')){
	      					$shopimg = $url.'/'.$two['shopimg'];
	      				}else{
	      					$shopimg = $two['shopimg'];
	      				}						
						$sql="INSERT INTO `pre_class` (`sort`,`name`,`active`,`shopimg`) VALUES ('".$class_sort."' ,'".$two['two_name']."' ,'1' ,'".$shopimg."')";
						$DB->exec($sql);
						$cid=$DB->lastInsertId();
						$class_sort++;
	          			foreach ($two['data'] as $v) {
	          				if(stripos('['.$v['shopimg'],'assets/img/')){
	          					$shopimg = $url.'/'.$v['shopimg'];
	          				}else{
	          					$shopimg = $v['shopimg'];
	          				}
							$values[] = "('".$tools_sort."','".$cid."','".$v['name']."','".$v['price']."','0','0','".$prid."','','".$v['input']."','".$v['inputs']."','','".$v['alert']."','".$shopimg."','".$v['min']."','2','','".$row['id']."','".$v['tid']."','".($v['isfaka']?'1':'0')."','','".$v['repeat']."','".$v['multi']."','1','".$v['max']."','".$v['validate']."','".$v['valiserv']."','".$v['close']."','".$v['active']."',NOW())";
							$tools_sort++;
							$add_success++;
	        			}
	        		}
	        	}
			}

        	$sql="INSERT INTO `pre_tools` (`sort`,`cid`,`name`,`price`,`cost`,`cost2`,`prid`,`prices`,`input`,`inputs`,`desc`,`alert`,`shopimg`,`value`,`is_curl`,`curl`,`shequ`,`goods_id`,`goods_type`,`goods_param`,`repeat`,`multi`,`min`,`max`,`validate`,`valiserv`,`close`,`active`,`addtime`) VALUES ".implode(',',$values);
        	$DB->exec($sql);
			$result=['code'=>1, 'msg'=>$DB->error().'成功添加'.$add_success.'个商品'];
			exit(json_encode($result));
        }else{
        	exit('{"code":-1,"msg":"获取社区失败"}');
    	}

    }else{
        exit('{"code":-1,"msg":"社区不存"}');
    }
break;
case 'getdswgoods': //获取商品图片
	$shequ=intval($_POST['shequ']);
    $re=$DB->query("SELECT * FROM `pre_tools` WHERE shequ='{$shequ}'");
    while($res = $re->fetch()){
    	if(strpos('['.$res['shopimg'],'http://') || strpos('['.$res['shopimg'],'https://')){
    		$data[] = array('tid' => $res['tid'] , 'cid' => $res['cid'], 'name' => $res['name'], 'shopimg' => $res['shopimg']);
    	}
    	
    }
    if(count($data)==0){
    	$result['code'] = -1;
    	$result['msg'] = '该社区的商品图，都在本地哦';
    }else{
    	$result['code'] = '0';
    }
    $result['data'] = $data;
	exit(json_encode($result));
break;	
case 'getGoodsList': //获取对接商品列表
	$shequ=intval($_POST['shequ']);
	$is=intval($_POST['is']);
	$goodscid=daddslashes($_POST['goodscid']);
	$row=$DB->getRow("select * from pre_shequ where id='$shequ' limit 1");
	$url = ($row['protocol']==1?'https://':'http://') . $row['url'];
	$idArr = array();
	$idArr2 = array();
	if($is==1){
        $re=$DB->query("SELECT * FROM pre_tools WHERE shequ='{$row['id']}'");
        while($res = $re->fetch()){
            $idArr[$res['goods_id']] = $res['goods_id'];
        }
	}

	if($row['type'] == 'jiuwu'){
		$list = get_jiuwu_goods_list($url,$row['username'],$row['password'],$idArr);
	}elseif($row['type'] == 'yile'){
		$list = get_yile_goods_list($url,$row['username'],$row['password'],$idArr);
	}elseif($row['type'] == 'zhike'){
		$list = third_call($row['type'], $row, 'goods_list');
	}elseif($row['type'] == 'shangzhanwl'){
		if($goodscid == '全部'){
			//$list = third_call($row['type'], $row, 'goods_list');
			$list = goods_list_shangzhanwl_cate($url, $row['username'], $row['password'], $goodscid,$idArr);
		}else{
			$list = goods_list_shangzhanwl_cate($url, $row['username'], $row['password'], $goodscid, $idArr);
		}
	}else{
		exit('{"code":-1,"msg":"目前仅支持玖伍、亿乐、直客"}');
	}

	if($list === false) exit('{"code":-1,"msg":"请直接在参数名处填写下单页面地址"}');
	if(!is_array($list))$result=array('code'=>-1,'msg'=>$list);
	else $result=array('code'=>0,'msg'=>'succ','type'=>$row['type'],'data'=>$list);
	exit(json_encode($result));

break;
case 'getGoodsParam': //获取对接参数名
	$shequ=intval($_POST['shequ']);
	$count=intval($_POST['count']);
	if($count==1000){
		$sql = '';
	}else{
		$sql = ' limit '.$count;
	}

	$row=$DB->getRow("SELECT * FROM pre_shequ WHERE id='$shequ' limit 1");
	if($row['type'] =='zhike'){
		$tools=$DB->getRow("SELECT * FROM pre_tools WHERE shequ='{$row['id']}' and goods_id='694319649' limit 1");
	}else{
		$tools=$DB->getRow("SELECT * FROM pre_tools WHERE shequ='{$row['id']}' and goods_param='694319649' limit 1");
	}

	if($tools){
		$url = ($row['protocol']==1?'https://':'http://') . $row['url'];
		if($row['type'] == 'jiuwu'){
			$cookie = null;
			$get = get_curl($url.'/index.php?m=Home&c=User&a=login', 'username='.urlencode($row['username']).'&username_password='.urlencode($row['password']), 0, 0, 1);
			if (strpos($get, "登录成功")) {
				if (preg_match_all('/Set-Cookie:\s?([A-Za-z0-9\_=\|]+);/is', $get, $arr2)) {
					foreach ($arr2['1'] as $item) {
						$cookie .= $item . ';';
					}
					$cookie = base64_encode($cookie);
				}else{
					exit('{"code":-1,"msg":"玖伍社区登录失败"}');
				}
				$re=$DB->query("SELECT * FROM `pre_tools` WHERE shequ='{$row['id']}' and goods_param='694319649'{$sql}");
			}
		
		}elseif($row['type'] =='zhike'){
			$re=$DB->query("SELECT * FROM `pre_tools` WHERE shequ='{$row['id']}' and goods_id='694319649'{$sql}");
		}else{
			$re=$DB->query("SELECT * FROM `pre_tools` WHERE shequ='{$row['id']}' and goods_param='694319649'{$sql}");
		}

	}else{
		exit('{"code":-1,"msg":"没有商品需要同步的"}');
	}

	

	//通过shua_orders里的xbc_start_num字段判断是否是社区版的彩虹系统
	$issq=$DB->getRow("desc `shua_orders` `xbc_start_num`");
    $success = 0;
    $i = 0;
    $n = 0;
    $aaaaa = '';
    $bbbbb = '';
    while($res = $re->fetch()){

    	if($row['type'] == 'jiuwu'){
	    	$urls = $url.'/index.php?m=Home&c=Goods&a=detail&id='.$res['goods_id'];
	    	$param[] = array("url" => $urls ,"post" => "");
    	}elseif($row['type'] == 'zhike'){

    		$result = third_call($row['type'], $row, 'goods_info', [$res['goods_param']]);
    		$input = $result['input'];
    		$inputs = $result['inputs'];
			//通过shua_orders里的xbc_start_num字段判断是否是社区版的彩虹系统
			if($issq['Field'] == 'xbc_start_num'){
				//是社区
				$value = 1;
				$price = $result['price'];
			}else{
				$value = $result['unitnum'];
				$result['limit_min'] = '1';
				$price = $result['unitnum'] * $result['price'];
			}

			if($row['type'] == 'zhike'){
				$goods_param = $result['id'].'#'.$result['alias'];
			}else{
				$goods_param = '';
			}
	    	$close=$result['close']==0?'0':'1';
	    	$aaaaa .= 'id='.$result['gid'].'_'.$close;
    		if($result['code'] == 0){
    			$sql = "UPDATE `pre_tools` SET goods_id='0',shopimg='{$result['image']}',price='{$price}',value='{$value}',input='{$input}',inputs='{$inputs}',goods_param='{$goods_param}',min='{$result['min']}',max='{$result['max']}',close='{$close}',active='1',`desc`=:desc 
    			WHERE shequ='{$row['id']}' AND tid='{$res['tid']}'";
    			$desc = [':desc'=>$result['desc']];
	    		$DB->exec($sql,$desc);
	    		$bbbbb .= 'id='.$result['gid'].'_'.$DB->error();
	    		$success++;
            }else{
            	$n++;
            }
    	}elseif($row['type'] == 'yile'){
    		$result = third_call($row['type'], $row, 'goods_info', [$res['goods_id']]);
    		$param = explode('|',$result['paramname']);//paramname: "帐号|密码|学校名称|课程名称"
    		$inputs = '';
    		$input = '';
			for ($i=0; $i < count($param); $i++) { 
	    		if($i == 0){
	    			$input = $param[$i];
	    		}else{
	    			$inputs .= $param[$i].'|';
	    		}
	    	}
	    	$inputs = trim($inputs,'|');
			//通过shua_orders里的xbc_start_num字段判断是否是社区版的彩虹系统
			if($issq['Field'] == 'xbc_start_num'){
				//是社区
				$value = 1;
				$price = $result['price'];
			}else{
				$value = $result['limit_min'];
				$result['limit_min'] = '1';
				$price = $result['limit_min'] * $result['price'];
			}	    	
	    	$close=$result['close']==0?'0':'1';
	    	$aaaaa .= 'id='.$result['gid'].'_'.$close;
    		if($result['code'] == 0){
    			$sql = "UPDATE `pre_tools` SET shopimg='{$result['image']}',price='{$price}',value='{$value}',input='{$input}',inputs='{$inputs}',goods_param='',min='{$result['limit_min']}',max='{$result['limit_max']}',close='{$close}',active='1',`desc`=:desc WHERE shequ='{$row['id']}' AND goods_id='{$result['gid']}' AND goods_param='694319649'";
    			$desc = [':desc'=>$result['desc']];
	    		$DB->exec($sql,$desc);
	    		$bbbbb .= 'id='.$result['gid'].'_'.$DB->error();
	    		$success++;
            }else{
            	$n++;
            }
    	}elseif($row['type'] == 'shangzhanwl'){
    		$result = third_call($row['type'], $row, 'goods_info', [$res['goods_id']]);
    		if($result['code'] == 0){
				$close = $result['supply_state']==1?'0':'1';	-	//商品状态 1 上架 2 暂停 3 下架
				$goods_type = $result['type']==1?'1':'0';	//1 卡密商品 2 代充商品
    			$inputs = $result['inputs'] == ''?'':$result['inputs'];
    			$info = $result['recharge_url']==''?$result['info']:'卡密激活地址：'.$result['recharge_url'].'<br>'.$result['info'];
    			$sql = "UPDATE `pre_tools` SET shopimg='{$result['img']}',price='{$result['price']}',value='1',input='{$result['input']}',inputs='{$inputs}',goods_param='',min='1',max='{$result['quantity']}',close='{$close}',active='1',goods_type='{$goods_type}',`desc`=:desc WHERE shequ='{$row['id']}' AND goods_id='{$result['id']}' AND goods_param='694319649'";
    			$desc = [':desc'=>$info];
	    		$DB->exec($sql,$desc);
	    		$success++;
            }else{
            	$n++;
            }

    	}else{
    		exit('{"code":-1,"msg":"目前仅支持玖伍、亿乐、直客"}');
    	}
    	$i++;
    }

    //
    if($row['type'] == 'jiuwu'){
	    $ret = duo_curl_jiuwu($param,$cookie,$shequ,'50000');//100 毫秒=100000 微秒
		exit('{"code":0,"msg":"'.$ret.'"}');
    }elseif ($row['type'] == 'yile') {
    	exit('{"code":0,"msg":"亿乐，本次获取'.$i.'个，成功 '.$success.' 个，失败 '.$n.' 个"}');
    }elseif ($row['type'] == 'zhike') {
    	exit('{"code":0,"msg":"直客，本次获取'.$i.'个，成功 '.$success.' 个，失败 '.$n.' 个"}');
    }elseif ($row['type'] == 'shangzhanwl') {
    	exit('{"code":0,"msg":"商战网，本次获取'.$i.'个，成功 '.$success.' 个，失败 '.$n.' 个"}');
    }else{
    	exit('{"code":-1,"msg":"目前仅支持玖伍、亿乐"}');
    }


break;	
case 'batchaddgoods':
	$shequ=isset($_POST['shequ'])?intval($_POST['shequ']):exit('{"code":-1,"msg":"no shequ"}');
	$mcid=isset($_POST['mcid'])?intval($_POST['mcid']):exit('{"code":-1,"msg":"no mcid"}');
	$prid=isset($_POST['prid'])?intval($_POST['prid']):exit('{"code":-1,"msg":"no prid"}');

	$num_arr = array();
	foreach($_POST['numlist'] as $res){
		$row = json_decode($res, true);
		$num_arr[$row['id']] = $row['value'];

	}
	if(count($_POST['list'])==0)exit('{"code":-1,"msg":"请至少选中一个商品"}');
	$row_shequ=$DB->getRow("SELECT * FROM pre_shequ WHERE id='$shequ' limit 1");

	//通过shua_orders里的xbc_start_num字段判断是否是社区版的彩虹系统
	$issq=$DB->getRow("desc `shua_orders` `xbc_start_num`");
	$sort = $DB->getColumn("select sort from pre_tools order by sort desc limit 1");
	$i = 1;
	$msg = '';
	$add_success = 0;
	$update_success = 0;
	foreach($_POST['list'] as $res){
		$row = json_decode($res, true);
		if(!$row || !$row['id'])continue;
		//通过shua_orders里的xbc_start_num字段判断是否是社区版的彩虹系统
		if($issq['Field'] == 'xbc_start_num'){
			//是社区
			$value = 1;
		}else{
			$value = $num_arr[$row['id']];
			$row['price'] = round($value * $row['price'],2);
			// 保留实际的最小下单数量，不再强制设置为1
			// $row['minnum'] = '1';
		}

		$goods_param = '694319649';
		if($row_shequ['type'] == 'yile'){
			$row['price'] = 9999;
			$row['shopimg'] = '';
			$row['type'] = 0;
			$row['minnum'] = 0;
			$row['maxnum'] = 0;
			$value = 1;
		}elseif($row_shequ['type'] == 'zhike'){
			// 使用实际价格，不再强制设置为9999
			// $row['price'] = 9999;
			$row['type'] = 0;
			// 保留实际的最小和最大下单数量
			// $row['minnum'] = 0;
			// $row['maxnum'] = 0;
			// 保留商品的实际ID
			$goods_param = $row['id'];
			// 不再将ID强制设置为694319649
			// $row['id'] = '694319649';
			$value = 1;
		}elseif($row_shequ['type'] == 'jiuwu'){

		}elseif($row_shequ['type'] == 'shangzhanwl'){
			$row['price'] = 9999;
			$row['type'] = 0;
			$row['minnum'] = '';
			$row['maxnum'] = '';
			$value = 1;
		}else{
			exit('{"code":-1,"msg":"目前仅支持玖伍、亿乐、直客"}');
		}

		$sort++;
		$sql="INSERT INTO `pre_tools` (`cid`,`sort`,`name`,`price`,`cost`,`cost2`,`prid`,`prices`,`input`,`inputs`,`desc`,`alert`,`shopimg`,`value`,`is_curl`,`curl`,`shequ`,`goods_id`,`goods_type`,`goods_param`,`repeat`,`multi`,`min`,`max`,`validate`,`valiserv`,`close`,`active`,`addtime`) VALUES (:cid,:sort,:name,:price,:cost,:cost2,:prid,:prices,:input,:inputs,:desc,:alert,:shopimg,:value,:is_curl,:curl,:shequ,:goods_id,:goods_type,:goods_param,:repeat,:multi,:min,:max,:validate,:valiserv,:close,:active,NOW())";
		// 根据商品状态设置close字段，0表示开启，1表示关闭
		$close = isset($row['close']) && $row['close'] == true ? 1 : 0;
		// 设置active字段为1，表示商品激活
		$active = 1;
		$data = [':cid'=>$mcid, ':sort'=>$sort, ':name'=>$row['name'], ':price'=>$row['price'], ':cost'=>0, ':cost2'=>0, ':prid'=>$prid, ':prices'=>'', ':input'=>'', ':inputs'=>'', ':desc'=>'', ':alert'=>'', ':shopimg'=>$row['shopimg'], ':value'=>$value, ':is_curl'=>2, ':curl'=>null, ':shequ'=>$shequ, ':goods_id'=>$row['id'], ':goods_type'=>$row['type'], ':goods_param'=>$goods_param, ':repeat'=>1, ':multi'=>1, ':min'=>$row['minnum'], ':max'=>$row['maxnum'], ':validate'=>0, ':valiserv'=>null, ':close'=>$close, ':active'=>$active];
		$DB->exec($sql, $data);
		$msg.=$DB->error().'<br><br>';
		$add_success++;
	}
	$result=['code'=>0, 'msg'=>'成功添加'.$add_success.'个商品<br>注意：玖伍社区需要下单参数的，请初始化商品，会自动获取对接参数、商品介绍、下单标题><br>'.$msg];
	exit(json_encode($result));

break;

default:
	exit('{"code":-4,"msg":"No Act"}');
break;
}

function get_yile_goods_list($url,$user,$pwd,$listid=array()){
	$url = $url.'.api.yilesup.net/api/goods/list';
	$param = array('api_token'=>$user, 'timestamp'=>time());
	$sign = getSign_batch($param, $pwd);
	$param['sign'] = $sign;
	$post = http_build_query($param);
	$ret = get_curl($url,$post);
	if (!$ret = json_decode($ret, true)) {
		return '打开对接网站失败';
	} elseif ($ret['status'] !== 0) {
		return $ret['message'];
	} else {
		$list = array();
		foreach ($ret['data'] as $v) {
			if(count($listid)>0){
				if(isset($listid[$v['gid']]))continue;
			}			
			$list[] = array(
				'id' => $v['gid'],
				'name' => $v['name'],
				'close' => $v['close']
			);
		}
		return $list;
	}
}
function getSign_batch($param, $key){
	$signPars = "";
	ksort($param);
	foreach ($param as $k => $v) {
		if ("sign" != $k && "" != $v) {
			$signPars .= $k . "=" . $v . "&";
		}
	}
	$signPars = trim($signPars, '&');
	$signPars .= $key;
	$sign = md5($signPars);
	return $sign;
}
function get_jiuwu_goods_list($url,$user,$pwd,$listid=array()){
	$url = $url.'/index.php?m=home&c=api&a=user_get_goods_lists_details&Api_UserName='.urlencode($user).'&Api_UserMd5Pass='.md5($pwd);
	$ret = get_curl($url);
	if (!$ret = json_decode($ret, true)) {
		return '打开对接网站失败';
	} elseif ($ret['status'] !== true) {
		return $ret['msg'];
	} else {
		$list = array();
		foreach ($ret['user_goods_lists_details'] as $v) {
			if(count($listid)>0){
				if(isset($listid[$v['id']]))continue;
			}
			$list[] = array(
				'id' => $v['id'],
				'type' => $v['goods_type'],
				'name' => $v['title'],
				'shopimg' => $v['thumb'],
				'minnum' => $v['minbuynum_0'],
				'maxnum' => $v['maxbuynum_0'],
				'price' => $v['user_unitprice'],
				'close' => $v['goods_status']
			);
		}
		return $list;
	}
}
function get_jiuwu_goods_info($url,$goods_id=0,$cookie=0){
	$data = $url;
	//$result['code'] = -1;
	//$data = get_curl($url.'/index.php?m=Home&c=Goods&a=detail&id='.$goods_id, 0, 0, base64_decode($cookie));
	$start = strpos($data, 'action="/index.php?m=home&c=order');
	$end = strpos($data, 'name="pay_type');
	if ($start > 1 && $end > 1) {
		$get = substr($data, $start, $end - $start);
		if (preg_match_all('/name="([a-z0-9A-Z\_\-]+)"/is', $get, $arr)) {
			$param = "";
			foreach ($arr[1] as $k => $item) {
				if ($item == 'need_num_0' || $item == 'goods_id' || $item == 'goods_type' || $item == 'ssnr' || $item == 'qmkg_url' || $item == 'kszp_url' || $item == 'kszy_url' || $item == 'kszp_dwz')continue;
				$param .= $item.'|';
			}
			$param = trim($param, '|');
			preg_match('/现金单价：<\/span><span  title=".*?">(.*?)<\/span>/',$data,$match);
			$result = array(
				'code' => 0,
				'message' => 'succ',
				'price' => $match[1],
				'param' => $param
			);

			//获取下单标题
			$start = strpos($data, 'action="/index.php?m=home&c=order');
			$end = strpos($data, '<span class="fixed-width-right-80">支付方式：</span>');
			$get = substr($data, $start, $end - $start);
			unset($arr);
			unset($item);
			preg_match_all('/class="fixed-width-right-80">(.*?)<\/span>/',$get,$arr);
			$param = "";
			foreach ($arr[1] as $k => $item) {
				if ($item == '接口：' || $item == '说说：' || $item == '下单赞：' || $item == '每条数量：' || $item == '下单数量：' || $item == '下单浏览：' || $item == '下单浏览量：' || $item == '下单方式：'|| $item == '下单喜欢：')continue;
				$param .= $item.'|';
			}
			$param = trim($param, '|');
	    	$input = explode('|',$param);
	    	$param = "";
	    	$zh = '';
	    	for ($i=0; $i < count($input); $i++) { 
	    		if($i == 0){
	    			if($input[$i] == '掌心ID：' || $input[$i] == '作品链接：' || $input[$i] == '歌曲Id：'){
	    				$zh = '作品链接';
	    			}else{
	    				$zh = $input[$i];
	    			}
	    			$result['input'] = str_replace('：', '', $zh);
	    		}else{
	    			if($input[$i] == '说说ID：'){
	    				$zh = '说说ID';
	    			}else{
	    				$zh = $input[$i];
	    			}
	    			$param .= str_replace('：', '', $zh).'|';
	    		}
	    	}
	    	$param = trim($param, '|');
	    	$result['inputs'] = $param;
			//获取商品介绍
			$start = strpos($data, '<div class="col-md-12 banner">');
			$end = strpos($data, '<!--内容-->');
			$get = substr($data, $start, $end - $start);
			$start = '<div class="col-md-12 banner">';
			$left = strpos($get, $start);
			$right = strpos($get, '<!--内容-->',$left);
			$get = substr($get, $left + strlen($start),$right-$left-strlen($start));
			$get = trim($get);
			$get = trim($get,'</div>');
			$get = trim($get);
			$get = trim($get,'</div>');
			$get = trim($get);
			$get = '<'.trim($get,'</div>').'>';
			$result['desc'] = $get;
		} else {
			$result['code'] = -1;
			$result['msg'] = '匹配商品POST数据失败';
		}
	} else {
		$result['code'] = -1;
		$result['msg'] = '获取商品POST数据失败';
	}
	return $result;
}
function duo_curl_jiuwu($param,$cookie,$shequid,$delay=0){
	global $DB;
	$cookie = base64_decode($cookie);
    $ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36';
    $queue = curl_multi_init();
    $map = [];
    foreach ($param as $value) {
    	$url = $value['url'];
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
		if($value['post']){
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $value['post']);
		}
		if($cookie){
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		}		
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOSIGNAL, true);
        curl_multi_add_handle($queue, $ch);
        $map[(string)$ch] = $url;

        if($delay){
        	usleep($delay);
        }
    }
    $i = 0;
    $n = 0;
    $success = 0;
    $string = '';
    do {
        while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ;
        if ($code != CURLM_OK) {
            break;
        }
        while ($done = curl_multi_info_read($queue)) {
            $info = curl_getinfo($done['handle']);
            $error = curl_error($done['handle']);
            $results = curl_multi_getcontent($done['handle']);//返回内容
            $urlarr = parse_url($info['url']);

            $data = get_jiuwu_goods_info($results);

            if($data['code'] == 0){
            	$id = getSubstr($urlarr['query'].'&','&id=','&');
            	$string .= $data['desc'].'<br><hr><br>'.$id;
	    		$sql = "UPDATE `pre_tools` SET input='{$data['input']}',inputs='{$data['inputs']}',goods_param='{$data['param']}',close='0',active='1',`desc`=:desc WHERE shequ='{$shequid}' AND goods_id='{$id}' AND goods_param='694319649'";
	    		$desc = [':desc'=>$data['desc']];
	    		$DB->exec($sql,$desc);
	    		$success++;
            }else{
            	$n++;
            }
           $i++;
            curl_multi_remove_handle($queue, $done['handle']);
            curl_close($done['handle']);
        }
        if ($active > 0) {
            curl_multi_select($queue, 0.5);
        }
    } while ($active);
    curl_multi_close($queue);
    $ret = '本次获取'.$i.'个，成功 '.$success.' 个，失败 '.$n.' 个';
    return $ret;
}
function file_download($url,$path=0){
	$state = @file_get_contents($url,0,null,0,1);//获取网络资源的字符内容
    if($state){
    	if($path){
			$filename = $path;//文件名称生成
    	}else{
    		$filename = date("dMYHis").'.jpg';//文件名称生成
    	}
	    ob_start();//打开输出
	    readfile($url);//输出图片文件
	    $img = ob_get_contents();//得到浏览器输出
	    ob_end_clean();//清除输出并关闭
	    $size = strlen($img);//得到图片大小
	    $fp2 = @fopen($filename, "a");       
	    fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
	    fclose($fp2);       
	    return true;
    }else{       
       return false;
    }
}

function goods_list_shangzhanwl_cate($url,$user,$pwd,$cid,$listid=array()){
		if($cid == '全部'){
			$url = $url.'/api.php/Client/goodsList';
			$param = array('customerid'=>$user);
			$sign = md5($user . $pwd);
		}else{
			$url = $url.'/api.php/Client/getCateGoods';
			$param = array('customerid'=>$user, 'cate_id'=>$cid);
			$sign = md5($user . $cid. $pwd);
		}
		$param['sign'] = $sign;
		$post = http_build_query($param);
		$ret = get_curl($url, $post);
		if (!$ret = json_decode($ret, true)) {
			return '打开对接网站失败';
		} else if ($ret['code'] != 1000) {
			return $ret['info'];
		} else {
			$list = array();
			foreach ($ret['data'] as $v) {
				if(count($listid)>0){
					if(isset($listid[$v['id']]))continue;
				}
				$list[] = array(
					'id' => $v['id'],
					'name' => $v['name'],
					'type' => $v['type'],
					'price' => $v['price'],
					'stock_state' => $v['stock_state'],
					'supply_state' => $v['supply_state'],
					'stock_num' => $v['stock_num']
				);
			}
			return $list;
		}
	}