<?php namespace Seller\Api;
use Dever;
use \Dever\Helper\Redis;
use \Dever\Helper\Str;
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 >= 1000) {
                    # 等会儿再执行
                    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).'"}\'';
        exec($command, $out);
    }

    # 获取当前执行的子进程数量
    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 stat_commit(){}
    public function stat()
    {
        # 获取昨天的时间
        $time = \Dever\Helper\Date::day();
        $where['cdate'] = array('<', $time[0]);
        $where['status'] = array('>=', 10);
        $order = Dever::db('order', '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) {
            if ($v['status'] >= 10) {
                # 整理这一天成功的和失败的
                $day = \Dever\Helper\Date::mktime(date('Y-m-d 00:00:00', ($v['finish_date'] ? $v['finish_date'] : $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']);
                }

                $state = Dever::db('order_bak', 'seller')->insert($v);
                if ($state) {
                    Dever::db('order', 'seller')->delete($v['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['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);
            }
        }
    }
}