<?php

namespace Admin\Controller;
use Think\Controller;

/**
 * 聚合渠道结算接口对接
 * @author cz
 */
class AggregateFinanceSetController extends Controller {
	public $apihost;
	public $token = "LYHTQDJS";

	public function _initialize(){
		$apihost = M("Kv")->field("value")->where("`key` = 'aggregate_finance_api'")->find();
		
		if(empty($apihost)){
			echo "请先设置请求接口aggregate_finance_api的值".PHP_EOL;die;
		}
		$this->apihost = $apihost['value'];
	}
	public function setFreeDateCount($begin,$end='')
	{
		if($end == '') $end = $begin;
		//判断日期格式
		$patten = "/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01])$/";
		if (!preg_match($patten, $begin)) {
			die("开始时间格式错误");
		}
		if (!preg_match($patten, $end)) {
			die("结束时间格式错误");
		}
		if(strtotime($end) < strtotime($begin)){
			die("结束时间不能比开始时间小");
		}
		if(strtotime($end)+86399-24*3600 > time()){
			die("结束时间不能大于当前");
		}

		$starttime = $begin?strtotime($begin):mktime(0,0,0,date('m'),date('d'),date('Y'));
		$endtime = $end?strtotime($end)+86399:$starttime+86399;
		$datelist = get_date_list($starttime,$endtime,1);
		$countdate = count($datelist);
		for($i=0;$i<$countdate;$i++){
			$this->setDailyCount($datelist[$i]);
		}		
	}
	public function setDailyCount($stime="now")
    {
		if(!IS_CLI){
			die("只支持脚本访问");
		}
		if($stime=="now"){
			$stime=time();
		}else{
			$stime = strtotime($stime);
		}
		$nowdate = date("Y-m-d",$stime);
		$w = (int)date("w",$stime);
		$d = (int)date("d",$stime);

		if($w == 1 || $d == 1){
			if($w == 1){
				echo $nowdate.":".PHP_EOL;
				echo "--周结begin".PHP_EOL;
				$this->setWeekCount($stime);
			}
			if($d == 1){
				echo $nowdate.":".PHP_EOL;
				echo "--月结&补点begin".PHP_EOL;
				$this->setMonthCount($stime);
			}
		}else{
			echo $nowdate."非周一和月初,无需任何处理".PHP_EOL;
		}
	}
	protected function setWeekCount($stime)//进行周结
	{
		$begintime = mktime(0,0,0,date('m',$stime),date('d',$stime)-7,date('Y',$stime));
		$endtime = mktime(0,0,0,date('m',$stime),date('d',$stime),date('Y',$stime))-1;
		$this->getAndSaveData(0,$begintime,$endtime);
	}
	protected function setMonthCount($stime)//进行周结
	{
		$thismonth = date('m',$stime);
		$thisyear = date('Y',$stime);
		if ($thismonth == 1) {
			$lastmonth = 12;
			$lastyear = $thisyear - 1;
		} else {
			$lastmonth = $thismonth - 1;
			$lastyear = $thisyear;
		}
		$lastStartDay = $lastyear . '-' . $lastmonth . '-1';
		$lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));
		$begintime = strtotime($lastStartDay);//上个月的月初时间戳
		$endtime = strtotime($lastEndDay)+24*3600-1;//上个月的月末时间戳
		//普通月结
		$this->getAndSaveData(1,$begintime,$endtime);
		//补点
		$this->getAndSaveData(2,$begintime,$endtime);

	}
    protected function getAndSaveData($type,$begintime,$endtime)
    {
        $sign = md5($begintime.$endtime.$type.$this->token);
        $arr = [
            "begintime"=>$begintime,
            "endtime"=>$endtime,
            "type"=>$type,
            "sign"=>$sign
        ];
        $dataurl .= $this->apihost."&".http_build_query($arr);
        $html = file_get_contents($dataurl);
//		echo $dataurl;die();
        sleep(5);
        $rsp = json_decode($html,true);
        if($rsp['code'] != 1){
            echo $rsp['error'].PHP_EOL;die;
        }
        //成功插入
        $Aggregate = M("aggregate_statement","tab_");
        $begintimestr = date("Y-m-d",$begintime);
        $endtimestr = date("Y-m-d",$endtime);
        if($rsp['count'] > 0){
            //插入数据
            foreach ($rsp['data'] as $k => $v) {
                foreach ($v["game_list"] as $ke => &$va) {
                    $va['begintime'] = $begintimestr;
                    $va['endtime'] = $endtimestr;
                    $va['fax_ratio'] = 0;
                }
                $v["statement_info"] = json_encode($v["game_list"],JSON_UNESCAPED_UNICODE);
                unset($v["game_list"]);
                $v['begintime'] = $begintime;
                $v['endtime'] = $endtime;
                $v['create_time'] = time();
                $v['admin_name'] = "system";
                $v['admin_id'] = 0;
                $v['second_party_info'] =
                    json_encode([
                        "partner"=>$v['channel_name'],
                        "invoice_type"=>$v['invoice_type'],
                        "invoice_item"=>$v['invoice_item'],
                        "company_tax_no"=>$v['tax_identification_number'],
                        "link_man"=>$v['connection_person'],
                        "link_phone"=>$v['phone'],
                        "address"=>$v['send_address'],
                        "register_address"=>$v['register_address'],
                        "register_phone"=>$v['register_phone'],
                        "payee_name"=>$v['bank_user'],
                        "bank_account"=>$v['bank_card'],
                        "opening_bank"=>$v['bank_name'],
                    ],JSON_UNESCAPED_UNICODE);
                $relationData = $this->setAggregateStatement($v['channel_id']);

                if ($relationData) {
                    $v['first_party_info'] = json_encode($relationData['first_company_info']);
                    $v['second_party_info'] = json_encode($relationData['second_company_info']);

                    $statementInfo = json_decode($v['statement_info'],true);
                    if ($relationData['tax_ratio']) {
                        $v['ratio_money'] = 0;

                        foreach ($statementInfo as $key => $value) {

                            $statementInfo[$key]['ratio_money'] = round($value['ratio_money'] * ((100-$relationData['tax_ratio'])/100),2);
                            $statementInfo[$key]['fax_ratio'] = $relationData['tax_ratio'];
                            $v['ratio_money'] += $statementInfo[$key]['ratio_money'];
                        }
                    }
                    $v['statement_info'] = json_encode($statementInfo);
                    $pay_type = 0;
                    if ($relationData['pay_type']==1) {
                        $pay_type = 1;
                    } elseif($relationData['pay_type']==2) {
                        $pay_type = 0;
                    }

                    $v['pay_type'] = $pay_type;
                    $v['verify_status'] = 0;
                }
                $Aggregate->add($v);
            }
        }

        if($type == 0){
            echo "----周结统计ok".PHP_EOL;
        }elseif($type == 1){
            echo "----月结统计ok".PHP_EOL;
        }elseif($type == 2){
            echo "----补点统计ok".PHP_EOL;
        }
    }

    /**
     * 自动开票
     */
    public function setAggregateStatement($channel_id = 0) {

        $where = "(first_company_type = 3 and first_company_id={$channel_id}) OR (second_company_type = 3 and second_company_id={$channel_id})";

        $relationData = M("company_relation","tab_")
            ->where($where)
            ->find();

        if ($relationData) {

            $first_company_info = json_decode($relationData['first_company_info'],true);
            $second_company_info = json_decode($relationData['second_company_info'],true);
            $tax_ratio = $first_company_info['tax_ratio']?$first_company_info['tax_ratio']:$second_company_info['tax_ratio'];
            $pay_type = $relationData['collection'];

            return ['first_company_info'=>$first_company_info,'second_company_info'=>$second_company_info,'tax_ratio'=>$tax_ratio,'pay_type'=>$pay_type];
        } else {
            return false;
        }

    }

	/**
	 * 重算聚合接口数据
	 * @param [type] $id
	 * @return void
	 */
    public function updateAggregateFinanceData($id)
    {
        //获取基础信息
        $Aggregate = M("aggregate_statement","tab_");
        $info = $Aggregate->where("id='{$id}'")->find();
        $sign = md5($info['begintime'].$info['endtime'].$info['withdraw_type'].$this->token);
        $arr = [
            "begintime"=>$info['begintime'],
            "endtime"=>$info['endtime'],
            "type"=>$info['withdraw_type'],
            "sign"=>$sign,
            "channel_id"=>$info['channel_id']
        ];
        $dataurl .= $this->apihost."&".http_build_query($arr);
        $html = file_get_contents($dataurl);
        $rsp = json_decode($html,true);
        if($rsp['code'] != 1){
            echo $rsp['error'].PHP_EOL;die;
        }
        //更新信息
        $begintimestr = date("Y-m-d",$info['begintime']);
        $endtimestr = date("Y-m-d",$info['endtime']);

        if($rsp['count'] > 0){
            //插入数据
            foreach ($rsp['data'] as $k => $v) {
                foreach ($v["game_list"] as $ke => &$va) {
                    $va['begintime'] = $begintimestr;
                    $va['endtime'] = $endtimestr;
                    $va['fax_ratio'] = 0;
                }
                $v["statement_info"] = json_encode($v["game_list"],JSON_UNESCAPED_UNICODE);
                unset($v["game_list"]);
                $v['create_time'] = time();
                $v['admin_name'] = $_SESSION['onethink_admin']['user_auth']['username'];
                $v['admin_id'] = $_SESSION['onethink_admin']['user_auth']['uid'];
                $v['verify_status'] = 0;

//				$first_party_info = json_decode($info['first_party_info'], 1);
//				if($first_party_info['partner'] == $info['channel_name']){

                $v['second_party_info'] =
                    json_encode([
                        "partner"=>$v['channel_name'],
                        "invoice_type"=>$v['invoice_type'],
                        "invoice_item"=>$v['invoice_item'],
                        "company_tax_no"=>$v['tax_identification_number'],
                        "link_man"=>$v['connection_person'],
                        "link_phone"=>$v['phone'],
                        "address"=>$v['send_address'],
                        "register_address"=>$v['register_address'],
                        "register_phone"=>$v['register_phone'],
                        "payee_name"=>$v['bank_user'],
                        "bank_account"=>$v['bank_card'],
                        "opening_bank"=>$v['bank_name'],
                    ],JSON_UNESCAPED_UNICODE);

                $v['first_party_info'] = '';

                $v['pay_type'] =0;
                $relationData = $this->setAggregateStatement($v['channel_id']);

                if ($relationData) {
                    $v['first_party_info'] = json_encode($relationData['first_company_info']);
                    $v['second_party_info'] = json_encode($relationData['second_company_info']);

                    $statementInfo = json_decode($v['statement_info'],true);
                    if ($relationData['tax_ratio']) {
                        $v['ratio_money'] = 0;

                        foreach ($statementInfo as $key => $value) {

                            $statementInfo[$key]['ratio_money'] = round($value['ratio_money'] * ((100-$relationData['tax_ratio'])/100),2);
                            $statementInfo[$key]['fax_ratio'] = $relationData['tax_ratio'];
                            $v['ratio_money'] += $statementInfo[$key]['ratio_money'];
                        }
                    }
                    $v['statement_info'] = json_encode($statementInfo);

                    $pay_type = 0;
                    if ($relationData['pay_type']==1) {
                        $pay_type = 1;
                    } elseif($relationData['pay_type']==2) {
                        $pay_type = 0;
                    }

                    $v['pay_type'] = $pay_type;

                    $v['verify_status'] = 0;
                }
//				} else {
//                    $v['second_party_info'] =
//                        json_encode([
//                            "partner"=>$v['channel_name'],
//                            "invoice_type"=>$v['invoice_type'],
//                            "invoice_item"=>$v['invoice_item'],
//                            "company_tax_no"=>$v['tax_identification_number'],
//                            "link_man"=>$v['connection_person'],
//                            "link_phone"=>$v['phone'],
//                            "address"=>$v['send_address'],
//                            "register_address"=>$v['register_address'],
//                            "register_phone"=>$v['register_phone'],
//                            "payee_name"=>$v['bank_user'],
//                            "bank_account"=>$v['bank_card'],
//                            "opening_bank"=>$v['bank_name'],
//                        ],JSON_UNESCAPED_UNICODE);
//
//                    $v['pay_type'] =1;
//                }


                $res =  $Aggregate->where("id='{$id}'")->save($v);
                if(empty($res)){
                    return false;
                }
            }
        }else{
            $savedata = [
                "create_time"=>time(),
                "admin_name"=>$_SESSION['onethink_admin']['user_auth']['username'],
                "admin_id"=>$_SESSION['onethink_admin']['user_auth']['uid'],
                "verify_status"=>0,
                "statement_info"=>json_encode([],JSON_UNESCAPED_UNICODE),
                "ratio_money"=>0,
                "pay_money"=>0
            ];

            $first_party_info = json_decode($info['first_party_info'], 1);
            if($first_party_info['partner'] == $info['channel_name']){
                $savedata['second_party_info'] = $info['first_party_info'];
                $savedata['first_party_info'] = $info['second_party_info'];

                $savedata['pay_type'] =0;
            }

            $res =  $Aggregate->where("id='{$id}'")->save($savedata);
            if(empty($res)){
                return false;
            }
        }
        return true;
    }
}