<?php
/**
 * 更新会员组资料
 * @author yzxh24
 */
class MemberAction extends BaseAction
{
    public function run()
    {
        if (Yii::app()->request->isPostRequest)
        {
            $newGroups = $this->getController()->arrayFlipKeys($_POST['add']);
            $oldGroups = $_POST['group'];
            foreach($newGroups as $k => $v)
            {
				if(!$v['title'] || !$v['title1'] || !$v['title2'] || !$v['creditshigher'])
				{
					unset($newGroups[$k]);
				}
            }
            $groupKeys = array_keys($oldGroups);
            $maxGroupId = max($groupKeys);
            foreach($newGroups as $k => $v)
            {
                $oldGroups[$k + $maxGroupId + 1] = $v;
            }
            
            $orderArray = array();
            if(is_array($oldGroups))
            {
				foreach($oldGroups as $id => $group)
				{
				    $orderArray[$group['creditshigher']] = $id;
				}
			}
			ksort($orderArray);
			
            $rangeArray = array();
			$lowerLimit = array_keys($orderArray);
			for($i = 0; $i < count($lowerLimit); $i++)
			{
				$rangeArray[$orderArray[$lowerLimit[$i]]] = array(
					'creditshigher' => isset($lowerLimit[$i - 1]) ? $lowerLimit[$i] : -999999999,
					'creditslower' => isset($lowerLimit[$i + 1]) ? $lowerLimit[$i + 1] : 999999999
				);
			}
			
            foreach($oldGroups as $id => $group)
            {
				$creditsHigherNew = $rangeArray[$id]['creditshigher'];
				$creditsLowerNew = $rangeArray[$id]['creditslower'];

				if(in_array($id, $groupKeys))
				{
				    $item = UserGroup::model()->find('groupid='.$id." AND gptype='member'");
				    if (!empty($item))
				    {
				        $item->grouptitle = $group['title'];
				        $item->grouptitle1 = $group['title1'];
				        $item->grouptitle2 = $group['title2'];
				        $item->creditshigher = $creditsHigherNew;
				        $item->creditslower = $creditsLowerNew;
				        $item->save();
				    }
				}
				elseif($group['title'] && $group['creditshigher'] != '')
				{
				    $item = new UserGroup();
				    $item->grouptitle = $group['title'];
				    $item->grouptitle1 = $group['title1'];
				    $item->grouptitle2 = $group['title2'];
				    $item->creditshigher = $creditsHigherNew;
			        $item->creditslower = $creditsLowerNew;
			        $item->gptype = 'member';
			        $item->isdefault = 0;
			        $item->groupimg = 6;
			        $item->save();
				}
			}
			
			$this->getController()->redirect(array('index'));
        }
        else
        {
            throw new CHttpException(500, '非法操作');
        }
    }
}