<?php

namespace Bill\Lib;

use Dever;

class Cron
{
    # 校正金额和业绩
    public function jz_api()
    {
        $member = Dever::db('agent/member')->select();
        if ($member) {
            foreach ($member as $v) {
                $where['mid'] = $v['id'];
                $data = Dever::db('bill/cash')->getCash($where);
                if ($data && $data['total']) {
                    Dever::db('agent/member')->update(array('where_id' => $v['id'], 'cash' => $data['total']));
                }
            }
        }
        
    }

    public function sell_api()
    {
    	# 按月份统计团队业绩和直推业绩
        $month = Dever::input('month', date('Y-m'));
        $start_time = $month .'-01 00:00:00';
		$end_time = date('Y-m-d', strtotime($start_time. ' +1 month -1 day')).' 23:59:59';
		// $where['type'] = '2';
        $where['start'] = Dever::maketime($start_time);
        $where['end'] = Dever::maketime($end_time);
        $data = Dever::db('bill/sell')->getNumByTime($where);
        if ($data) {
        	foreach ($data as $k => $v) {

                if ($v['num'] > 0) {
                    $w = array();
                    $w['mid'] = $v['mid'];
                    $w['month'] = $where['start'];
                    $w['clear'] = true;
                    $info = Dever::db('bill/sell_stat')->find($w);
                    
                    $where['mid'] = $v['mid'];
                    $where['type'] = $v['type'];
                    $total = Dever::db('bill/sell')->getNumByTimeOne($where);

                    if ($v['type'] == 1) {
                        $w['new_ztnum'] = $v['num'];
                        if ($total) {
                            $w['zt_num'] = $total['num'];
                        }
                    } else {
                        $w['new_num'] = $v['num'];
                        if ($total) {
                            $w['num'] = $total['num'];
                        }
                    }
                    
                    if ($info) {
                        $w['where_id'] = $info['id'];
                        Dever::db('bill/sell_stat')->update($w);
                    } else {
                        Dever::db('bill/sell_stat')->insert($w);
                    }
                }
        	}
        }

        return 'ok';
    }

    # 权益使用情况统计：类型、商品名、总发放数量、总使用数量
    public function goods_api()
    {
        $num = Dever::input('num', 5);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);

        for($i=0; $i<=$day; $i++) {
            $where['start'] = $start + 86400*$i;
            $where['end'] = $start + 86400*$i + 86399;
            $goods = Dever::db('agent/member_goods')->findAll($where);
            $dh_order = Dever::db('agent/dh_order')->getDhNum(array('status'=>3,'start'=>$where['start'],'end'=>$where['end'],'state'=>1));
            // print_R($dh_order);die;
            if ($goods) {
                foreach ($goods as $k => $v) {
                    $data = array();
                    $data['day'] = $where['start'];
                    $data['type'] = $v['type'];
                    $data['type_id'] = $v['type_id'];
                    $data['sku_id'] = $v['sku_id'];
                    $info = Dever::db('bill/goods_stat')->find($data);

                    $data['total_num'] = $v['total_num'];
                    $data['sell_num'] = $v['sell_num'];
                    $data['cash'] = $v['cash'];
                    $data['y_cash'] = $v['y_cash'];
                    $data['w_cash'] = $v['cash'] - $v['y_cash'];
                    $data['name'] = $v['name'];
                    $data['sell_nonum'] = $dh_order;

                    if ($info) {
                        $data['where_id'] = $info['id'];
                        Dever::db('bill/goods_stat')->update($data);
                    } else {
                        Dever::db('bill/goods_stat')->insert($data);
                    }
                }
            }
        }

        return 'ok';
    }

    # 区域分润
    /*
    区域毛利  =  区域内所有门店的采购商品的零售价总额  x  30%

    城市分润  =  区域毛利 x 1%

    区县分润  =  区域毛利 x 3%

    街道分润  =  区域毛利 x 5%
    */
    public function area_api()
    {
        # 获取所有代理商
        $where['status'] = 2;
        $member = Dever::db('agent/member')->select($where);
        if ($member) {
            foreach ($member as $k => $v) {
                # 获取区域内门店的利润
                $role = Dever::db('setting/role')->find($v['role']);
                $profit = $role['profit'];
                if (!$profit) {
                    continue;
                }
                $temp = explode(',', $v['area']);
                if ($role['type'] == 2) {
                    $area = '';
                    if ($role['area'] == 1 && isset($temp[1])) {
                        # 城市
                        $area = $temp[0] . ',' . $temp[1];
                    } elseif ($role['area'] == 2 && isset($temp[2])) {
                        # 区县
                        $area = $temp[0] . ',' . $temp[1] . ',' . $temp[2];
                    } elseif ($role['area'] == 3 && isset($temp[3])) {
                        # 街道
                        $area = $temp[0] . ',' . $temp[1] . ',' . $temp[2] . ',' . $temp[3];
                    }
                    if ($area) {
                        
                    }
                }
            }
        }
    }

    # 营业额报表：日期，订单数，确认订单数，确认订单额度，新增代理商数量
    public function order_api()
    {
        $num = Dever::input('num', 5);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);

        for($i=0; $i<=$day; $i++) {
            $where = array();
            $where['fstart'] = $start + 86400*$i;
            $where['fend'] = $start + 86400*$i + 86399;
            $data = array();
            $data['day'] = $where['fstart'];
            $info = Dever::db('bill/order_stat')->find($data);
            $data['num'] = Dever::db('agent/order')->getNum($where);
            $where['status'] = 4;
            $data['yes_num'] = Dever::db('agent/order')->getNum($where);

            $cash = Dever::db('agent/order')->getCash($where);
            if ($cash) {
                $data['cash'] = $cash['total'];
            } else {
                $data['cash'] = 0;
            }
            $agent_cash = Dever::db('agent/order')->getDailiCash($where);
            if ($agent_cash) {
                $data['agent_cash'] = $agent_cash['total'];
            } else {
                $data['agent_cash'] = 0;
            }
            $where['status'] = 2;
            $data['daili_num'] = Dever::db('agent/member')->getNum($where);
            $where['status'] = '-2,1,2,3,6';//驳回不加入
            $where['start'] = $where['fstart'];
            $where['end'] = $where['fend'];
            unset($where['fstart']);
            unset($where['fend']);

            $data['no_num'] = Dever::db('agent/order')->getNum($where);
            $no_cash = Dever::db('agent/order')->getCash($where);
            if ($no_cash) {
                $data['no_cash'] = $no_cash['total'];
            } else {
                $data['no_cash'] = 0;
            }
            if (!$info) {
                Dever::db('bill/order_stat')->insert($data);
            } else {
                $data['where_id'] = $info['id'];
                Dever::db('bill/order_stat')->update($data);
            }
        }
    }

    # 代理商统计：日期，新增代理商，城市代理商，区县代理商，街道代理商，创客，消客
    public function member_api()
    {
        $num = Dever::input('num', 5);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);
        
        for($i=0; $i<=$day; $i++) {
            $where = array();
            $where['status'] = 2;
            $where['fstart'] = $start + 86400*$i;
            $where['fend'] = $start + 86400*$i + 86399;
            $data = array();
            $data['day'] = $where['fstart'];
            $info = Dever::db('bill/member_stat')->find($data);
            $data['num'] = Dever::db('agent/member')->getNum($where);
            $where['role'] = 2;
            $data['city_num'] = Dever::db('agent/member')->getNum($where);

            $where['role'] = 3;
            $data['county_num'] = Dever::db('agent/member')->getNum($where);

            $where['role'] = 4;
            $data['town_num'] = Dever::db('agent/member')->getNum($where);

            $where['role'] = 5;
            $data['cf_num'] = Dever::db('agent/member')->getNum($where);

            $where['role'] = 6;
            $data['ck_num'] = Dever::db('agent/member')->getNum($where);

            $where['role'] = 8;
            $data['cv_num'] = Dever::db('agent/member')->getNum($where);


            if (!$info) {
                Dever::db('bill/member_stat')->insert($data);
            } else {
                $data['where_id'] = $info['id'];
                Dever::db('bill/member_stat')->update($data);
            }
        }
    }

    # 资金账户统计：日期，总收入，代理费，软件服务费，赠送商品价值，直推佣金，市场培训费
    # 总收入金额 = 代理费金额 + 软件服务费 - 赠送商品价值 - 直推分佣 - 市场培训费 - 活动分佣 - 手动发放
    public function cash_in_api()
    {
        $num = Dever::input('num', 5);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);
        
        for($i=0; $i<=$day; $i++) {
            $where = array();
            $where['start'] = $start + 86400*$i;
            $where['end'] = $start + 86400*$i + 86399;
            $data = array();
            $data['day'] = $where['start'];
            $info = Dever::db('bill/cash_in_stat')->find($data);

            $where['status'] = 4;
            $data['daili_cash'] = 0;
            $cash = Dever::db('agent/order')->getDailiCash($where);
            if ($cash) {
                $data['daili_cash'] = $cash['total'];
            }
            $data['soft_cash'] = 0;
            $cash = Dever::db('agent/order')->getSoftCash($where);
            if ($cash) {
                $data['soft_cash'] = $cash['total'];
            }
            $data['goods_cash'] = 0;
            $cash = Dever::db('agent/order')->getGoodsCash($where);
            if ($cash) {
                $data['goods_cash'] = $cash['total'];
            }
            unset($where['status']);

            $where['type'] = 1;

            $data['zt_cash'] = 0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['zt_cash'] = $cash['total'];
            }

            $where['type'] = 2;

            $data['sc_cash'] = 0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['sc_cash'] = $cash['total'];
            }

            $where['type'] = 4;

            $data['hd_cash'] = 0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['hd_cash'] = $cash['total'];
            }

            $where['type'] = 10;

            $data['sd_cash'] = 0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['sd_cash'] = $cash['total'];
            }
            #间推
            $where['type'] =3;
            $whehre['jt_cash'] =0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['jt_cash'] = $cash['total'];
            }

            $data['cash'] = $data['daili_cash'] + $data['soft_cash'] - $data['goods_cash'] - $data['sc_cash'] - $data['zt_cash'] - $data['hd_cash'] - $data['sd_cash'];

            if (!$info) {
                Dever::db('bill/cash_in_stat')->insert($data);
            } else {
                $data['where_id'] = $info['id'];
                Dever::db('bill/cash_in_stat')->update($data);
            }
        }
    }

    # 应付金额 = 现存余额 + 未审核提现 + 已审核待发放提现。
    /*public function cash_out_api()
    {
        $num = Dever::input('num', 1);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);
        
        for($i=0; $i<=$day; $i++) {
            $where = array();
            $where['start'] = $start + 86400*$i;
            $where['end'] = $start + 86400*$i + 86399;
            $data = array();
            $data['day'] = $where['start'];
            $info = Dever::db('bill/cash_in_stat')->find($data);

            $where['status'] = 4;
            $data['daili_cash'] = 0;
            $cash = Dever::db('agent/order')->getDailiCash($where);
            if ($cash) {
                $data['daili_cash'] = $cash['total'];
            }
            $data['soft_cash'] = 0;
            $cash = Dever::db('agent/order')->getSoftCash($where);
            if ($cash) {
                $data['soft_cash'] = $cash['total'];
            }
            $data['goods_cash'] = 0;
            $cash = Dever::db('agent/order')->getGoodsCash($where);
            if ($cash) {
                $data['goods_cash'] = $cash['total'];
            }
            unset($where['status']);

            $where['type'] = 1;

            $data['zt_cash'] = 0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['zt_cash'] = $cash['total'];
            }

            $where['type'] = 2;

            $data['sc_cash'] = 0;
            $cash = Dever::db('bill/cash')->getCash($where);
            if ($cash) {
                $data['sc_cash'] = $cash['total'];
            }

            $data['cash'] = $data['daili_cash'] + $data['soft_cash'] - $data['goods_cash'] - $data['sc_cash'] - $data['zt_cash'];

            if (!$info) {
                Dever::db('bill/cash_in_stat')->insert($data);
            } else {
                $data['where_id'] = $info['id'];
                Dever::db('bill/cash_in_stat')->update($data);
            }
        }
    }
    */
    #财务应付报表：
    #应付金额 = 现存余额 + 未审核提现 + 已审核待发放提现
     public function cash_up_api()
    {
        $num = Dever::input('num', 5);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);
        
        for($i=0; $i<=$day; $i++) {
            $where = array();
            $where['start'] = $start + 86400*$i;
            $where['end'] = $start + 86400*$i + 86399;
            $data = array();
            $data['day'] = $where['start'];
            $info = Dever::db('bill/cash_up_stat')->find($data);
            /*
             现存余额=tixian.php下的cash
             未审核提现=cash下的status=1，type=11
             已审核待发放提现=tixian.php下的status=1,cash
             */
            #现存余额
            $data['xc_cash']=0;
            $where['status'] = 2;
            $cash=Dever::db('bill/tixian')->gettxCash($where);
            if($cash){
                $data['xc_cash']=$cash['total']*(-1);
            }
            #未审核提现
            $where['status']=-1;
            $data['ws_cash']=0;
            // print_R($where);die;
            $tixian=Dever::db('bill/tixian')->getwsCash($where);
            if($tixian){
                // $where['status']=1;
                // $where['type']=11;
                // $where['mid']=$tixian['mid'];
                // $cash=Dever::db('bill/cash')->getwsCash($where);
                $data['ws_cash']=$tixian['total']*(-1);
            }
            #已审核待发放提现
            $data['df_cash']=0;
            $where['status']=1;
            $where['state'] = 1;
            $cash=Dever::db('bill/tixian')->getdfCash($where);
            if($cash){
                $data['df_cash'] = $cash['total'] *(-1);
            }
            $data['cash'] = $data['xc_cash'] + $data['ws_cash'] + $data['df_cash'];

            if (!$info) {
                Dever::db('bill/cash_up_stat')->insert($data);
            } else {
                $data['where_id'] = $info['id'];
                Dever::db('bill/cash_up_stat')->update($data);
            }
        }
    }
    #归店统计
    public function shop_stat_api(){
        $month = Dever::input('month');
        $y = date('Y');
        if($month){
            $month = $month;
        }else{
            $m = date('m')-1;
            if ($m == 0) {
                $y = $y - 1;
                $m = 12;
            }
            $month = $y.'-'.$m;
        }
        $start_time = $month .'-01 00:00:00';
        $end_time = date('Y-m-d', strtotime($start_time. ' +1 month -1 day')).' 23:59:59';
        $start = Dever::maketime($start_time);
        $end = Dever::maketime($end_time);
        $shops = Dever::db('shop/info')->getAll();
        $logs = Dever::db('agent/member_shop_log')->getGui(array('start'=>$start,'end'=>$end,'state'=>1));
        foreach($logs as $a => $b){
            $log[$b['mid']]=$b;
        }
        $logs=array_values($log);
        // print_R($logs);die;
        foreach($shops as $s=>$sv){
            foreach($logs as $l => $lv){
                if($lv['new_shop_id'] == $sv['id']){
                    $sv['mid'][] = $lv['mid'];
                    $sv['cdate'][] = Dever::maketime(date('Y-m-01', $lv['cdate']) . ' 00:00:00');
                    // $lv['cdate'];
                    $shops[] = $sv;
                }else{
                    unset($shops[$s]);
                }
            }
        }
        $data=array_unique($shops, SORT_REGULAR);
        $rest=array();
        foreach($data as $a=>$va){
            $rest[$va['id']]=$va;
        }
        $shop=array_values($rest);
        // print_R($shop);die;
        foreach($shop as $k => $v){
            
            #采购金额
            $shop[$k]['c_money'] = Dever::db('shop/buy_order')->getCashNum(array('type'=>1,'type_id'=>$v['id'],'state'=>1));
            #代理商的总数量
             $shop[$k]['num'] = Dever::db('agent/member_shop_log')->getAll(array('start'=>$start,'end'=>$end,'new_shop_id'=>$v['id'],'state'=>1));
             foreach($v['mid'] as $k1 => $v1){
                $shop[$k]['mids'] = implode(',',$v['mid']);
                #除去创V的代理数量
                $shop[$k]['dl_num'][] = Dever::db('agent/member')->getCount(array('id'=>$v1,'role'=>'1,2,3,4,5,6,7','state'=>1));
                $shop[$k]['ck_num'][] = Dever::db('agent/member')->getCount(array('id'=>$v1,'role'=>'6','state'=>1));
                #创V数量
                $shop[$k]['v_num'][] = Dever::db('agent/member')->getCount(array('id'=>$v1,'role'=>8,'state'=>1));
                #创V名额外数量
                $shop[$k]['out_num'][] = Dever::db('agent/member')->getCount(array('id'=>$v1,'role'=>8,'prize_type'=>1,'state'=>1));
                // foreach($v['cdate'][$k1] as $v2){
                    #代理商业绩
                    $shop[$k]['money'][] = Dever::db('agent/order')->getCount(array('parent_mid'=>$v1,'start'=>$v['cdate'][$k1],'state'=>1));
                    #除去创V的代理商业绩
                    $shop[$k]['dl_money'][] = Dever::db('agent/order')->getVCount(array('parent_mid'=>$v1,'start'=>$v['cdate'][$k1],'role'=>'1,2,3,4,5,6,7'));
                    // echo Dever::sql();die;
                    #创V名额外业绩
                    $out = Dever::db('agent/member')->guidian(array('parent_mid'=>$v1,'start'=>$v['cdate'][$k1],'role'=>8,'prize_type'=>1));
                    if(isset($out) && $out){
                        foreach($out as $v3){
                            $shop[$k]['out_money'][] = Dever::db('agent/order')->getVCount(array('mid'=>$v3['id'],'start'=>$v['cdate'][$k1],'role'=>8,'state'=>1));
                        }
                    }
                // }
                
             }
            #除创V的代理商数量
            if(isset($shop[$k]['dl_num']) && $shop[$k]['dl_num']){
                $shop[$k]['dl_num'] = array_sum($shop[$k]['dl_num']);
            }else{
                $shop[$k]['dl_num'] = 0;
            }
            #创客代理商数量
            if(isset($shop[$k]['ck_num']) && $shop[$k]['ck_num']){
                $shop[$k]['ck_num'] = array_sum($shop[$k]['ck_num']);
            }else{
                $shop[$k]['ck_num'] = 0;
            }
            #创V总数量
            if(isset($shop[$k]['v_num']) && $shop[$k]['v_num']){
                $shop[$k]['v_num'] = array_sum($shop[$k]['v_num']);
            }else{
                $shop[$k]['v_num'] = 0;
            }
            #创V名额外的数量
            if(isset($shop[$k]['out_num']) && $shop[$k]['out_num']){
                $shop[$k]['out_num'] = array_sum($shop[$k]['out_num']);
            }else{
                $shop[$k]['out_num'] = 0;
            }
        }
        // print_R($shop);die;
        foreach($shop as $key => $val){
            #代理商的总业绩
            if(isset($val['money']) && $val['money']){
                $shop[$key]['money'] = array_sum(array_map(function($val){return $val['total'];}, $val['money']));
            }else{
                $shop[$key]['money'] = 0;
            }
            #除创V的代理商业绩
            if(isset($val['dl_money']) && $val['dl_money']){
                $shop[$key]['dl_money'] = array_sum(array_map(function($val){return $val['total'];}, $val['dl_money']));
            }else{
                $shop[$key]['dl_money'] = 0;
            }
            #创V名额外业绩
            if(isset($val['out_money']) && $val['out_money']){
                $shop[$key]['out_money'] = array_sum(array_map(function($val){return $val['total'];}, $val['out_money']));
            }else{
                $shop[$key]['out_money'] = 0;
            }
           
            $insert['shop_id'] = $val['id'];
            $insert['mids'] = $val['mids'];
            $insert['num'] = $val['num'];
            $insert['c_money'] = $val['c_money']['total'];
            $insert['dl_num'] = $val['dl_num'];
            $insert['v_num'] = $val['v_num'];
            $insert['ck_num'] = $val['ck_num'];
            $insert['money'] = $shop[$key]['money'];
            $insert['dl_money'] = $shop[$key]['dl_money'];
            $insert['month'] = $start;
            $insert['out_num'] = $val['out_num'];
            $insert['out_money'] = $shop[$key]['out_money'];

            if($insert){
                $res = Dever::db('bill/shop_stat')->getState(array('start'=>$start,'end'=>$end,'shop_id'=>$insert['shop_id'],'state'=>1));
                if($res){
                    foreach($res as $k2 => $v2){
                        $insert['where_id'] = $v2['id'];
                        Dever::db('bill/shop_stat')->update($insert);
                    } 
                }else{
                    Dever::db('bill/shop_stat')->insert($insert);
                }     
            }
        }     
        return 'ok';
    }

    # 角色统计
    public function role_api()
    {
        $num = Dever::input('num', 5);
        $start = Dever::input('start', date('Y-m-d', strtotime('-'.$num.' day')));
        $end = Dever::input('end', date('Y-m-d'));

        $start = Dever::maketime($start . ' 00:00:00');
        $end = Dever::maketime($end . ' 23:59:59');
        $day = intval(($end - $start)/86400);
        $status = 4;

        $role = Dever::load('setting/role-state');

        for($i=0; $i<=$day; $i++) {
            $where = array();
            $where['fstart'] = $start + 86400*$i;
            $where['fend'] = $start + 86400*$i + 86399;
            $where['status'] = 4;

            foreach ($role as $k => $v) {
                $data = array();
                $data['day'] = $where['fstart'];
                $data['role'] = $v['id'];
                $data['clear'] = true;
                $where['role'] = $v['id'];
                $info = Dever::db('bill/role_stat')->find($data);
                $data['num'] = Dever::db('agent/order')->getNum($where);
                if ($data['num'] && $data['num'] > 0) {
                    $cash = Dever::db('agent/order')->getCash($where);
                    if ($cash) {
                        $data['cash'] = $cash['total'];
                    } else {
                        $data['cash'] = 0;
                    }
                    $data['touru'] = $data['cash'];
                    $cash = Dever::db('agent/member')->getCash($where);
                    if ($cash) {
                        $data['shouru'] = $cash['total'];
                    } else {
                        $data['shouru'] = 0;
                    }
                    if (!$info) {
                        Dever::db('bill/role_stat')->insert($data);
                    } else {
                        $data['where_id'] = $info['id'];
                        Dever::db('bill/role_stat')->update($data);
                    }
                }
            }
        }

        return 'ok';
    }
}