<?php
// +----------------------------------------------------------------------
// | Sunnyi 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.sunnyi.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 商易网络(admin@sunnyi.cn)
// +----------------------------------------------------------------------

// 配送方式
class DeliveryAction extends CommonAction{
	public function add()
	{
		$weight_list = D("Weight")->findAll();
		$default_lang_id = D("LangConf")->where("lang_name='".C('DEFAULT_LANG')."'")->getField("id");
		foreach($weight_list as $k=>$v)
		{
			$weight_list[$k]['name'] = $v['name_'.$default_lang_id];
		}
		$this->assign("weight_list",$weight_list);
		
		$new_sort = D(MODULE_NAME)-> max("sort") + 1;
		$this->assign("new_sort",$new_sort);
		parent::add();
	}
	
	public function insert()
	{
		$_POST['first_weight'] = toBaseWeight($_POST['first_weight'],$_POST['weight_unit']);
		$_POST['continue_weight'] = toBaseWeight($_POST['continue_weight'],$_POST['weight_unit']);
		//B('FilterString');
		$name=$this->getActionName();
		$model = D ($name);
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			//开始存储配送地区
			$region_ids_array = $_POST['region_ids'];
			$region_first_price = $_POST['region_first_price'];
			$region_continue_price = $_POST['region_continue_price'];
			$region_allow_cod = $_POST['region_allow_cod'];
			foreach($region_ids_array as $k=>$v)
			{
				$data['region_ids'] = $v;
				$data['first_price'] = $region_first_price[$k];
				$data['continue_price'] = $region_continue_price[$k];
				$data['allow_cod'] = $region_allow_cod[$k];
				$data['delivery_id'] = $list;
				D("DeliveryRegion")->add($data);
			}
			$this->saveLog(1,$list);
//			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('ADD_SUCCESS'));
		} else {
			//失败提示
			$this->saveLog(0,$list);
			$this->error (L('ADD_FAILED'));
		}
	}
	
	public function edit()
	{
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );

		$vo['first_weight'] = fromBaseWeight($vo['first_weight'],$vo['weight_unit']);
		$vo['continue_weight'] = fromBaseWeight($vo['continue_weight'],$vo['weight_unit']);

		$this->assign ( 'vo', $vo );
		
		$weight_list = D("Weight")->findAll();
		$default_lang_id = D("LangConf")->where("lang_name='".C('DEFAULT_LANG')."'")->getField("id");
		foreach($weight_list as $k=>$v)
		{
			$weight_list[$k]['name'] = $v['name_'.$default_lang_id];
		}
		$this->assign("weight_list",$weight_list);

		$region_list = D("DeliveryRegion")->where("delivery_id=".$id)->findAll();
		foreach($region_list as $k=>$v)
		{
			if($v['region_ids']!=0)
				$ids = explode(",",$v['region_ids']);
				else 
				$ids = 0;
			$names_arr = D("RegionConf")->where(array("id"=>array("in",$ids)))->findAll();
			$names_str = '';
			foreach($names_arr as $kk=>$vv)
			{
				$names_str .= $vv['name'].",";
			}
			if($names_str!='')
			$names_str = substr($names_str,0,-1);
			$region_list[$k]['names'] = $names_str;
		}

		$this->assign("region_list",$region_list);
		
		$this->display ();
	}
	
	
	public function update()
	{
		$_POST['first_weight'] = toBaseWeight($_POST['first_weight'],$_POST['weight_unit']);
		$_POST['continue_weight'] = toBaseWeight($_POST['continue_weight'],$_POST['weight_unit']);
	//B('FilterString');
		$name=$this->getActionName();
		$model = D ( $name );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		// 更新数据
		$data = $model->create();
		if(!$data['allow_default'])$data['allow_default'] = 0;
		$list=$model->save ($data);
		if (false !== $list) {
			//成功
			
			//开始存储配送地区
			$ids = $_POST['ids'];
			$region_ids_array = $_POST['region_ids'];
			$region_first_price = $_POST['region_first_price'];
			$region_continue_price = $_POST['region_continue_price'];
			$region_allow_cod = $_POST['region_allow_cod'];
			foreach($region_ids_array as $k=>$v)
			{
				$data['id'] = intval($ids[$k]);
				$data['region_ids'] = $v;
				$data['first_price'] = $region_first_price[$k];
				$data['continue_price'] = $region_continue_price[$k];
				$data['allow_cod'] = $region_allow_cod[$k];
				$data['delivery_id'] = $_REQUEST['id'];
				if($data['id']==0)
				D("DeliveryRegion")->add($data);
				else 
				D("DeliveryRegion")->save($data);
			}
			
			$this->saveLog(1);
//			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		} else {
			//错误提示
			$this->saveLog(0);
			$this->error (L('EDIT_FAILED'));
		}
	}
	
	
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				if(D("Order")->where(array ("delivery" => array ('in', explode ( ',', $id ) ) ))->count()>0)
				{
					$this->error (L('DELIVERY_USED'));
				}
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					//echo $model->getlastsql();
					D("DeliveryRegion")->where(array ("delivery_id" => array ('in', explode ( ',', $id ) ) ))->delete();
					$this->saveLog(1);
					$this->success (L('DEL_SUCCESS'));
				} else {
					$this->saveLog(0);
					$this->error (L('DEL_FAILED'));
				}
			} else {
				$this->saveLog(0);
				$this->error ( L('INVALID_OP') );
			}
		}
		$this->forward ();
	}
	
	public function delRegionItem()
	{
		$id = intval($_REQUEST['id']);
		if(D("DeliveryRegion")->where("id=".$id)->delete())
		{
			echo 1;
		}
		else 
		{
			echo 0;
		}
	}
	
	function getDelivery(){
		$id = intval($_REQUEST ['id']);
		$weight = floatval($_REQUEST ['weight']);
		$money = floatval($_REQUEST ['money']);
		
		//$region_lv1 = $_REQUEST ['region_lv1']; //国家
		$region_lv2 = intval($_REQUEST ['region_lv2']);//省
		$region_lv3 = intval($_REQUEST ['region_lv3']);//地/市
		$region_lv4 = intval($_REQUEST ['region_lv4']);//区/县
		
		$model = D ("Delivery");
		$vo = $model->getById ( $id );	
		
		$type2 = false;
		
		//type 地区费用类型：0:统一设置;1:指定配送地区和费用
		$vo['type'] = D("DeliveryRegion")->where('delivery_id = '.$id)->count();
		if ($vo['type'] >= 1){
			if (!empty($region_lv4) && $region_lv4 != -1){
				$sql_str = 'select * from '.C("DB_PREFIX").'delivery_region where delivery_id = '.$id.' and region_ids like \'%,'.$region_lv4.',%\' limit 1';
				$area_vo = $model->query($sql_str);
			}
			if (empty($area_vo) && !empty($region_lv3) && $region_lv3 != -1){
				$sql_str = 'select * from '.C("DB_PREFIX").'delivery_region where delivery_id = '.$id.' and region_ids like \'%,'.$region_lv3.',%\' limit 1';
				$area_vo = $model->query($sql_str);	
			}
			if (empty($area_vo) && !empty($region_lv2) && $region_lv2 != -1){
				$sql_str = 'select * from '.C("DB_PREFIX").'delivery_region where delivery_id = '.$id.' and region_ids like \'%,'.$region_lv2.',%\' limit 1';
				$area_vo = $model->query($sql_str);	
			}			
			/*
			if (empty($area_vo) && !empty($region_lv1) && $region_lv4 != -1){
				$sql_str = 'select * from '.C("DB_PREFIX").'freight_mode_area where freight_mode_id = '.$id.' and areaid_group like \'%,'.$region_lv1.',%\' limit 1';
				$area_vo = $model->find($sql_str);				
			}
			*/
			
			$area_vo = $area_vo[0];
			
			if (empty($area_vo)){//如果都没有找到的话
				if ($vo['allow_default'] == 0){//allow_default 0:启用缺省地址；1：禁用缺省地址
					$type2 = true;
				}else{
					$vo['freight_fee'] = 0;
				}
			}else{
				$type2 = true;
				
				$vo['first_price'] = $area_vo['first_price'];
				$vo['continue_price'] = $area_vo['continue_price'];
				
				$vo['allow_cod'] = $area_vo['allow_cod'];//0:不支持货到付款；1：支持货到付款
			}
		}
		
		if ($vo['type'] == 0 || $type2){
			if ($weight > $vo['first_weight'] && $vo['continue_weight'] != 0){
	  			$vo['freight_fee'] =  $vo['first_price'] + ceil(($weight - $vo['first_weight'])/$vo['continue_weight']) * $vo['continue_price'];
			}else{
	  			$vo['freight_fee'] =  $vo['first_price'];
			}			
		}
		
		//0:不支持物流保价；1：支持物流保价
		if ($vo['protect'] == 1){
			$vo['protect_fee'] = $money * $vo['protect_radio'] / 100;
			
			if ($vo['protect_fee'] < $vo['min_protect_price']){//最低保价费
				$vo['protect_fee'] = $vo['min_protect_price'];
			}
		}else{
			$vo['protect_fee'] = 0;
		}
		
		echo json_encode($vo);
	}		
	
}
?>