<?php
/**
 * 平台对账
 */
defined( 'IN_WEB') or die( 'Include Error!');

include_once dirname(__FILE__) . "/Base.php";


class Reconciliation extends  Base{
	public function __construct()
	{
        $this->_payBlackList['uid'] = oo::commonOprModel("config")->payWhiteList();
	}
	
	/**
     * 某个月份的订单
     * @return string
     * Created by: hss
     * Created on: 2020/4/16 14:59
     */
    public function month($param){
    	$time = oo::functions()->escape($param['time']);
    	$times = $this->getthemonth($time);
    	$stime = strtotime($times[0]);
        $etime = strtotime(date('Y-m-d 23:59:59', strtotime($times[1])));
        
        $blackUidArr = $this->_payBlackList['uid'];
        $blackUidSql = '';
        if(!empty($blackUidArr)) {
            $blackUidStr = implode(',', $blackUidArr);
            $blackUidSql = " AND uid NOT IN ({$blackUidStr}) ";
        }
        $where = $blackUidSql;
        $out = [];//订单数据
		for($i = 1; $i <= 100; $i++){
			$table = otable::payment($i);
	        $sql = " SELECT * FROM {$table} WHERE platform_serial_num != '' AND status = 2 AND order_time >= {$stime} AND order_time <= {$etime}  {$where}";
	        $ret = oo::commonOprDb('common')->getAll($sql, 1);
	        $out = array_merge($out,$ret);
		}
        
        //商品数据
        $gTable = otable::goodsCrazy();
        $sql = " SELECT gid,gpid,gname FROM {$gTable}";
	    $goodsCrazy = oo::commonOprDb('common')->getAll($sql, 1);
	    
	    //Google账单数据
	    $tb = otable::reconciliation();
        $sql = " SELECT * FROM {$tb} WHERE Month = '{$time}'";
	    $reconciliation = oo::commonOprDb('common')->getAll($sql, 1);
        
        return json_encode(array('list'=>$out,'goods'=>$goodsCrazy,'reconciliation'=>$reconciliation));
    }
    
    //获取某个月的第一天已经最后一天
    function getthemonth($date){
	   $firstday = date('Y-m-01', strtotime($date));
	   $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
	   return array($firstday, $lastday);
	}
	
	/**
     * 导入Google账单
     * @return string
     * Created by: hss
     * Created on: 2020/4/16 14:59
     */
    public function import($param){
    	$data = json_decode($param['data'],true);
    	
    	if(!empty($data)) {
            $tableSid = otable::reconciliation();
            $sidStr = '';
            
            if(isset($data[0]['month'])){
            	$month = $data[0]['month'];
	            //删除原先月份数据
	            $sql = "DELETE FROM {$tableSid} WHERE Month = '{$month}'";
	            $ret = oo::commonOprDb('common')->query($sql);
            }
            $AmountMerchant = 0;
            $ordernum = 0;
            foreach ($data as $k => $v) {
                $sidStr .= '("'.$v['month'].'","'.$v['platform_serial_num'].'","'.$v['type'].'","'.$v['BuyerCurrency'].'","'.$v['Rate'].'","'.$v['AmountBuyer'].'","'.$v['MerchantCurrency'].'","'.$v['AmountMerchant'].'","'.$v['fee'].'","'.$v['DateTime'].'"),';
                
                //type = 1 税费
                if($v['type'] != 1){
                	$ordernum++;
                	$AmountMerchant += $v['AmountMerchant'];
                }
            }
            $sidStr = rtrim($sidStr, ',');
            $sqlSid = " INSERT INTO {$tableSid} (Month, PlatformSerialNum, Type, BuyerCurrency, Rate, AmountBuyer, MerchantCurrency, AmountMerchant, Fee, DateTime) VALUES $sidStr";
            $ret = oo::commonOprDb('common')->query($sqlSid);
            
            $this->earnmoney($month,$AmountMerchant,$ordernum);
            
			return $ret;
        }
        return 1;
    }
    
    /**
     * 导入时生成平台对账
     * @return string
     * Created by: hss
     * Created on: 2020/4/16 14:59
     */
    public function earnmoney($time,$money = 0,$ordernum = 0){
    	$channel = 1;//支付渠道
        //$money = 0;//第三方总金额
        //$ordernum = 0;//第三方订单数
        $currency = 2;//第三方货币单位
        $other_income = 0;//第三方实际财务收入
        $exchange_rate = 7.7919;//汇率
        $other_fee = 0.3;//第三方费率
        
        $time = strtotime($time);
        $table = otable::earnmoney();
        //先查询是否有填写相关数据
        $sql = " SELECT * FROM {$table} WHERE local_channel = {$channel} AND check_time = {$time} ";
        $info = oo::commonOprDb('common')->getOne($sql, 1);
        if (!empty($info)) {//已经存在了
        	//删除原先数据
            $sql = "DELETE FROM {$table} WHERE local_channel = {$channel} AND check_time = {$time}";
	        $ret = oo::commonOprDb('common')->query($sql);
        }

        //查询本地数据入库
        $monthStart = mktime(0,0,0,date('m', $time),1,date('Y', $time));
        $temp = date('Y-m-d', $time);
        $monthEnd = mktime(23,59,59,date('m', $time),date('d', strtotime("$temp +1 month -1 day")),date('Y', $time));
        $sTable = otable::summarylist();
        $gTable = otable::goodsCrazy();
		$blackUidArr = $this->_payBlackList['uid'];
        //$blackUidArr = [1,2,3];
        $blackUidSql = '';
        if(!empty($blackUidArr)) {
        	$blackUidStr = implode(',', $blackUidArr);
        }
        
        $sqlChannl = ' AND gchannel = '.$channel;
        $sql = " SELECT sl_pusd, sl_sid FROM {$sTable} AS st LEFT JOIN {$gTable} AS gt ON st.sl_gid = gt.gid WHERE sl_sid != -1 AND sl_status = 2 AND sl_order_time >= {$monthStart} AND sl_order_time <= {$monthEnd} AND sl_uid NOT IN ({$blackUidStr}) {$sqlChannl} ";
        $sucList = oo::commonOprDb('common')->getAll($sql, 1);
        $local_totalmoney = $local_ordernum = $local_income =  0;
        if (!empty($sucList)) {
            foreach ($sucList as $info) {
                $local_totalmoney += $info['sl_pusd'];
                $local_ordernum++;
                $tmpIncome = $this->channelSettlement($info['sl_sid'], $info['sl_pusd']);
                $local_income += $tmpIncome;
            }
        }
        
        //本地金额乘汇率
        $local_totalmoney = $local_totalmoney;
        $local_income = $local_income;
        
        $local_income = round($local_income, 2);
        //判断商家和本地的金额差距
        $moneygap = 0;
        if ($local_totalmoney != $money) {
            $moneygap = $money - $local_totalmoney * $exchange_rate;
        }

        $sqlInsert = "INSERT INTO {$table} (local_channel, local_totalmoney, local_ordernum, local_currency, other_channel, other_totalmoney, other_ordernum, other_currency, moneygap, check_time, local_income, other_income,exchange_rate,other_fee) VALUES($channel, $local_totalmoney, $local_ordernum, $currency, $channel, $money, $ordernum, $currency, $moneygap, $time, $local_income, $other_income,$exchange_rate,$other_fee)";
        oo::commonOprDb('common')->query($sqlInsert);
    }
    
    //渠道结算
    public function channelSettlement($channel, $money)
    {
        $income = 0;
        switch ($channel) {
            case 1://谷歌 本地*70
            case 3://苹果 本地*70
                $income = $money * 0.7;
                break;
            case 2://短信
                $income = (1 - 0.05) * 0.7 * $money;
                break;
            case 4://Bluecoins 96%
                $income = $money * 0.96;
                break;
            case 5://Truemoney
            case 6://12call
            case 7://dtac 86%
                $income = $money * 0.86;
                break;
            case 8://line 90%
                $income = $money * 0.9;
                break;
            case 9:
            	$income = $money * 0.7;
                break;
            default:
                break;
        }
        return $income;
    }
    
    /**
     * 月度流水统计
     * @return string
     * Created by: hss
     * Created on: 2020/4/17 15:26
     */
    public function payStreamSta($param){
    	$month = oo::functions()->escape($param['month']);
    	$channel = oo::functions()->uint($param['channel']);//支付渠道
    	$channel = empty($channel)?1:$channel;
    	$table = otable::staData();
        $type = 'payStreamSta';
        $sql = "SELECT * FROM {$table} WHERE type = '{$type}' ORDER BY date DESC";
        $data = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
		foreach($data as $k => $v){
            $data[$k]['data'] = json_decode($v['data'],true);
            if($data[$k]['data']['channel'] != $channel){
            	unset($data[$k]);
            }
        }
        
        return json_encode($data);
    }
    
    /**
     * 生成月度流水统计
     * @return string
     * Created by: hss
     * Created on: 2020/4/17 14:59
     */
    public function savePayStream($param){
    	$month = oo::functions()->escape($param['month']);
    	$channel = oo::functions()->uint($param['channel']);//支付渠道
    	$exchange_rate = oo::functions()->escape($param['exchange_rate']);//汇率
    	$other_totalmoney = oo::functions()->escape($param['other_totalmoney']);//第三方汇总金额(港币)
    	$other_ordernum = oo::functions()->uint($param['other_ordernum']);//第三方汇总订单数
    	if(empty($month)){
    		return 0;
    	}
    	if(empty($channel)){
    		$channel = 1;
    	}
    	$time = strtotime($month);
        $table = otable::staData();
        //先查询是否有填写相关数据
        $month = date("Ymd",strtotime($month));
        $sql = " SELECT * FROM {$table} WHERE type = 'payStreamSta' AND date = {$month} ";
        $info = oo::commonOprDb('statistics')->getOne($sql, 1);
        if (!empty($info)) {//已经存在了
        	//删除原先数据
            $sql = "DELETE FROM {$table} WHERE type = 'payStreamSta' AND date = {$month}";
	        $ret = oo::commonOprDb('statistics')->query($sql);
        }

        //查询本地数据入库
        $monthStart = mktime(0,0,0,date('m', $time),1,date('Y', $time));
        $temp = date('Y-m-d', $time);
        $monthEnd = mktime(23,59,59,date('m', $time),date('d', strtotime("$temp +1 month -1 day")),date('Y', $time));
        $sTable = otable::summarylist();
        $gTable = otable::goodsCrazy();
		$blackUidArr = $this->_payBlackList['uid'];
        //$blackUidArr = [1,2,3];
        $blackUidSql = '';
        if(!empty($blackUidArr)) {
        	$blackUidStr = implode(',', $blackUidArr);
        }
        
        $sqlChannl = ' AND gchannel = '.$channel;
        $sql = " SELECT sl_pusd, sl_sid FROM {$sTable} AS st LEFT JOIN {$gTable} AS gt ON st.sl_gid = gt.gid WHERE sl_sid != -1 AND sl_status = 2 AND sl_order_time >= {$monthStart} AND sl_order_time <= {$monthEnd} AND sl_uid NOT IN ({$blackUidStr}) {$sqlChannl} ";
        $sucList = oo::commonOprDb('common')->getAll($sql, 1);
        $local_totalmoney = $local_ordernum = 0;
        if (!empty($sucList)) {
            foreach ($sucList as $info) {
                $local_totalmoney += $info['sl_pusd'];
                $local_ordernum++;
            }
        }
        
        $data = array(
        	'channel'=>$channel,
        	'add_time'=>time(),//统计时间
        	'local_ordernum'=>$local_ordernum,//本地订单数
        	'local_totalmoney'=>$local_totalmoney,//本地金额
        	'other_totalmoney'=>$other_totalmoney,//第三方汇总金额(港币)
        	'other_ordernum'=>$other_ordernum,//第三方汇总订单数
        	'exchange_rate'=>$exchange_rate,//汇率
        	'status'=>0,//是否确认
        );
        
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        $tb = otable::staData();
    	$type = 'payStreamSta';
        $sql = "INSERT INTO {$tb} VALUES('{$month}', '{$type}' ,'{$data}')";
        $ret = oo::commonOprDb('statistics')->query($sql);
        
        $time = strtotime($month);
        $table = otable::earnmoney();
        //先查询是否有填写相关数据
        $sql = " SELECT * FROM {$table} WHERE local_channel = {$channel} AND check_time = {$time} ";
        $info = oo::commonOprDb('common')->getOne($sql, 1);
        if (!empty($info)) {//已经存在了
        	//删除原先数据
            $sql = "DELETE FROM {$table} WHERE local_channel = {$channel} AND check_time = {$time}";
	        $ret = oo::commonOprDb('common')->query($sql);
        }
        
        
        //月度收入统计
        //本地金额乘汇率
        $local_totalmoney = $local_totalmoney;
        $local_income = 0;
        $other_fee = 0.3;
        $other_income = 0;
        $currency = 2;
        $local_income = round($local_income, 2);
        //判断商家和本地的金额差距
        $moneygap = 0;
        if ($local_totalmoney != $other_totalmoney) {
            $moneygap = $other_totalmoney - $local_totalmoney * $exchange_rate;
        }

        $sqlInsert = "INSERT INTO {$table} (local_channel, local_totalmoney, local_ordernum, local_currency, other_channel, other_totalmoney, other_ordernum, other_currency, moneygap, check_time, local_income, other_income,exchange_rate,other_fee) VALUES($channel, $local_totalmoney, $local_ordernum, $currency, $channel, $other_totalmoney, $other_ordernum, $currency, $moneygap, $time, $local_income, $other_income,$exchange_rate, $other_fee)";
        oo::commonOprDb('common')->query($sqlInsert);
        
        return $ret;
    }
    
    /**
     * ajax编辑财务收入
     */
    public function ajaxEditIncome($param){
        $date = oo::functions()->uint($param['date']);
        $field = oo::functions()->escape($param['field']);
        $val = oo::functions()->escape($param['val']);
        $type = 'payStreamSta';
        $table = otable::staData();
        
        $sql = " SELECT * FROM {$table} WHERE type = 'payStreamSta' AND date = '{$date}' ";
        $info = oo::commonOprDb('statistics')->getOne($sql, 1);
        $info['data'] = json_decode($info['data'],true);
        $info['data'][$field] = $val;
        
        $data = $info['data'];
        
        $data = json_encode($data,JSON_NUMERIC_CHECK);
        
        $sql = "UPDATE {$table} SET data = '{$data}' WHERE date = '{$date}' AND type = '{$type}' LIMIT 1";
        $ret = oo::commonOprDb('common')->query($sql);
        return $ret;
    }
}
