<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 对账统计
 */
class Reconciliation extends MY_Controller
{
	public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    public function __construct()
    {
        parent::__construct();
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize'  => 1024*5,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls','.xlsx','.csv')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $this->load->library('curl');
    }
    
    //月度流水对账 全部订单
    public function index($rate = 7.7695){
    	if( $this->env == 1 ){
			$url = $this->config->item('officialUrl');
		}else{
			$url = $this->config->item('localUrl');
			$this->postData['demo'] = 1;
		}
		if( $month = get_cookie('payuserindex_stime') ){
			
        }else{
        	if(date("m") <= 10){
        		$month = date("Y")."-0".(date("m")-1);
        	}else{
        		$month = date("Y")."-".(date("m")-1);
        	}
        }
		
		
		$this->postData['mod'] = 'Reconciliation';
		$this->postData['act'] = 'month';
		$this->postData['time'] = $month;
		$res = $this->curl->req($url, $this->postData);
		
		$retData = json_decode($res, TRUE);
		//商品数据
		$goods = [];
		foreach($retData['goods'] as $k => $v){
			$goods[$v['gid']] = $v;
		}
		
		$google = [];
		$googleFee = [];
		$googleTotal = $googleTotalFee = $terraceTotal = 0;
		foreach($retData['reconciliation'] as $k => $v){
			if($v['Type'] == 1){
				$googleFee[$v['PlatformSerialNum']] = $v;
				$googleTotalFee += abs($v['AmountMerchant']);
			}else{
				$google[$v['PlatformSerialNum']] = $v;
				$googleTotal += $v['AmountMerchant'];
			}
		}
		//平台有Google账单没有
		$terraceOrderNo = []; 
		$terraceOrder = [];
		foreach($retData['list'] as $k => $v){
			$retData['list'][$k]['gname'] = $goods[$v['gid']]['gname'];
			if(isset($google[$v['platform_serial_num']])){
				$retData['list'][$k]['googlePrice'] = $google[$v['platform_serial_num']]['AmountMerchant'];
			}else{
				$terraceOrderNo[] = $retData['list'][$k];
			}
			if(isset($googleFee[$v['platform_serial_num']])){
				$retData['list'][$k]['fee'] = $googleFee[$v['platform_serial_num']]['Fee'];
			}
			$terraceTotal += $v['pusd'];
			$terraceOrder[$v['platform_serial_num']] = $retData['list'][$k];
		}

		//平台没有Google账单有
		$googleOrderNo = [];
		foreach($google as $k => $v){
			if(!isset($terraceOrder[$v['PlatformSerialNum']])){
				$googleOrderNo[] = $v;
			}
		}
		
        $data['recordsTotal'] = count($retData['list']);
        $data['recordsFiltered'] = count($retData['list']);
        $data['data'] = $retData['list'];
        $data['total'] = count($retData['list']);
        $data['rate'] = $rate; 
        $data['month'] = $month;
        $data['terraceOrderNum'] = count($retData['list']);
        $data['googleOrderNum'] = count($google);
        $data['googleTotal'] = $googleTotal;
        $data['googleTotalFee'] = $googleTotalFee;
        $data['terraceTotal'] = $terraceTotal;
        $data['terraceOrderNo'] = $terraceOrderNo;
        $data['googleOrderNo'] = $googleOrderNo;
        
        $this->load->view('reconciliation/index', $data);
    }
    
    //月度流水对账2 统计列表
    public function index2($channletype = 1){
    	$data = array('channelList' => array(1 =>'GooglePlay', 2 => 'IOS'), 'list' => [], 'channeltype' => $channletype, 'currencyname' => array(1 => '美元', 2 => '港币', 3 => '美元'));
    	if( $this->env == 1 ){
			$url = $this->config->item('officialUrl');
		}else{
			$url = $this->config->item('localUrl');
			$this->postData['demo'] = 1;
		}
		if( $month = get_cookie('payuserindex_stime') ){
			
        }else{
        	if(date("m") <= 10){
        		$month = date("Y")."-0".(date("m")-1);
        	}else{
        		$month = date("Y")."-".(date("m")-1);
        	}
        }
		
		$this->postData['mod'] = 'Reconciliation';
		$this->postData['act'] = 'payStreamSta';
		$this->postData['channel'] = $channletype;
		$res = $this->curl->req($url, $this->postData);
		$retData = json_decode($res, TRUE);
		$data['list'] = $retData;
		$data['channelname'] = $data['channelList'][$channletype];
		
		if(date("m") <= 10){
    		$month = date("Y")."-0".(date("m")-1);
    	}else{
    		$month = date("Y")."-".(date("m")-1);
    	}
        $data['month'] = $month;
        
        $this->load->view('reconciliation/index2', $data);
    }
    
    //导入数据 月度流水收益
    public function import($month){
    	try {

	        $file = $this->uploader->getFileInfo();
	        
	        //指定文件类型 效率高
	        //$xlsReader = IOFactory::createReader('CSV');
	        //$xlsReader->setReadDataOnly(true);
	        //$xlsReader->setLoadSheetsOnly(true);
	        //$Sheets = $xlsReader->load($file['url']);
	        //$dataArray = $Sheets->getSheet(0)->toArray();
	        //unset($dataArray[0]);
	        
	        //自动获取类型 效率低
	        $xlsReader = IOFactory::load($file['url']);
	        $dataArray = $xlsReader->getSheet(0)->toArray();
	        unset($dataArray[0]);
	        
			$datas = array();
	        foreach ($dataArray as $key=>$row){
	            $data = array();
	            $data['month'] = $month;
	            $data['platform_serial_num'] = $row[0];
	            $data['BuyerCurrency'] = $row[11];
	            $data['Rate'] = $row[16];
	            $data['AmountBuyer'] = $row[15];
	            $data['MerchantCurrency'] = $row[17];
	            $data['AmountMerchant'] = $row[18];
	            $data['DateTime'] = $row[2];
	            if($row[4] == 'Google fee'){
	            	$data['fee'] = $row[18];
	            	$data['type'] = 1;
	            }else{
	            	$data['fee'] = 0;
	            	$data['type'] = 0;
	            }
	            $datas[] = $data;
	        }
	        
	        $posts = $this->postData;
	        $posts['mod'] = 'Reconciliation';
	        $posts['act'] = 'import';
	        $posts['data'] = json_encode($datas,JSON_UNESCAPED_UNICODE);
	        $url = $this->config->item('officialUrl');
	        $retData = $this->curl->req($url, $posts);
	        if($retData){
	        	return $this->response(0, '操作成功');
	        }else{
	        	return $this->response(1, '操作失败');
	        }
        
    	}
		catch (\Exception $e)
		{
		        die($e->getMessage());
		}
    }
    
    //导入数据 月度流水销售
    public function import2($month){
    	try {

	        $file = $this->uploader->getFileInfo();

	        //自动获取类型 效率低
	        $xlsReader = IOFactory::load($file['url']);
	        $dataArray = $xlsReader->getSheet(0)->toArray();
	        unset($dataArray[0]);
	        
			$datas = array();
			$other_totalmoney = $other_ordernum = 0;
			$currency = [];
	        foreach ($dataArray as $key=>$row){
	            $data = array();
	            $data['platform_serial_num'] = $row[0];//订单号
	            $data['currency'] = $row[9];//单位
	            $data['timestamp'] = $row[2];//创建时间
	            $data['price'] = $row[10];//价格
	            $data['taxes'] = $row[11];//税费
	            $data['charged_amount'] = $row[12];//金额
	            $datas[] = $data;
	            $other_ordernum++;
	            $other_totalmoney += $this->rate($data['currency']) * $data['charged_amount'];
	        }
			
	        //保存文件
	        $contentStr = json_encode($datas);
	        $dir = "./deBUG/payStream/";
	        if (!is_dir($dir)){
	            $old = umask(0);
	            $ret = mkdir($dir, 0775, true);
	            umask($old);
	        }
	        $ret = file_put_contents($dir.$month.".txt", $contentStr);
			
	        if($ret){
	        	$posts = $this->postData;
		        $posts['mod'] = 'Reconciliation';
		        $posts['act'] = 'savePayStream';
		        $posts['month'] = $month;
		        $posts['channel'] = $channel;
		        $posts['exchange_rate'] = 7.9;
		        $posts['other_totalmoney'] = $other_totalmoney;
		        $posts['other_ordernum'] = $other_ordernum;
		        $url = $this->config->item('officialUrl');
	        	$retData = $this->curl->req($url, $posts);
	        	
	        	return $this->response(0, '操作成功');
	        }else{
	        	return $this->response(1, '操作失败');
	        }
        
    	}
		catch (\Exception $e)
		{
		    die($e->getMessage());
		}
    }
    
    /**
     * ajax编辑财务收入
     */
    public function ajaxEditIncome(){
        $date = $this->input->post('date');
        $field = $this->input->post('field');
        $val = $this->input->post('val');

        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }
        $this->postData['mod'] = 'Reconciliation';
        $this->postData['act'] = 'ajaxEditIncome';
        $postData = array_merge(array('date' => $date, 'field' => $field, 'val' => $val), $this->postData);
        $res = $this->curl->req($url, $postData);
        echo $res;
    }
    
    //汇率
    public function rate($currency){
    	$number = 0;
    	switch($currency){
    		case 'USD':
    			$number = 7.7509;
    		break;
    		case 'GBP':
    			$number = 9.6406;
    		break;
    		case 'EUR':
    			$number = 8.3919;
    		break;
    		case 'CAD':
    			$number = 5.4998;
    		break;
    		case 'DKK':
    			$number = 1.125;
    		break;
    		case 'RON':
    			$number = 1.7359;
    		break;
    		case 'JPY':
    			$number = 0.07193;
    		break;
    		case 'PLN':
    			$number = 1.8517;
    		break;
    		case 'AUD':
    			$number = 4.9079;
    		break;
    		case 'NZD':
    			$number = 4.6397;
    		break;
    		case 'MYR':
    			$number = 1.7757;
    		break;
    		case 'SEK':
    			$number = 0.7721;
    		break;
    		case 'CHF':
    			$number = 7.9832;
    		break;
    		case 'PHP':
    			$number = 0.1524;
    		break;
    		case 'HUF':
    			$number = 0.02391;
    		break;
    		case 'HRK':
    			$number = 1.1058;
    		break;
    		case 'CLP':
    			$number = 0.009107;
    		break;
    		case 'THB':
    			$number = 0.2380;
    		break;
    		case 'CZK':
    			$number = 0.3094;
    		break;
    		case 'RSD':
    			$number = 0.07150;
    		break;
    		case 'MXN':
    			$number = 0.3229;
    		break;
    		case 'BGN':
    			$number = 4.3073;
    		break;
    		case 'INR':
    			$number = 0.1014;
    		break;
    	}
    	
    	return $number;
    }
}