<?php namespace Seller\Api;
use Dever;
use \Dever\Helper\Redis;
use \Dever\Helper\Str;
use \Dever\Helper\Cmd;
ini_set("memory_limit", -1);
class Task
{
    # 每个商户一个进程，暂时不做
    public function act()
    {
        $seller = Dever::db('info', 'seller')->select(array('status' => 1));
        if ($seller) {
            foreach ($seller as $k => $v) {

            }
        }
    }

    public function cron()
    {
        while(1) {
            try {
                # 获取当前执行的进程数量
                $num = $this->getNum();
                if ($num >= 500) {
                    # 等会儿再执行
                    sleep(30);
                }
                $data = Redis::pop('submit_' . DEVER_PROJECT);
                if ($data) {
                    $this->popen($data);
                }
            } catch (\Exception $e) {
                $this->redis = false;
            }
        };
    }

    # 将数据推到子进程处理
    private function popen($order)
    {
        $command = 'php /www/'.DEVER_PROJECT.'/src/dai/seller/index.php \'{"l":"task.run","order":"'.Str::encode($order).'"}\'';
        Cmd::shell($command);
    }

    # 获取当前执行的子进程数量
    private function getNum()
    {
        $command = 'ps -ef | grep task.run | grep -v grep | wc -l';
        $num = exec($command);
        return $num;
    }

    public function run()
    {
        $order = Str::decode(Dever::input('order'));
        $info = Dever::db('order', 'seller')->find($order);
        if ($info) {
            Dever::load('order', 'seller')->handle($info);
        }
    }

    # 每日整理订单数据
    public function order_commit(){}
    public function order()
    {
        # 获取昨天的时间
        $time = \Dever\Helper\Date::day();
        $where['cdate'] = array('<', $time[0]);
        $where['status'] = array('>=', 10);
        $order = Dever::db('order', 'seller')->load($where);
        foreach ($order as $k => $v) {
            if ($v['status'] >= 10 && $v['finish_date'] > 0) {
                $info = Dever::db('order_bak', 'seller')->find($v['id']);
                if (!$info) {
                    $info = Dever::db('order_bak', 'seller')->insert($v);
                }
                if ($info) {
                    Dever::db('order', 'seller')->delete($v['id']);
                }
            }
        }
    }

    # 统计
    public function stat()
    {
        $day = Dever::input('day');
        if ($day) {
            $time = \Dever\Helper\Date::day($day);
        } else {
            # 获取昨天的时间
            $time = \Dever\Helper\Date::day(1);
        }
        
        $where['cdate'] = array('>=', $time[0]);
        $where['#cdate'] = array('<=', $time[1]);
        $order = Dever::db('order_bak', 'seller')->load($where);
        $data = array();
        $default = array
        (
            'total_num' => 0,
            'success_num' => 0,
            'error_num' => 0,
            'total_cash' => 0,
            'success_cash' => 0,
            'error_cash' => 0,
            'seller_actual_cash' => 0,
            'channel_actual_cash' => 0,
            'profit_cash' => 0,
            'data' => array(),
        );
        foreach ($order as $k => $v) {
            # 整理这一天成功的和失败的
            $day = \Dever\Helper\Date::mktime(date('Y-m-d 00:00:00', $v['cdate']));
            $this->statItem($data, $day, '_1', $default, $v);
            $this->statItem($data, $day, 'seller_' . $v['seller_id'], $default, $v, $v['channel_id']);
            if ($v['channel_id']) {
                $this->statItem($data, $day, 'channel_' . $v['channel_id'], $default, $v, $v['seller_id']);
            }
        }

        if ($data) {
            foreach ($data as $k => $v) {
                foreach ($v as $k1 => $v1) {
                    $v1['data'] = Dever::json_encode($v1['data']);
                    $k1 = explode('_', $k1);
                    $w = array();
                    $w['day'] = $k;
                    $table = 'order_stat';
                    if ($k1[0]) {
                        $w[$k1[0] . '_id'] = $k1[1];
                        $table .= '_' . $k1[0];
                    }
                    $info = Dever::db($table, 'seller')->find($w);
                    if ($info) {
                        Dever::db($table, 'seller')->update($info['id'], $v1);
                    } else {
                        $v1 = array_merge($v1, $w);
                        Dever::db($table, 'seller')->insert($v1);
                    }
                }
            }
        }
    }

    public function statItem(&$data, $day, $mid, $default, $v, $rid = false)
    {
        if (!isset($data[$day][$mid])) {
            $data[$day][$mid] = $default;
        }
        if ($rid) {
            if (!isset($data[$day][$mid]['data'][$rid])) {
                $data[$day][$mid]['data'][$rid] = $default;
            }
        }
        
        $data[$day][$mid]['total_num'] += $v['num'];
        $data[$day][$mid]['total_cash'] += $v['cash'];
        if ($rid) {
            $data[$day][$mid]['data'][$rid]['total_num'] += $v['num'];
            $data[$day][$mid]['data'][$rid]['total_cash'] += $v['cash'];
        }
        if ($v['status'] == 10) {
            $data[$day][$mid]['success_num'] += $v['num'];
            $data[$day][$mid]['success_cash'] += $v['cash'];
            $data[$day][$mid]['seller_actual_cash'] += $v['price'];
            $data[$day][$mid]['channel_actual_cash'] += $v['buy_price'];
            $data[$day][$mid]['profit_cash'] += ($v['price']-$v['buy_price']);
            if ($rid) {
                $data[$day][$mid]['data'][$rid]['success_num'] += $v['num'];
                $data[$day][$mid]['data'][$rid]['success_cash'] += $v['cash'];
                $data[$day][$mid]['data'][$rid]['seller_actual_cash'] += $v['price'];
                $data[$day][$mid]['data'][$rid]['channel_actual_cash'] += $v['buy_price'];
                $data[$day][$mid]['data'][$rid]['profit_cash'] += ($v['price']-$v['buy_price']);
            }

        } elseif ($v['status'] == 11) {
            $data[$day][$mid]['error_num'] += $v['num'];
            $data[$day][$mid]['error_cash'] += $v['cash'];
            if ($rid) {
                $data[$day][$mid]['data'][$rid]['error_num'] += $v['num'];
                $data[$day][$mid]['data'][$rid]['error_cash'] += $v['cash'];
            }
        }
    }

    # 每小时统计一次正确的商户余额
    public function yue()
    {
        $where['status'] = 1;
        $seller = Dever::db('info', 'seller')->load($where);
        foreach ($seller as $k => $v) {
            $data = Dever::db('log', 'seller')->select(array('seller_id' => $v['id']), array('col' => 'sum(cash)'));
            if ($data && isset($data[0]['sum'])) {
                //$sum = $data[0]['sum'] - $v['credit'];
                $sum = $data[0]['sum'];
                //Dever::db('info', 'seller')->update($v['id'], array('cash' => $sum));
            }
        }
    }

    # 每5分钟跑一次回调
    public function callback()
    {
        $where['status'] = array('>=', 10);
        $where['seller_callback_num'] = array('<=', 5);
        $where['seller_callback_date'] = array('<=', time() + 300);
        $where['finish_date'] = $where['seller_callback_date'];
        $where['seller_callback'] = array('!=', 'ok');
        $order = Dever::db('order', 'seller')->load($where);
        foreach ($order as $k => $v) {
            $msg = '';
            if ($v['status'] == 10) {
                $msg = 'ok';
            } elseif ($v['status'] == 11) {
                $msg = 'error';
            }
            if ($msg) {
                Dever::load('order', 'seller')->notify($v, $msg);
            }
        }
    }

    # 每5分钟跑一次处理中
    public function chuli()
    {
        $where['status'] = 1;
        $where['cdate'] = array('<=', time() + 500);
        $order = Dever::db('order', 'seller')->select($where);

        $test = Dever::input('test');
        if ($test == 1) {
            print_r($order);die;
        }
        foreach ($order as $k => $v) {
            Dever::load('order', 'seller')->handle($v);
        }
    }

    # 插入测试数据
    public function test()
    {
        $where = array();
        //$where['id'] = '65c345d7d46ba46b32041d32';
        $where['status'] = 10;
        $set = array();
        //$where['sku_id'] = 18;
        //$set['limit'] = 10;
        //$set['order'] = 'total desc';
        //$set['col'] = 'id,cash,seller_id';
        //$set['group'] = 'cash';
        //$set['col'] = 'sum(cash)';
        //$info = Dever::db('order_log1', 'seller')->count($where, $set);
        //print_r($info);die;
        $order = Dever::db('order', 'seller')->load([]);
        foreach ($order as $k => $v) {
            //$v['cdate'] = time();
            //unset($v['id']);
            $id = Dever::db('order_log1', 'seller')->insert($v);
            //print_r($id);die;
        }
        $this->test();
    }

    # 历史数据整理
    public function history_order()
    {
        $order = Dever::db('order_bak', 'seller')->load([]);
        foreach ($order as $k => $v) {
            $order_log = Dever::db('order_log1', 'seller')->find(array('order_num' => $v['order_num']));
            if (!$order_log) {
                Dever::db('order_log1', 'seller')->insert($v);
            }
        }
    }
    public function history()
    {
        $order = Dever::db('log', 'seller')->select([]);
        foreach ($order as $k => $v) {
            Dever::db('log1', 'seller')->insert($v);
            /*
            $log = Dever::db('log1', 'seller')->find(array('sid' => $v['id']));
            if (!$log) {
                $v['sid'] = $v['id'];
                unset($v['id']);
                Dever::db('log1', 'seller')->insert($v);
            }*/
        }
    }
}