<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\HttpClient;
use Yilianyun\Config\YlyConfig;
use Yilianyun\Api\PrintService;
use Yilianyun\Oauth\YlyOauthClient;
use think\Cache;

class Printer extends Model
{

    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        return $base['printer'];
    }
    
    public static function getTypeText($type){
        $list = ['1'=>'易联云(K4)','2'=>'飞鹅(FP-58W)'];
        if(empty($list[$type])){
            return "未知打印机";
        }
        
        return $list[$type];
    }
    
    public static function orderPrint($order_id,$type=0){
        $set = self::getSet();
        if($set['status'] != 1){
            return __json(0,"未开启打印");
        }
		if($type == 1){
			$order = Db::name("bbfx_scoreshop_order")->where("id",$order_id)->find();
		}
        else{
			$order = Db::name("bbfx_order")->where("id",$order_id)->find();
		}
        if(empty($order)){
            return __json(0,"订单不存在");
        }
        if($order['is_pay'] != 1){
            // return __json(0,"订单未支付");
        }
        
        $print = Db::name("bbfx_printer")->where(['id'=>$set['printer_id']])->find();
        if(empty($print)) {
			return __json(0,"打印机数据不存在");
		}
		$content = iunserializer($print['content']);
		$print_type = $print['type'];
		$print = $content['type'.$print['type']];
		if(empty($print)){
		    return __json(0,"打印机参数错误");
		}
		
// 		print_r(111);die;
		if($print_type == 1){
		    // 易联云打印机
		    $content = self::YiLianYun($order_id,$type);
			
			addFileLog("printer",$content);
			
			// echo "<pre>"; 
			// print_r($print);die;

    		// $result = self::action_print($print['partner'], $print['machine_code'], urlencode($content), $print['apikey'], $print['terminal_secret']);
			// 易联云开发文档：https://www.kancloud.cn/ly6886/oauth-api/3170299
			try {
				$config = new YlyConfig($print['client_id'], $print['client_secret']);
				//v2.0接口需设置请求域名
				$config->setRequestUrl('https://open-api.10ss.net/v2');
				$client = new YlyOauthClient($config);

				$access_token = Cache::get("yly_access_token_".$print['client_id']);
				if(!empty($access_token)){
					$yly_access_token_time = Cache::get("yly_access_token_time_".$print['client_id']);
					if($yly_access_token_time <= time()){
						$access_token = "";
					}
				}

				if(empty($access_token)){
					
					if(intval($print["client_type"]) == 1){
						$token = $client->getToken($print["client_authcode"]);
					}
					else{
						$token = $client->getToken();
					}

					if($token->expires_in > time()){
						$expires_time = $token->expires_in;
					}
					else{
						$expires_time = $token->expires_in + time();
					}
					$access_token = $token->access_token;
					Cache::set("yly_access_token_".$print['client_id'],$access_token);
					Cache::set("yly_access_token_time_".$print['client_id'],$expires_time);
				}
				

				$PrintService = new PrintService($access_token, $config);
				$result = $PrintService->index($print['machine_code'],$content,$order['order_no']);

			} catch (\Exception $e) {
				return __json(0,$e->getMessage());
			}

			// var_dump($result);
			
			$result = json_decode(json_encode($result),true);
		}
		else if($print_type == 2){
		    // 飞蛾打印机
		    
		    header("Content-type: text/html; charset=utf-8");
			$contents = array(
				'user' => $print['user'],
				'stime' => time(),
				'sig' => sha1($print['user'] . $print['feukey'] . time()),
				'apiname' => 'Open_printMsg',
				'sn' => $print['dyjnumber'],
				'content' => $content,
				'times' => 1, //打印次数
			);
		    $content = self::feie($order_id,$type);
			$contents['content'] = $content;
		    addFileLog("printer",$content);
			$client = new HttpClient('api.feieyun.cn', '80');
			if (!$client->post('/Api/Open/', $contents)) {
				$result = 'error';
			} 
			else {
				$result = $client->getContent();
			}
		}
// 		print_r($result);die; 
		addFileLog("printer",json_encode($result));
		// echo "<pre>";
		// print_r($result);die;
		return __json(1,"操作成功",$result);
    }
    
    /**
    * 飞蛾打印机
    */
    public static function feie($order_id,$type){
		if($type == 1){
			$order = Db::name("bbfx_scoreshop_order")->where("id",$order_id)->find();
		}
        else{
			$order = Db::name("bbfx_order")->where("id",$order_id)->find();
		}
        if(empty($order)){
            return false;
        }
        $set = self::getSet();
        
        if($type == 1){
			$order_goods = Db::name("bbfx_scoreshop_order_goods")->where(['order_id'=>$order['id']])->select();
		}
        else{
			$order_goods = Db::name("bbfx_order_goods")->where(['order_id'=>$order['id']])->select();
		}
        
		$newTel = $order['delivery_mobile'];
		if($set['show_intact_mobile'] !== 0){
			$newTel = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $order['delivery_mobile']);
		}
		
		
		$order_no = $order['order_no'];
		$selfMode = '';
		$orderItem = "发货订单";
		if ($order['order_type'] == 1 || $order['order_type'] == 4) {
			$orderItem = "虚拟商品";
		}
		else if ($order['order_type'] == 3) {
			$orderItem = "自提订单";
		}
		
		
		$payType = '未支付';
		$origin = '微信小程序';
		$deliveryMode = '商家配送';
		
		switch ($order['paytype']) {
    		case 1:
    			$payType = '微信支付';
    			break;
    		case 2:
    			$payType = '余额支付';
    			break;
    	}
        
		
		$content = "--------------------------------<BR>";
		$content .= "订单来源：" . $orderItem . "(" . $origin . ")<BR>";
		
		$content .= "订单号：" . $order['order_no'] . "<BR>";
		$content .= "下单时间：" . date('Y-m-d H:i:s', $order['createtime']) . "<BR>";
		if ($order['remarks']) {
			$content .= "<BOLD>备注：" . $order['remarks'] . "</BOLD><BR>";
		}
		$content .= "--------------------------------<BR>";
		$content .= "名称             数量    价格<BR>";
		$content .= self::feiStyle($order_goods);
		
		$total = 0;
		foreach ($order_goods as $key => $val){
		    $total += $val['total'];
		}
		
		$content .= "<C>----------其它费用----------</C>\n";
		
		$content .= "快递费：" . $order['express_fee'] . "<BR>";
		$content .= "商品合计X" . $total . "<BR>";
		
		$content .= "--------------------------------<BR>";
		
		if ($order['discount_price'] > 0) {
			$content .= "优惠金额：￥" . $order['discount_price'] . "<BR>";
		}
		
		if($type == 1){
			$content .= "<BOLD>实付：" . $order['score'] . "积分<BOLD><BR><BR>";
		}
		else{
			$content .= "<BOLD>实付：￥" . $order['price'] . "<BOLD><BR><BR>";
		}
		if($order['order_type'] == 2 && $order['is_hexiao'] != 1  && $set['show_delivery'] !== 0){
			$content .= "<BOLD><B>" . $order['delivery_province'].$order['delivery_city'].$order['delivery_area'].$order['delivery_street'].$order['delivery_address'] . "</B></BOLD><BR><BR>";
			$content .= "<BOLD><B>" . $order['delivery_username'] . "</B>  <B>" . $newTel . "</B></BOLD><BR><BR>";
		}
		
		if ($set['codeUrl']) {
			$content .= "<QR>" . $set['qrcode']. "</QR><BR>";
		}
		if ($set['note']) {
			$content .= "<C>" . $set['note'] . "</C><BR>";
		}
		
		return $content;
    }
    
    public static function feiStyle($arr, $A = 20, $B = 6, $C = 3, $D = 6){
		$orderInfo = '';
		foreach ($arr as $k5 => $v5) {
			$goods = iunserializer($v5['goods_info']);
			$name = $goods['title'];
			if (!empty($goods['sku_name'])) {
				$name = $goods['title'] . '(' . $goods['sku_name'] . ')';
			}

			
			$num = $v5['total'];
			$price = $v5['score'];
			

			$kw3 = '';
			$kw1 = '';
			$kw2 = '';
			$kw4 = '';
			$str = $name;
			$blankNum = $A; //名称控制为14个字节
			$lan = mb_strlen($str, 'utf-8');
			$m = 0;
			$j = 1;
			$blankNum++;
			$result = array();

			if (strlen($num) < $C) {
				$k2 = $C - strlen($num);
				for ($q = 0; $q < $k2; $q++) {
					$kw2 .= ' ';
				}
				$num = $num . $kw2;
			}

			for ($i = 0; $i < $lan; $i++) {
				$new = mb_substr($str, $m, $j, 'utf-8');
				$j++;
				if (mb_strwidth($new, 'utf-8') < $blankNum) {
					if ($m + $j > $lan) {
						$m = $m + $j;
						$tail = $new;
						$lenght = iconv("UTF-8", "GBK//IGNORE", $new);
						$k = $A - strlen($lenght);
						for ($q = 0; $q < $k; $q++) {
							$kw3 .= ' ';
						}
						if ($m == $j) {
							$tail .= $kw3 . ' ' . $num . ' ' . $price ;
						} else {
							$tail .= $kw3 . '<BR>';
						}
						break;
					} else {
						$next_new = mb_substr($str, $m, $j, 'utf-8');
						if (mb_strwidth($next_new, 'utf-8') < $blankNum) {
							continue;
						} else {
							$m = $i + 1;
							$result[] = $new;
							$j = 1;
						}
					}
				}

			}
			$head = '';
			foreach ($result as $key => $value) {
				if ($key < 1) {
					$v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
					$v_lenght = strlen($v_lenght);
					if ($v_lenght == 13) {
						$value = $value . " ";
					}

					$head .= $value . ' ' . $num . ' ' . $price ;
				} else {
					$head .= $value . '<BR>';
				}
			}

			$orderInfo .= $head . $tail . '<BR>';

		}
		return $orderInfo;
	}
    
    /**
    * 易联云打印机
    */
    public static function YiLianYun($order_id,$type){
        if($type == 1){
			$order = Db::name("bbfx_scoreshop_order")->where("id",$order_id)->find();
		}
        else{
			$order = Db::name("bbfx_order")->where("id",$order_id)->find();
		}
		
        if(empty($order)){
            return false;
        }
        $set = self::getSet();
        
		if($type == 1){
			$order_goods = Db::name("bbfx_scoreshop_order_goods")->where(['order_id'=>$order['id']])->select();
		}
        else{
			$order_goods = Db::name("bbfx_order_goods")->where(['order_id'=>$order['id']])->select();
		}
        
		$newTel = $order['delivery_mobile'];
		if($set['show_intact_mobile'] === 0){
			$newTel = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $order['delivery_mobile']);
		}
		
		$order_no = $order['order_no'];
		$selfMode = '';
		$orderItem = "发货订单";
		if ($order['order_type'] == 1 || $order['order_type'] == 4) {
			$orderItem = "虚拟商品";
		}
		else if ($order['order_type'] == 3) {
			$orderItem = "自提订单";
		}
		
		
		$payType = '未支付';
		$origin = '微信小程序';
		$deliveryMode = '商家配送';
		
		switch ($order['paytype']) {
    		case 1:
    			$payType = '微信支付';
    			break;
    		case 2:
    			$payType = '余额支付';
    			break;
    	}
		
		$content = "--------------------------------\n";
		$content .= "订单来源：" . $orderItem . "(" . $origin . ")\n";
		
		
		
		$content .= "订单编号：" . $order['order_no'] . "\n";
		$content .= "下单时间：" . date('Y-m-d H:i:s', $order['createtime']) . "\n";
		if ($order['remarks']) {
			$content .= "<FB>备注:" . $order['remarks'] . "</FB>\n";
		}
		$content .= "--------------------------------\n";
		$content .= '名称' . str_repeat(" ", 10) . "数量         价格\n";
		
		$content .= "<FS><table>";
		$total = 0;
		foreach ($order_goods as $key => $value) {
		    $total += $value['total'];
		    $goods = iunserializer($value['goods_info']);
			$name = $goods['title'];
			if (!empty($goods['sku_name'])) {
				$name = $goods['title'] . '(' . $goods['sku_name'] . ')';
			}
		
			if($type == 1) {
				$content .= "<tr><td>" . $name . "</td><td>×" . $value['total'] . "</td><td>  " . $value['score'] . "积分</td></tr>";
			}
			else{
				$content .= "<tr><td>" . $name . "</td><td>×" . $value['total'] . "</td><td>  ￥" . $value['price'] . "</td></tr>";
			}
		}
		$content .= "</table></FS>\n";
		
		$content .= "<center>----------其它费用----------</center>\n";
		$content .= "快递费：￥" . $order['express_fee'] . "\n";
		$content .= "商品合计X" . $total . "\n";
		
		$content .= "--------------------------------\n";
		
		if ($order['discount_price'] > 0) {
			$content .= "优惠金额：￥" . $order['discount_price'] . "]\n";
		}
		
		if($type == 1) {
			$content .= "<FS2>实付：" . $order['score'] . "积分</FS2>\n";
		}
		else{
			$content .= "<FS2>实付：￥" . $order['price'] . "</FS2>\n";
		}
		$content .= "--------------------------------\n";
		
		if($order['order_type'] == 2 && $order['is_hexiao'] != 1  && $set['show_delivery'] !== 0){
		    $content .= "<FB><FS>" . $order['delivery_province'].$order['delivery_city'].$order['delivery_area'].$order['delivery_street'].$order['delivery_address']. "</FS></FB>\n\n";
		    $content .= "<FB><FS>" . $order['delivery_username'] . "</FS>  <FS>" . $newTel . "</FS></FB>\n\n";
		}
		
		if ($set['qrcode']) {
			$content .= "<QR>" . $set['qrcode'] . "</QR>\n\n";
		}
		if ($set['note']) {
			$content .= "<center>" . $set['note'] . "</center>\n";
		}
		
		return $content;
    }
    
    /**
     * 生成签名sign
     * @param  array $params 参数
     * @param  string $apiKey API密钥
     * @param  string $msign 打印机密钥
     * @return   string sign
     */
    public static function generateSign($params, $apiKey,$msign)
    {
        //所有请求参数按照字母先后顺序排
        ksort($params);
        //定义字符串开始所包括的字符串
        $stringToBeSigned = $apiKey;
        //把所有参数名和参数值串在一起
        foreach ($params as $k => $v)
        {
            $stringToBeSigned .= urldecode($k.$v);
        }
        unset($k, $v);
        //定义字符串结尾所包括的字符串
        $stringToBeSigned .= $msign;
        //使用MD5进行加密，再转化成大写
        return strtoupper(md5($stringToBeSigned));
    }
    /**
     * 生成字符串参数
     * @param array $param 参数
     * @return  string        参数字符串
     */
    public static function getStr($param)
    {
    	$str = '';
    	foreach ($param as $key => $value) {
    		$str=$str.$key.'='.$value.'&';
    	}
    	$str = rtrim($str,'&');
    	return $str;
    }
    /**
     * 打印接口
     * @param  int $partner     用户ID
     * @param  string $machine_code 打印机终端号
     * @param  string $content      打印内容
     * @param  string $apiKey       API密钥
     * @param  string $msign       打印机密钥
     */
    public static function  action_print($partner,$machine_code,$content,$apiKey,$msign)
    {
    	$param = array(
    		"partner"=>$partner,
    		'machine_code'=>$machine_code,
    		'time'=>time(),
    		);
    	//获取签名
    	$param['sign'] = self::generateSign($param,$apiKey,$msign);
    	$param['content'] = $content;;
    	$str = self::getStr($param);
    	return self::sendCmd('http://open.10ss.net:8888',$str);
    }
    /**
     *  添加打印机
     * @param  int $partner     用户ID1		
     * @param  string $machine_code 打印机终端号
     * @param  string $username     用户名
     * @param  string $printname    打印机名称
     * @param  string $mobilephone  打印机卡号
     * @param  string $apiKey       API密钥
     * @param  string $msign       打印机密钥
     */
    public static function action_addprint($partner,$machine_code,$username,$printname,$mobilephone,$apiKey,$msign)
    {
    	$param = array(
    		'partner'=>$partner,
    		'machine_code'=>$machine_code,
    		'username'=>$username,
    		'printname'=>$printname,
    		'mobilephone'=>$mobilephone,
    		);
    	$param['sign'] = self::generateSign($param,$apiKey,$msign);
    	$param['msign'] = $msign;
    	$str = self::getStr($param);
    	return self::sendCmd('http://open.10ss.net:8888/addprint.php',$str);
    }
    /**
     * 删除打印机
     * @param  int $partner      用户ID
     * @param  string $machine_code 打印机终端号
     * @param  string $apiKey       API密钥
     * @param  string $msign        打印机密钥
     */
    public function action_removeprinter($partner,$machine_code,$apiKey,$msign)
    {
    	$param = array(
    		'partner'=>$partner,
    		'machine_code'=>$machine_code,
    		);
    	$param['sign'] = $this->generateSign($param,$apiKey,$msign);
    	$str = self::getStr($param);
    	return self::sendCmd('http://open.10ss.net:8888/removeprint.php',$str);
    }
    /**
     * 发起请求
     * @param  string $url  请求地址
     * @param  string $data 请求数据包
     * @return   string      请求返回数据
     */
    public function sendCmd($url,$data)
    {
        $curl = curl_init(); // 启动一个CURL会话      
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址                  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测    
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在      
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交     
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转      
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer      
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求      
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包      
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循     
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容      
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 
               
        $tmpInfo = curl_exec($curl); // 执行操作      
        if (curl_errno($curl)) {      
           echo 'Errno'.curl_error($curl);      
        }      
        curl_close($curl); // 关键CURL会话    
		
		
		
       	return $tmpInfo; // 返回数据      
    }
    
    public static function getOrderVariable($type=0){
        $list = array(
            array("val"=>"[[商品名称]]","title"=>"商品名称","key"=>"goods_name"),
            array("val"=>"[[商品价格]]","title"=>"商品价格","key"=>"goods_price"),
            array("val"=>"[[商品数量]]","title"=>"商品数量","key"=>"goods_total"),
            array("val"=>"[[订单编号]]","title"=>"订单编号","key"=>"order_no"),
            array("val"=>"[[订单金额]]","title"=>"订单金额","key"=>"order_price"),
            array("val"=>"[[优惠金额]]","title"=>"优惠金额","key"=>"order_discount"),
            array("val"=>"[[收货人]]","title"=>"收货人","key"=>"delivery_username"),
            array("val"=>"[[收货地址]]","title"=>"收货地址","key"=>"delivery_address"),
            array("val"=>"[[收货电话]]","title"=>"收货电话","key"=>"delivery_mobile"),
            array("val"=>"[[运费]]","title"=>"运费","key"=>"express_fee"),
            array("val"=>"[[订单时间标题]]","title"=>"订单时间标题","key"=>"order_time_title"),
            array("val"=>"[[订单时间]]","title"=>"订单时间","key"=>"order_time_title"),
            array("val"=>"[[订单状态]]","title"=>"订单状态","key"=>"statusText"),
            array("val"=>"[[商品价格详情]]","title"=>"商品价格详情","key"=>"goods_price_detail"),
        );
        
        if($type == 1){
            $variables = [];
            
            foreach ($list as $key => &$val){
                
            }
            unset($val);
        }
        else{
            $variables = $list;
        }
    }
}