<?php
/**
 *
 */
include_once(SERVER_ROOT."/model/mBase.php");


class mShop extends mBase {

    private $obj;
    private $shop;

    public function __construct() {
        $this->obj = new dShop();
        $this->shop = 'shop_list';
    }

    public function addShop($name, $access_token, $expire_time, $uid=0) {
        $data = array();
        $data['access_token'] = $access_token;
        $data['expire_time'] = $expire_time;

        $info = $this->getShopByName($name);
        if ($info) {
            $res = $this->updateShop($info['id'], $data);

            return $info;
        }

        if ($uid) {
            $data['uid'] = $uid;
        } else {
            $uobj = new mUser();
            $uid = $uobj->addUser();
            if (!$uid) {
                $this->setError('uid创建失败');
                return false;
            }
            $data['uid'] = $uid;
        }
        $data['name'] = $name;

        $res = $this->obj->insert($this->shop, $data);

        $this->syncHistoricalOrders($name);

        $info = $this->getShopByName($name);
        return $info;
    }

    /**
     * 同步最近3个月历史订单
     * @param unknown $name
     * @return boolean
     */
    public function syncHistoricalOrders($name) {
        $rdobj = $this->initRedis();

        $start_date = date("Y-m-d", strtotime('-3 month'));

        for($i=0; $i<100; $i++) {
            $date = date("Y-m-d", strtotime($start_date)+$i*86400);
            if ($date > date("Y-m-d H:i:s")) break;

            // 同步历史订单
            $rdobj->lpush(_RQ_SYNC_HISTORICAL_ORDERS, json_encode(array('name'=>$name, 'start_date'=>$date)));

            // 同步增量订单开始时间
            if ($date == date("Y-m-d")) {
                $rdobj->lpush(_RQ_SYNC_INCREMENT_ORDERS, json_encode(array('name'=>$name, 'start_date'=>date("Y-m-d H:i:s"), 'end_date'=>date("Y-m-d H:i:s", strtotime("+5 minute")))));
            }
        }

        return true;
    }

    public function getShopByName($name) {
        return $this->obj->select($this->shop, array('sql'=>'`name`=?', 'vals'=>array($name)));
    }

    public function getShopById($id) {
        return $this->obj->select($this->shop, array('sql'=>'`id`=?', 'vals'=>array($id)));
    }


    public function updateShop($id, $data) {
        return $this->obj->update($this->shop, $data, array('sql'=>'`id`=?', 'vals'=>array($id)));
    }

}