
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
const query=require('querystring');
/*-------------------------------------------------------------------------------------------*/
    
// https请求操作
/*-------------------------------------------------------------------------------------------*/	
    class fetch
    {
        static get(url,send,_path,gbk='')
        {	
			var https
			if(url.indexOf('http://')==0)
			{
				https=require('http');
			}
			else
			{
				https=require('https');
			}

			var pro=new Promise
			(
				function (resolve,reject)
				{
					if(send instanceof Object)
					{
						try 
						{
							send='?'+query.stringify(send,"&",'=');
						} 
						catch (error) 
						{
							send='';
							console.error('注意：'+error);
						}
					}
					var https_cli=https.get
					(
						url+(send?send:''),function(d)
						{
							d.$gbk=gbk
							fetch.logic(d,_path,resolve,reject)
						}
					);

					fetch.info(https_cli,resolve)

				}
			)
			return pro;
		}
		
 		static post(opt,send,_path,gbk='')
        {
			var https
			if(opt.type=='http')
			{
				https=require('http');
			}
			else
			{
				https=require('https');
			}
			var query=require('querystring');

			var pro=new Promise
			(
				function (resolve,reject)
				{
					if(send instanceof Object)
					{
						try 
						{
							send='?'+query.stringify(send,"&",'=');
						} 
						catch (error) 
						{
							send='';
							console.error('注意：'+error);
						}
					}
					if(!(opt.headers instanceof Object))
					{
						opt.headers={};
					}
					
					if(!Buffer.isBuffer(opt.data) && (opt.data instanceof Object))
					{
						opt.data=query.stringify(opt.data,"&",'=');
					}
					
					if(!opt.headers['Content-Type'])
					{
						opt.headers['Content-Type']='application/x-www-form-urlencoded; charset=utf-8';
						opt.data=opt.data?opt.data:'';
					}
					opt.headers['Content-Length']=Buffer.byteLength(Buffer.from(opt.data));

					opt.rejectUnauthorized=(opt.rejectUnauthorized===undefined)?false:opt.rejectUnauthorized
					opt.path=(opt.path?opt.path:'/')+(send?send:'');
					var https_cli= https.request
					(
						opt,function (d)
						{
							d.$gbk=gbk
							fetch.logic(d,_path,resolve,reject)
						}
					);
					if(opt.method!='POST')
					{
						https_cli.end();
					}
					else
					{
						https_cli.end(opt['data']);
					}
					fetch.info(https_cli,resolve)
				}
			)
			return pro;
		}
		
		static upload(opt,send,_path,gbk='')
        {
			var https
			if(opt.type=='http')
			{
				https=require('http');
			}
			else
			{
				https=require('https');
			}
			var fs=require('fs')
			var query=require('querystring');

			var pro=new Promise
			(
				function (resolve,reject)
				{
					var _file=$Config.root+opt.file;
					fs.stat
					(
						_file,function(err,stat)
						{
							if(stat && stat.isFile())
							{
								if(send instanceof Object)
								{
									try 
									{
										send='?'+query.stringify(send,"&",'=');
									} 
									catch (error) 
									{
										send='';
										console.error('注意：'+error);
									}
								}
								if(!(opt.headers instanceof Object))
								{
									opt.headers={};
								}
								var boundaryKey = '----' + Date.now();
								opt.headers['Content-Type']='multipart/form-data; boundary=' + boundaryKey;
								opt.path=(opt.path?opt.path:'/')+(send?send:'');
				
								opt.data=opt.data instanceof Object?opt.data:{};
								
								var str = '';
								for (let key in opt.data) 
								{
									str+='--'+boundaryKey +`\r\nContent-Disposition: form-data; name="${key}"\r\n\r\n${opt.data[key]}\r\n`;
								}
								var bin='--'+boundaryKey +`\r\nContent-Disposition: form-data; name="upload"; filename="${opt.file}"\r\n` +
								'Content-Type: application/other\r\n\r\n';
								var bin_end='\r\n--' + boundaryKey + '--';
								opt.headers['Content-Type']='multipart/form-data; boundary=' + boundaryKey;
								opt.headers['Content-Length']=fs.statSync(_file).size+Buffer.byteLength(Buffer.from(bin))+
											Buffer.byteLength(Buffer.from(bin_end))+Buffer.byteLength(Buffer.from(str));
								opt.headers['Connection']='keep-alive';
								opt.rejectUnauthorized=(opt.rejectUnauthorized===undefined)?false:opt.rejectUnauthorized
								var https_cli= https.request
								(
									opt,function (d)
									{
										d.$gbk=gbk
										fetch.logic(d,_path,resolve,reject)
									}
								);

								https_cli.write(str);
								
								https_cli.write(bin);
				
								var fileStream = fs.createReadStream(_file);
								fileStream.pipe(https_cli,{ end: false });
								fileStream.on
								(
									'end',function()
									{
										https_cli.end(bin_end);
									}
								);
				
								fetch.info(https_cli,resolve)
							}
							else
							{
								resolve({data:false,head:d,cookie:''});;
							}
						}
					)
				}
			)
			return pro;
		}

		static logic(d,_path,resolve)
		{
			var da='';
			if(_path)
			{
				d.setEncoding('binary');
				if(_path!==true)
				{
					const fs=require('fs');
					let _ur=_path;
					d.pipe(fs.createWriteStream(_ur,{ encoding: 'binary'})).
					on
					(
						'error', function(error) 
						{
							console.error("文件下载发生错误------"+`描述：${error}`);
						}
					);
					da=_ur;
				}
			}
			else
			{
				if(d.$gbk) 
				{
					da=[]
				}
				else d.setEncoding('utf8');
				d.on
				(
					'data',function(dat)
					{
						if(d.$gbk) 
						{
							da.push(dat)
							d.$len=(d.$len?d.$len:0)+dat.length
						}
						else da+=dat;
					}
				)
			}
			d.on
			(
				'end',function()
				{
					if(_path===true)
					{
						resolve(da)
						return;
					}
					if(d.$gbk)
					{
						da=Buffer.concat(da,d.$len)
						da=$Sys.model('/tool/com/gbk','decode',[da])
					}
					if(d.headers['content-type'] && d.headers['content-type'].indexOf('application/json')!=-1)
					{
						try  
						{
							da=JSON.parse(da)
						} 
						catch (error){}	
					}
					resolve({data:da,head:d,cookie:$Sys.model('/request/cookie','get')(d)});
				}
			)
		}

		static info(https_cli,resolve)
		{
			https_cli.on
			(
				'close',function ()
				{
					console.warn('HTTP/S客户端关闭');
				}
			);

			https_cli.on
			(
				'error',function err(e)
				{
					resolve({data:false,head:'',cookie:''});;
					console.error('HTTP/S客户端错误------'+`描述：${e}`);
				}
			);
		}
    }
/*-------------------------------------------------------------------------------------------*/    
module.exports=fetch;