<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Shop_service {

	public $shopinfo;



	public function __construct(){
		$this->ci = &get_instance();
		$this->ci->load->model('shop_model');
		$this->ci->load->helper('discuz_helper');
	}




	public function formatListData($date = '', $level, $result){
		$this->ci->load->model('area_model','area');
		$arealist = $this->ci->area->getarea();
		$arealist[0] = '全部';
		$return = array();
		foreach($result as $row){
			$temp['name'] = $row['name'];
			$temp['pic'] = $row['pic'];
			$temp['sid'] = (string)$row['sid'];
			$temp['level'] = $level;
			$temp['category'] = $row['category'];
			$temp['shop_des'] = "[{$arealist[$row['aid']]}]".$row['shop_des'];
			$temp['date'] = !empty($date) ? $date : date('Y-m-d', $row['timestamp']);
			$return[] = $temp;
		}

		return $return;
	}


	public function getSid($result){
		$sids = array();
		foreach($result as $row){
			$sids[] = $row['sid'];
		}

		return $sids;
	}


	

	public function getData($timestamp, $offset, $pagesize,  $category = '', $aid = 0 ,$order = 'buy_num', $mode = 1){

		$level2_shop_num = $this->ci->shop_model->countLevel2ByDate($timestamp, $category);
	    $result = array();
		//有高级权益剩余
		
		if($level2_shop_num > $offset){		
		
			$result = $this->ci->shop_model->getLevel2List($timestamp, $offset, $pagesize,  $category, $aid, $order);
			$result = $this->formatListData(date('Y-m-d', $timestamp), '2', $result);
		}
		
		$level2_count = count($result); //当前已经取得的高级权益
		$level1_offset = $offset - $level2_shop_num > 0 ? $offset - $level2_shop_num : 0; //当前的普通权益偏移
		$level1_pagesize = $level2_count > 0 ? $pagesize - $level2_count : $pagesize; 
		

		$sids = '';
		//数量不足
		if($level2_count < $pagesize){

			$level1_result = $this->ci->shop_model->getLevel1List($timestamp, $level1_offset, $level1_pagesize, $category, $aid, $order);
			
			if(!$level1_result){
				$level1_result = array();
			}

			$level1_result = $this->formatListData(date('Y-m-d', $timestamp), '1', $level1_result);
			$result = array_merge($result,$level1_result);
		}

		$total_count = count($result); //总数

		if($total_count < 1){
			return array();
		}

		if($mode == 2){
			return $result;
		}

		//总数不足进入下一日取
		if($total_count < $pagesize){
			$next_day_result = $this->getData(strtotime('+1 day', $timestamp), 0, $pagesize - $total_count, $category ,  $aid, $order);
			$result = array_merge($result, $next_day_result);
		}

		return $result;


	}


	public function getList($page, $pagesize, $category = 0, $aid = 0 ,$order = 'buy_num', $mode = 1){

		$start_date = date('Y-m-d');
		
		$shop_num = $this->ci->shop_model->countShops($category, $aid);

		if($shop_num <= 0){
			return array();
		}
		

		//计算开始日期
		$offset  = ($page - 1) * $pagesize; //已经取得数据
		if($mode == 2 && $offset >= $shop_num){
			return array();
			
		}
		$offest_date = floor($offset/$shop_num); //偏移日期
		$now_offset = $offset % $shop_num;  //当前日期数据偏移
		$timestamp = strtotime('+'.$offest_date.' day', strtotime($start_date));
		$result = $this->getData($timestamp, $now_offset, $pagesize, $category, $aid, $order, $mode);
		return $result;

	}


	public function getLevel2List($page, $pagesize, $date = '', $category, $aid = 0, $order){

		$start = ($page - 1) * $pagesize;
		$timestamp = empty($date) ? '' : strtotime($date);
		$result  = $this->ci->shop_model->getLevel2List($timestamp , $start, $pagesize, $category, $aid, $order);
		return $this->formatListData('', 2, $result);


	}


	public function getShopList($page, $pagesize, $level, $category, $aid = 0, $order){
		$start = ($page - 1) * $pagesize;
		$result = $this->ci->shop_model->getShopList($start, $pagesize, $level, $category, $aid, $order);
		return $this->formatListData(date('Y-m-d'), $level, $result);
	}



	public function updateShopDate($date, $start_date, $end_date, $level2_des, $shop_id, $mode){

		$start_time = strtotime($start_date);
		$end_time = strtotime($end_date);

		$date_serialize['mode'] = $mode;
		$date_serialize['date'] = $date;
		
		$date_serialize = serialize($date_serialize);
		$this->ci->shop_model->updateBySid(
			array(
			'start_time' => $start_time, 
			'end_time' => $end_time, 
			'date' => $date_serialize,
			'level2_des' => $level2_des
			),
			$shop_id
		);

		if($mode == 1){
			$date_array = $this->day_to_time($start_date, $end_date, $date, 'timestamp');
		}else{
			$date_array = $this->week_to_time($start_date, $end_date, $date, 'timestamp');
		}
		
		if(empty($date_array)){
			return array('code' => 0, 'msg' => '合同期内没有高级权益生效的日子,请确定');
		}

		foreach($date_array as $timestamp){
			$insert['sid'] = $shop_id;
			$insert['timestamp'] = $timestamp;
			$insert_batch[] = $insert;
		}
		$this->ci->shop_model->deleteShopDate($shop_id);
		$this->ci->shop_model->insertDate($insert_batch);

		return true;
	}


	public function day_to_time($start_date, $end_date, $date, $date_format = 'date'){
		date_default_timezone_set('PRC');
		$start_time = strtotime($start_date);
		$end_time = strtotime($end_date);
		$start_day = date('Y-m', $start_time);
		$start_day = strtotime($start_day);

		$valid_date = array();

		while($start_day < $end_time){
			$year = date('Y', $start_day);
			$month = date('m', $start_day);
			foreach($date as $day){
				if(checkdate($month, $day, $year)){
					$timestamp = strtotime($year.'-'.$month.'-'.$day);

					if($timestamp < $start_time){
						continue;
					}

					if($timestamp > $end_time){
						continue;
					}

					if($date_format == 'timestamp'){
						$valid_date[] = $timestamp;
					}else{
						$valid_date[] = $year.'-'.$month.'-'.$day;
					}
					
				}
			}

			$start_day = strtotime('+1 month', $start_day);
		}

		return $valid_date;
	}

	public function week_to_time($start_date, $end_date, $weeks, $date_format = 'date'){
		date_default_timezone_set('PRC');
		$start_time = strtotime($start_date) - 3600*24;
		$end_time = strtotime($end_date);

		$en_week = array(1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday', 7 => 'Sunday');
		$valid_date = array();
		$week_last = 0;
		while ($start_time < $end_time) {
			foreach($weeks as $k){
				$week_last = strtotime('next '.$en_week[$k], $start_time);
				if($week_last > $end_time){
					continue;
				}

				if($date_format == 'timestamp'){
					$valid_date[] = $week_last;
				}else{
					$valid_date[] = date('Y-m-d', $week_last);
				}
			}
			$start_time = strtotime('+ 1 week', $start_time);
		}

		return $valid_date;
	}



	public function make_sauth($username, $password){
		$auth = urlencode(base64_encode(authcode($username."\t".$password."\t", 'ENCODE')));
		return $auth;
	}


	public function autoLogin($sauth = ''){
		$sauth = empty($sauth) ? $this->ci->input->post('sauth') : $sauth;
		$sauth = urldecode($sauth);
		$auth = authcode(base64_decode($sauth), 'DECODE');

		
		$auth =  explode("\t", $auth);
		if(count($auth) < 2){
			return false;
		}
		$this->ci->load->model('shop_model');
		list($sid, $password) = $auth;
		if($this->shopinfo = $this->ci->shop_model->login($sid, $password)){
			$this->id = $this->shopinfo['sid'];
			$this->level = $this->ci->shop_model->getLevelByDate($this->shopinfo['sid'], date('Y-m-d'));
			return true;
		}

		return false;
	}








}