<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class HandselAction extends MemberAction
{
    public function run()
    {
        $id = S::gp('id', 'G', 2);
        $handsel = PropertyHandsel::single()->getOne($id);
        if (empty($handsel))
        {
            throw new iSystemException('找不到勋章赠送记录');
        }
        if ($handsel['getuid'] != $this->uid())
        {
            throw new iSystemException('此勋章不是赠送给您，不能接受');
        }
        if ($handsel['status'] != 0)
        {
            throw new iSystemException('此赠送已经锁定，不能再操作');
        }
        if (!iMedals::single()->medalExists($handsel['medalid']))
        {
            throw new iSystemException('不存在的勋章');
        }
        
        if ('denial' == trim($_GET['do']))
        {
            PropertyHandsel::single()->update($id, array('status'=>2));
            iexit('拒绝成功');
        }
        else
        {
            $check = $this->db()->select()->from(Memberfields::table())->where('uid='.$this->uid())->find(true);
            if (!empty($check['medals']) && !$_GET['confirm'])
            {
                $existsMedals = iMedals::single()->getMedalsString($check['medals']);
                if (!empty($existsMedals))
                {
                    $message[] = '您当前已经有'.count($existsMedals['images']).'枚勋章:'.implode('', $existsMedals['images']);
                    $message[] = '如果您接受此勋章，之前的将被删除，是否'.ilink('接受',url('system',array('s'=>'member','a'=>'handsel','id'=>$id,'do'=>'accept','confirm'=>1))).'|'.ilink('拒绝', url('system',array('s'=>'member','a'=>'handsel','do'=>'denial','id'=>$id))).'？';
                    iexit($message);
                }
            }
        
            $medals = $handsel['medalid'] . '|' . (time() + $handsel['days'] * 24 * 3600);
            $this->db()->update(Memberfields::table())->value(array('medals'=>$medals))->where('uid='.$this->uid())->q();
            PropertyHandsel::single()->update($id, array('status'=>1));
            
            Members::single()->updateOneCache($this->uid());
            $message[] = '勋章接受成功';
            $message[] = '返回'.ilink('信箱', url('system',array('s'=>'member','c'=>'message'))) . '.' .memberLink(). '.' . indexLink();
            $this->showMessage($message);
        }
    }
}