<?php

namespace loyalsoft;

/**
 * Description of AuctionProc
 *
 * @author cyzhao
 */
class AuctionProc {

    static function procMain() {
        switch (req()->cmd) {
            case CmdCode::cmd_Auction_GetUserAuctionItemsInfo:                  # 7401 获取全部拍卖信息
                return AuctionProc::GetAuctionItemsInfo();
            case CmdCode::cmd_Auction_GetUserUploadAuctionItems:                # 7402 玩家上架拍品信息
                return AuctionProc::GetUserUploadAuctionItems();
            case CmdCode::cmd_Auction_GetUserAuctionItems:                      # 7403 玩家竞拍信息
                return AuctionProc::GetUserAuctionItems();
            case CmdCode::cmd_Auction_BuyoutPrice:                              # 7404 竞拍/一口价
                return AuctionProc::BuyoutPrice();
            case CmdCode::cmd_Auction_CancelAuction:                            # 7405 取消出售
                return AuctionProc::CancelAuction();
            case CmdCode::cmd_Auction_UploadAuctionItems:                       # 7406 上传拍品
                return AuctionProc::UploadAuctionItems();       
            case CmdCode::cmd_Auction_UserAuctionBidItem:                       # 7407 竞拍
                return AuctionProc::UserAuctionBidItem();
            default:
                Err(ErrCode::cmd_err);
        }
    }

    /**
     * 获取全部拍卖信息
     */
    static function GetAuctionItemsInfo() {
        $obj = self::getAuctionUserItemListCache();
        if ($obj == null || $obj->ts < TimeUtil::tsCurrent(-3)) { # 查不到缓存,或者缓存是3秒以前的
            $obj = self::updateAuctionUserItemListCache(); # 更新玩家列表
        }
//        $ret = array(
//            "auction" => $obj->data,
//                //"bidRecord" => $req->userInfo->privateState->arrUserlAucBidItems # 加一个出价记录
//        );

        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "auction" => $obj->data,
        ));
    }

    /**
     * 玩家上架拍品信息
     */
    static function GetUserUploadAuctionItems() {       
        $dic = self::getMyAuctionItems();#上架信息
        
        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "auction" => $dic,
        ));
    }

    /**
     * 玩家竞拍信息
     */
    static function GetUserAuctionItems() {
        $result = self::selectMyAuctionBid();
        
        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "auction" => $result,
        ));
    }

    /**
     * 一口价-7404 ----暂时没有竞拍，只有一口价
     */
    static function BuyoutPrice() {
        list($uId) = req()->paras;
        $aucItem = self::getAuctionItem($uId);
              
        $buyoutPrice = $aucItem->buyoutPrice;             
        
        my_Assert($aucItem->result == "", "该拍品不能竞拍");  
        my_Assert($aucItem->sellerid != req()->uid, "不能竞拍自己的拍品");       
        my_Assert(req()->userInfo->game->baseInfo->cash >= $buyoutPrice, ErrCode::notenough_cash_msg);               
        //扣除钻石--交易费用 + 手续费
        req()->userInfo->game->base()->Consume_Cash($buyoutPrice);    
        //req()->userInfo->game->baseInfo->cash -= $buyoutPrice; 
                                   
        //更新表里的交易状态
        $aucItem->result = "完成";
        $aucItem->currpeopleid = req()->uid;
        $aucItem->currpeoplename = req()->userInfo->game->baseInfo->name;     
        
        $err = self::settleAuctionItem($aucItem); # 更新数据库     
//更新拍品缓存

        $obj = self::updateAuctionUserItemListCache();        
//发送邮件，给拍品
        $sList = explode(',', $aucItem->contents);
        EmailProc::SendAuctionItemsMail(req()->zoneid, req()->uid, $sList[0], $sList[1]); 
               
        EmailProc::SendAuctionCashMail(req()->zoneid,$aucItem->sellerid, $sList[0], 2, $buyoutPrice -intval($buyoutPrice * 0.05));//上架玩家给钻石邮件  
        
        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "auction" => $obj->data,
                    "cash"=>req()->userInfo->game->baseInfo->cash,
        ));
    }

    /**
     * 取消出售
     */
    static function CancelAuction() {
        list($uId) = req()->paras;
        $aucItem = self::getAuctionItem($uId);
        $aucItem->result = "取消出售";
        
        $ctxList = explode(',', $aucItem->contents);
        EmailProc::SendCantSellAuctionItemsMail(req()->zoneid, req()->uid, $ctxList[0],$ctxList[1]);
        
        self::updateAuctionItemState($aucItem);
        self::updateAuctionUserItemListCache();
                 
        $dic = self::getMyAuctionItems();#上架信息
        
        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "auction" => $dic,
        ));
    }

    /**
     * 上传拍品
     * @return type
     */
    static function UploadAuctionItems() {
        list($itemId, $num,$bugoutPrice) = req()->paras; //上传拍品的 id 数量 竞拍价 一口价

        $user = req()->userInfo->game; 

        my_Assert(StlUtil::dictHasProperty($user->store->items, $itemId), ErrCode::store_itemno_err); # 参数合法性判断
        $mo = GameConfig::item_base_getItem($itemId);       
        my_Assert($mo != null, ErrCode::err_const_no);
                             
        $sList = explode(',', $mo->buyoutPrice);       
        my_Assert($bugoutPrice>= $sList[1], ErrCode::notenough_cash_msg);
        
        StoreProc::removeItemFromStore($user->store, $itemId, $num);
       
        $aucItem = new Ins_AuctionItemModel();
        $aucItem->addstep = 1;
        $aucItem->contents = $itemId.",".$num;       
        $aucItem->startprice = 0;
        $aucItem->buyoutPrice = $sList[1]*$num;
        $aucItem->startts = time();
        $aucItem->endts = glc()->AuctionEndTs * 60 * 60 + time(); # 24小时 
        $aucItem->sellerid = req()->uid;
        $aucItem->sellername = $user->baseInfo->name;
        $aucItem->zoneid = req()->zoneid;              
        $err = self::insertNewUserAuctionItem($aucItem);
       
        my_Assert($err == 1, ErrCode::err_db);
      
        # 插入成功后,更新缓存
        # 写入玩家数据
        $auctionDic = self::updateAuctionUserItemListCache(); # 更新缓存    
        
        req()->userInfo->game = $user;      
        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "store" => $user->store,
                    "auction"=>$auctionDic,#拍品
        ));
    }
    
    /**
     * 竞价
     */
    static function UserAuctionBidItem() {
        list($uId) = req()->paras;
        $aucItem = self::getAuctionItem($uId);
        
        UserProc::updateUserInfo();                                             # 回写玩家数据
        return Resp::ok(array(
                    "store" => $user->store,
                    "auction"=>$auctionDic,#拍品
        ));
    }
    
    static function TriggerSettlement() {     
        $result = self::selectTimeoutAuctionItems();
        if(count($result) > 0){
            foreach ($result as $aucItem) {
                //发送流拍邮件
                $sList = explode(',', $aucItem->contents);               
                EmailProc::SendAuctionItemsStreamingMail(req()->zoneid, req()->uid, $sList[0], $sList[1]);
                
                //更新数据库信息
                $aucItem->result = "流拍";               
                self::updateAuctionItemState($aucItem);              
            }
        }
   
        return "ok";
    }




    /**
     * 获取当前的玩家拍卖缓存
     * @param type $mem
     * @return array
     */
    static function getAuctionUserItemListCache() {
        return gMem()->get(self::auctionItemListCache(req()->zoneid));
    }

    /**
     * 玩家拍卖的拍品列表缓存
     * @return string
     */
    static function auctionItemListCache($zoneid) {
        return "auction-user-itemlist" . "-zone" . $zoneid;
    }
    
    /**
     * 插入新的玩家拍品
     * @param Ins_AuctionItemModel $aucItem
     */
    static function insertNewUserAuctionItem($aucItem) {
        $paydb = daoInst();              
        $sql = "INSERT INTO `tab_auctionitems` (contents,startprice,buyoutPrice,startts,endts,sellerid,sellername,auchistory,zoneid) VALUES ('%s',%d,%d,%d,%d,'%s','%s','{}',%d)";
        $query = sprintf($sql, $aucItem->contents, $aucItem->startprice,$aucItem->buyoutPrice,$aucItem->startts, #
                $aucItem->endts, $aucItem->sellerid,$aucItem->sellername, $aucItem->zoneid);     
        $result = $paydb->exec($query);          
        return $result;
    }
    
    /**
     * 更新玩家拍卖拍品列表缓存
     * @param type $mem
     * @return array
     */
    static function updateAuctionUserItemListCache() {       
        $aucOfficial = self::getAuctionUserItemList(req()->zoneid); // 查询拍品列表                
        $obj = array(
            'ts' => time(),
            'data' => $aucOfficial,
        );
             
        gMem()->set(self:: auctionItemListCache(req()->zoneid), $obj); # 写入缓存      
        return json_decode(json_encode($obj));
    }
    /**
     * 取今天的玩家拍卖拍品集合
     * @return array
     */
    static function getAuctionUserItemList($zoneid = 1) {
        $now = time(); # 当前时间戳       
        $sql = "SELECT * from tab_auctionitems WHERE zoneid=$zoneid and $now < endts and $now >= startts"; 
        $paydb = daoInst();
        $result = $paydb->query($sql)->fetchAll();
        return $result; # 索引数组
    }
    
    /**
     * 查询某个拍品
     * @param type $aucItemId
     * @return Ins_AuctionItemModel
     */
    static function getAuctionItem($aucItemId) {
        $sql = "SELECT * from tab_auctionitems WHERE itemid = $aucItemId";
        $paydb = daoInst();
        $result = $paydb->query($sql)->fetchAll();
       
        return $result[0]; # 索引数组
    }
    
    /**
     * 结算更新
     * @param AuctionItemModel $aucItem
     */
    static function settleAuctionItem($aucItem) {         
        $sql = "UPDATE `tab_auctionitems` set result = '%s',currpeopleid = '%s',currpeoplename = '%s' where itemid = '%d'";
        $query = sprintf($sql, $aucItem->result, $aucItem->currpeopleid,$aucItem->currpeoplename,$aucItem->itemid);
        
        $paydb = daoInst();
        $result = $paydb->exec($query);             
        return $result;
    }
    
    /**
     * 
     * @param type $aucItem
     */
    static function updateAuctionItemState($aucItem) {
        $sql = "UPDATE `tab_auctionitems` set result = '%s' where itemid='%d'";
        $query = sprintf($sql,$aucItem->result, $aucItem->itemid);
        $paydb = daoInst();
        $result = $paydb->exec($query);             
        return $result;
    }
    
    /**
     * 查询我的上架拍品的信息
     * @return type
     */
    static function getMyAuctionItems() {
        $ts = time();
        $zoneid = req()->zoneid;
        $uid = req()->uid;
        $db = daoInst();
        $sql = "select * from tab_auctionitems where zoneid=$zoneid and sellerid = '$uid'";
        $result = $db->query($sql)->fetchAll();
       
        return $result;
    }
    /**
     * 玩家的竞拍信息
     * @param type $zoneid
     * @param type $oid
     * @return type
     */
    static function selectMyAuctionBid() {   
        $zoneid = req()->zoneid;
        $oid = req()->uid;
            
        $db = daoInst();
        $sql = "select * from tab_auctionitems where zoneid=$zoneid and currpeopleid = '$oid'";
        $result = $db->query($sql)->fetchAll();
        
        return $result;
    }
    
    /**
     * 查询到期且未处理的拍品
     * @return type
     */
    static function selectTimeoutAuctionItems() {
        $ts = time();
        $zoneid = req()->zoneid;     
        $db = daoInst();
        $sql = "select * from tab_auctionitems where zoneid=$zoneid and result = '' and $ts>endts";
        $result = $db->query($sql)->fetchAll();
       
        return $result;
    }
}
