<?php
namespace Admin\Controller;
/**
 * cp/公会对账单
 * @author yyh
 */
class StatementController extends ThinkController
{
   //创建
   public function createCpStatement()
   {
       $this->display();
   }
   public function editCpStatement(){
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];
        $dbres = M("statement","tab_")->where("id = '{$id}'")->find();
        $first_party_info = json_decode($dbres['first_party_info'],true);
        $second_party_info = json_decode($dbres['second_party_info'],true);
        $statement_info = json_decode($dbres['statement_info'],true);
        if($dbres['company_name'] == $first_party_info['partner']){
            $first_partner_type=0;
        }else{
            $first_partner_type=1;
        }
        // $fine = array_pop($statement_info);
        $senddata = array(
            "first_partner_type"=>$first_partner_type,
            "first_part_company"=>$first_party_info['partner'],
            "second_part_company"=>$second_party_info['partner'],
            "statement_type"=>$_REQUEST['pay_type'] == 0 ? 1 :0,
            "first_party_info"=>$first_party_info,
            "second_party_info"=>$second_party_info,
            "statement_info"=>$statement_info,
            "statement_count"=>array("sum_money"=>$dbres['statement_money'],"pay_amount"=>$dbres['pay_amount']),
            "fine"=>0,
            "statement_begin_time"=>date("Y-m-d",$dbres['statement_begin_time']),
            "statement_end_time"=>date("Y-m-d",$dbres['statement_end_time'])
        );
        $this->assign("data",$senddata);
        if($_REQUEST['pay_type'] == 0){
            $this->assign("company",$second_party_info['partner']);
        }else{
            $this->assign("company",$first_party_info['partner']);
        }
        $this->assign("company_id",$dbres['company_id']);
        $this->assign("company_name",$dbres['company_name']);
        $this->assign("statement_begin_time",date("Y-m-d",$dbres['statement_begin_time']));
        $this->assign("statement_end_time",date("Y-m-d",$dbres['statement_end_time']));
        $this->assign("id",$dbres['id']);
        $this->display();
        
   }
   public function delCpStatement()
   {
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];

       $statementData = M('statement','tab_')->where(['id'=>$id])->find();

        $res = M("statement","tab_")->where("id = '{$id}'")->delete();
        if($res !== false){

            addOperationLog(['op_type'=>2,'key'=>$statementData['company_name'].'/'.date('YmdHis',$statementData['statement_begin_time']).'/'.date('YmdHis',$statementData['statement_end_time']),'op_name'=>'删除上游对账单','url'=>U('StatementMangement/lists'),'menu'=>'推广员-结算管理-结算单管理-删除上游对账单']);

            $this->ajaxReturn(array("success"=>"ok","code"=>0));
        }else{
            $this->ajaxReturn(array("error"=>"database error","code"=>2000));
        }
   }
   public function getCompanyList()
   {
       $data = array();
       $data['ptCompany']= M("CompanyInfo","tab_")->field('id,partner')->select();
       $data['cpCompany']= getPartner();
       $this->ajaxReturn(array("success"=>$data,"code"=>2000));
   }
   //获取推广公司基础信息
   public function getCpCompanyInfo()
   {
       $CompanyId = $_REQUEST['company_id'];
       $company_type = $_REQUEST['company_type'];
       if($company_type == 'pt'){
         $info = M("CompanyInfo","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank")->where("id = '{$CompanyId}'")->find();
       }else{
          $info = M("partner","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank")->where("id = '{$CompanyId}'")->find();
       }
       if(empty($info)){
         $this->ajaxReturn(array("error"=>"no find","code"=>2000));
       }else{
         $this->ajaxReturn(array("success"=>$info,"code"=>0));
       }

   }
   //按时间-公司id-获取订单及分成比例
   public function getSpendStatement()
   {
        $map["pay_status"] = 1;

        $CompanyId = $_REQUEST['company_id']; //对账公司id
        $statement_type = $_REQUEST['statement_type'];//付款方
        $first_partner_type = $_REQUEST['first_partner_type'];//甲方类型:0cp,1pt
        
        $is_month = false;//是否是月结判断,非月结无需梯度计算
        if (isset($_REQUEST['time_start']) && isset($_REQUEST['time_end'])) {
            //判断是否是月结
            $tm = explode('-',$_REQUEST['time_start']);
            $en  = mktime(0,0,0,$tm[1]-0+1,1,$tm[0])-1; //当月最后一天时间戳
            $en2 = strtotime($_REQUEST['time_end']) + 86399; //上传的订单时间
            if($tm[2] == 1 && $en == $en2){
                $is_month = true;
            }
            $map['pay_time'] = ['between', [strtotime($_REQUEST['time_start']), strtotime($_REQUEST['time_end']) + 86399]];
        }
        //判断是否有重叠时间
        $Statement = M("statement","tab_");
        $repart =false;
        $errorstr = '';
        $errorstr1 = '';
        $errorstr2 = '';
        //开始时间被重叠部分
        $checkmap = array(
            "statement_begin_time"=>array("ELT",strtotime($_REQUEST['time_start'])),
            "statement_end_time"=>array("EGT",strtotime($_REQUEST['time_start'])),
            "company_id"=>$CompanyId
        );
        $bres = $Statement->field("id,statement_begin_time,statement_end_time")->where($checkmap)->find();
        if($bres){
            $repart=true;
            $begin =  $_REQUEST['time_start'];
            //统计相交时间
            if(strtotime($_REQUEST['time_end']) > $bres["statement_end_time"]){
                $end = date("Y-m-d",$bres["statement_end_time"]);
            }else{
                $end = $_REQUEST['time_end'];
            }
            $errorstr = ($begin."到".$end."期间的数据已经结算过<br/>");
        }
        //结束被重复的部分
        $checkmap = array(
            "statement_begin_time"=>array("ELT",strtotime($_REQUEST['time_end'])),
            "statement_end_time"=>array("EGT",strtotime($_REQUEST['time_end'])),
            "company_id"=>$CompanyId
        );
        
        $bres = $Statement->field("statement_begin_time,statement_end_time")->where($checkmap)->find();
        if($bres){
            $repart=true;
            $begin = date("Y-m-d",$bres["statement_begin_time"]);
            //统计相交时间
            $end = $_REQUEST['time_end'];
            $errorstr1 = ($begin."到".$end."期间的数据已经结算过<br/>");
        }
        //中间被包住
        $checkmap = array(
            "statement_begin_time"=>array("EGT",strtotime($_REQUEST['time_start'])),
            "statement_end_time"=>array("ELT",strtotime($_REQUEST['time_end'])),
            "company_id"=>$CompanyId
        );
        $bres = $Statement->field("statement_begin_time,statement_end_time")->where($checkmap)->find();
        if($bres){
            $repart=true;
            $begin = date("Y-m-d",$bres["statement_begin_time"]);
            //统计相交时间
            $end = date("Y-m-d",$bres["statement_end_time"]);
            $errorstr2 = ($begin."到".$end."期间的数据已经结算过<br/>");
        }

        if($repart){
            if($errorstr1 == $errorstr){
                $errorstr1 ='';
            }
            if($errorstr1 == $errorstr2){
                $errorstr1 ='';
            }
            if($errorstr == $errorstr2){
                $errorstr2 ='';
            }
            $errorstr .=($errorstr1.$errorstr2);
            $this->ajaxReturn(array("error"=>$errorstr,"code"=>2001));
        }

        //获取对应cp公司的游戏
        $game_list = M("game","tab_")->field("id")->where("partner_id = '{$CompanyId}'")->select();
        if($game_list){
            $map['game_id'] = ['in', implode(',', array_column($game_list,'id'))];
        }
        //获取统计
        $list =  M("Spend","tab_")->field('sum(pay_amount) pay_amount,game_id,game_name')->where($map)->group('game_id')->select();
        $CpGameRatio =   M("CpGameRatio","tab_");
        $countarr = array(
            "pay_amount"=>0,
            "sum_money"=>0
        );
        foreach($list as $k=>&$v){
            $map = array(
                "game_id"=>$v['game_id'],
                "begin_total_amount"=>0,
            );
            // if($is_month){
            //     $map['begin_total_amount'] = array("ELT",$v['pay_amount']);
            // };
            // $ratiores =  $CpGameRatio->where($map)->order("begin_total_amount desc")->limit(1)->select();
            // if(empty($ratiores)){
            //     $redio = 0;
            // }else{
            //     $redio = $ratiores[0]['ratio'];
            // }
            $redio = getGameCpRadio($v['game_id'],$v['pay_amount'],$is_month);//获取分成比例
            if($first_partner_type==0){
                //甲方cp
                $v['first_ratio'] = round($redio,2);
                $v['second_ratio'] = round((100-$redio),2);
            }else{
                $v['second_ratio'] = round($redio,2);
                $v['first_ratio'] = round((100-$redio),2);
            }
            if($statement_type == 0){
                $v['sum_money'] = round($v['pay_amount']*$v['first_ratio']/100,2);
            }else{
                $v['sum_money'] = round($v['pay_amount']*$v['second_ratio']/100,2);
            }
            
            $countarr['pay_amount'] += $v['pay_amount'];
            $countarr['sum_money'] += $v['sum_money'];
            $v['fax_ratio'] = 0;
            $v['promote_ratio'] = 0;
            $v['statement_begin_time']=$_REQUEST['time_start'];
            $v['statement_end_time']=$_REQUEST['time_end'];
            $v['statement_type']=0;
        }
        //获取奖罚
        $rrmap = array(
            "reward_time" => ['between', [strtotime($_REQUEST['time_start']), strtotime($_REQUEST['time_end']) + 86399]],
            "company_type"=>1,
            "company_id"=>$CompanyId
        );
        $rfres = M("RewardRecord","tab_")
                ->field("
                    IFNULL(SUM(CASE WHEN reward_type = 1 THEN money ELSE 0 END),0) as reward_count,
                    IFNULL(SUM(CASE WHEN reward_type = 2 THEN money ELSE 0 END),0) as fine_count
                    ")
                ->where($rrmap)->find();
        if($statement_type == 0 ){
            //乙->甲 甲方cp
            if($first_partner_type==0){
                $reward_count = $rfres['reward_count']-0;
                $fine_count = 0-$rfres['fine_count'];
            }else{
                $reward_count = 0-$rfres['reward_count'];
                $fine_count = $rfres['fine_count']-0;
            }
        }else{
            if($first_partner_type==0){
                $reward_count = 0-$rfres['reward_count']-0;
                $fine_count = $rfres['fine_count']-0;
            }else{
                $reward_count = $rfres['reward_count']-0;
                $fine_count = 0-$rfres['fine_count'];
            }
        }
        
        if($rfres['reward_count'] > 0){
            $list[] = array(
                "statement_begin_time"=>$_REQUEST['time_start'],
                "statement_end_time"=>$_REQUEST['time_end'],
                'statement_type'=>2,
                "game_name"=>"奖励",
                'pay_amount'=>$reward_count,
                'sum_money'=>$reward_count,
            );
            $countarr['pay_amount'] +=$reward_count;
            $countarr['sum_money']+=$reward_count;
        }
        if($rfres['fine_count'] > 0){
            $list[] = array(
                "statement_begin_time"=>$_REQUEST['time_start'],
                "statement_end_time"=>$_REQUEST['time_end'],
                'statement_type'=>1,
                "game_name"=>"罚款",
                'pay_amount'=>$fine_count,
                'sum_money'=>$fine_count,
            );
            $countarr['pay_amount'] += $fine_count;
            $countarr['sum_money'] += $fine_count;
        }
        
        $countarr['pay_amount'] = round($countarr['pay_amount'],2);
        $countarr['sum_money'] = round($countarr['sum_money'],2);

        $this->ajaxReturn(array("success"=>$list,"count"=>$countarr,"code"=>0));

   }
   //添加数据
   public function doAddCpStatement($id = 0){
       $first_partner_type = $_REQUEST['first_partner_type'];
       if($first_partner_type == 0){
            //甲方cp
           $company =  $_REQUEST['first_party_info'];
       }else{
           $company =$_REQUEST['second_party_info'];
       }
        $second_party_info = $_REQUEST['second_party_info'];
        $statement_info = $_REQUEST['statement_info'];
        // $statement_info[] = array(
        //     "sum_money"=>$_REQUEST['fine'],
        //     "type_name"=>"罚款",
        //     "statement_type"=>1
        // );
       //拼凑数据
       $adddata = array(
            "statement_type"=>0,
            "company_id"=>$company['id'],
            "company_name"=>$company['partner'],
            "link_phone"=>$company['link_phone'],
            "statement_begin_time"=>strtotime($_REQUEST['statement_begin_time']),
            "statement_end_time"=>strtotime($_REQUEST['statement_end_time']),
            'create_time'=>time(),
            "statement_money"=>$_REQUEST['statement_count']['sum_money'],
            "pay_amount"=>$_REQUEST['statement_count']['pay_amount'],
            "is_confirm"=>0,
            "pay_type"=>$_REQUEST['statement_type'] == 0 ? 1 :0,
            "first_party_info"=>json_encode($_REQUEST['first_party_info'],JSON_UNESCAPED_UNICODE),
            "second_party_info"=>json_encode($_REQUEST['second_party_info'],JSON_UNESCAPED_UNICODE),
            "statement_info"=>json_encode($statement_info,JSON_UNESCAPED_UNICODE)
        );
        if($id == 0){
//            var_dump(1);die();
            addOperationLog(['op_type'=>0,'key'=>$company['partner'].'/'.getNowDate(),'op_name'=>'新增上游对账单','url'=>U('StatementMangement/lists'),'menu'=>'推广员-结算管理-结算单管理-新增上游对账单']);

            $res = M("statement","tab_")->add($adddata);
        }else{

            addOperationLog(['op_type'=>1,'key'=>$company['partner'].'/'.getNowDate(),'op_name'=>'编辑上游对账单','url'=>U('StatementMangement/lists'),'menu'=>'推广员-结算管理-结算单管理-编辑上游对账单']);

            $res = M("statement","tab_")->where("id = '{$id}'")->save($adddata);
        }
        if($res !== false){
            $this->ajaxReturn(array("success"=>"ok","code"=>0));
        }else{
            $this->ajaxReturn(array("error"=>"database error","code"=>2000));
        }
   }

}