<?php

namespace App\Models;
use Illuminate\Support\Facades\Log;
use DB;

/**
 *
 */
class Nagent_countwater extends BaseModel {

    protected $table = 'nagent_countwater';
    public $timestamps = false;

    //获取对应时间区间代理业绩及佣金相关数据
    protected function SettleData($wtime,$gid){
        DB::connection()->enableQueryLog();
        $sql = "SELECT agent_water,zt_water,group_water,sum_water,game_water,count_time FROM nagent_countwater WHERE ";
        if(is_array($wtime)){
            $sql .= "count_time In ('" . $wtime[0] . "','" . $wtime[1] . "')";
        }else{
            $sql .= "count_time='" . $wtime . "'";
        }
        $sql .= " and time_type=2 and agent_identity IN (SELECT agent_identity FROM nagent_detailed WHERE parent_id='" . $gid . "')";
        $snwater = DB::select ($sql);
        $snwater = json_encode ($snwater);
        $snwater = json_decode ($snwater, 1);   //直推会员业绩查询

        $uwater =  $this->select('agent_water','zt_water','group_water','sum_water','game_water','count_time')->where('agent_identity',$gid);
        if(is_array($wtime)){
            $uwater = $uwater->whereIn('count_time',$wtime);
        }else{
            $uwater = $uwater->where('count_time',$wtime);
        }
        $uwater = $uwater->where('time_type',2)->where('status',1)->first();    
        $resdata = array(
            'ae' => 0.00,   //团队业绩
            'sae' => 0.00,  //直推会员业绩
            'gae' => 0.00,  //直属代理业绩
            'saemoney' => 0.00, //直推会员佣金
            'gaemoney' => 0.00, //直属代理佣金
            'aemoney' => 0.00,  //团队佣金
        );
        if(!$uwater || count($uwater->toArray())<1)return $resdata;
        
        $ogames = \App\Models\GameType::getOutWatergame();
        $uwater = $uwater->toArray();
        $uwater = $this->OutGameData($uwater,$uwater['game_water'],$ogames);
        
        $resdata['ae'] = $uwater['sum_water'];
        $resdata['sae'] = $uwater['zt_water'];
        $resdata['gae'] = $uwater['group_water'];

        //获取佣金比例及对应等级、计算代理佣金
        $mgrade = "\App\Models\NagentGrade";
        $grades = $mgrade::getGrades();
        $ratio = empty($grades)?$grades:$mgrade::getGradeBymoney($uwater['sum_water'],$grades);
        if(empty($ratio))return $resdata;
        $resdata['ratio'] = $ratio;
        $resdata['saemoney'] = round($resdata['sae']*($ratio['water_ratio']/100),2);
        $resdata['aemoney'] = $resdata['saemoney'] + $resdata['gaemoney'];
        if(!$snwater || count($snwater)<1)return $resdata;
        
        //直属代理佣金计算
        foreach ($snwater as $k => $v) {
            $kwater = $this->OutGameData($v,$v['game_water'],$ogames,'sum_water');
            $gratio = empty($grades)?$grades:$mgrade::getGradeBymoney($kwater['sum_water'],$grades);
            if(empty($gratio))continue;
            $cratio = $ratio['water_ratio'] - $gratio['water_ratio'];
            $resdata['gaemoney'] += round($kwater['sum_water']*($cratio/100),2);
        }
        $resdata['gaemoney'] = ($resdata['gaemoney']<0)?0:$resdata['gaemoney'];
        $resdata['aemoney'] = $resdata['saemoney'] + $resdata['gaemoney'];
        return $resdata;
    }


    //过滤不计入流水游戏业绩
    private function OutGameData($water,$gwater,$games,$key=''){
        if(!is_array($games) || count($games)<1)return $water;
        $gwater = json_decode($gwater,1);
        foreach ($games as $k => $v) {
            if(empty($key)){
                $water['agent_water'] = isset($gwater[$v['table_name']]['agent_water'])?($water['agent_water']-$gwater[$v['table_name']]['agent_water']):$water['agent_water'];
                $water['zt_water'] = isset($gwater[$v['table_name']]['zt_water'])?($water['zt_water']-$gwater[$v['table_name']]['zt_water']):$water['zt_water'];
                $water['group_water'] = isset($gwater[$v['table_name']]['group_water'])?($water['group_water']-$gwater[$v['table_name']]['group_water']):$water['group_water'];
                $water['sum_water'] = isset($gwater[$v['table_name']]['sum_water'])?($water['sum_water']-$gwater[$v['table_name']]['sum_water']):$water['sum_water'];
            }else{
                $water[$key] = isset($gwater[$v['table_name']][$key])?($water[$key]-$gwater[$v['table_name']][$key]):$water[$key];
            }
        }
        return $water;
    }

    //根据ID更新数据
    protected function updateDataByID($id,$udata){
        $res = $this->where('id',$id)->update($udata);
        if($res<1)return -8505012802;
        return 1;
    }


    //批量更新
    protected function updateBatch($multipleData)
    {
        try{
            $tableName = $this->table; // 表名
            $firstRow = current($multipleData);

            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            // 拼接sql语句
            $sql = "UPDATE " . $tableName . " SET ";
            $ids  = '';
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $sql .= $uColumn . " = CASE ";
                foreach ($multipleData as $data) {
                    $sql .= "WHEN " . $referenceColumn . " = $data[$referenceColumn] THEN '$data[$uColumn]' ";
                    $ids .= $data[$referenceColumn] . ',';
                }
                $sql .= "ELSE " . $uColumn . " END,";
            }
            $sql = trim($sql,',');
            $ids = trim($ids,',');
            $sql .= " WHERE " . $referenceColumn . " IN (" . $ids . ")";

            // 传入预处理sql语句和对应绑定数据
            $res = DB::update($sql);
            return $res;
        } catch (\Exception $e) {
            return -8505013302;
        }
    }

    //更新或添加代理业绩统计数据
    protected function udadData($indata,$udata){
        if(!empty($udata)){
            $updateinfo = array();
            foreach ($udata as $k => $v) {
                foreach ($v as $sk => $sv) {
                    unset($sv['agent_identity']);
                    unset($sv['agent_user']);
                    unset($sv['count_time']);
                    unset($sv['status']);
                    unset($sv['time_type']);
                    unset($sv['sort']);
                    $updateinfo[] = $sv;
                }
            }
            $res = $this->updateBatch($updateinfo);
            if(is_numeric($res) && $res<0)return $res;
        }
        
        if (!empty($indata)) {
            $indata = array_values($indata);
            $res = $this->insert($indata);
            if ($res < 1)return $res;
        }
        return 1;
    }
}

?>