<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class WaiyuController extends BaseController
{
	public function get_time_list()
	{	
		$list = M('time')->where(array('admin_id' => $this->data['business_id'], 'status' => 1))->select();

		if (empty($list)) {
			$this->ajaxReturn(['status' => -1, 'msg' => '没有可选择的时间']);die;
		}

		$now_time = time();// 当前时间

		foreach ($list as $k => &$v) {
			$v['time'] = date('Y-m-d').' '.$v['time'];
			$v['time'] = strtotime($v['time']);
		}

		$list = $this->sort_two_array($list, 'SORT_ASC', 'time');

		if ($list[0]['time'] - $list[0]['allow_time']*60 > $now_time) {#当天

		} else if ($list[0]['time'] - $list[0]['allow_time']*60 <= $now_time && $now_time < end($list)['time'] + end($list)['allow_time']*60) {
			foreach ($list as $key => $value) {
				if ($value['time'] - $value['allow_time'] <= $now_time && $now_time < $value['time'] + $value['allow_time']*60) {
					continue;
				} else {
					unset($list[$key]);
				}
			}
		} else if ($now_time >= end($list)['time'] + end($list)['allow_time']*60) {#明天
			foreach ($list as $key => &$value) {
				$list[$key]['time'] += 24*60*60;
			}
		} 

		$array = array();
		foreach ($list as $key => &$value) {
			$array[] = $value['time'];
		}

		$this->ajaxReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $array]);
	}

	// 冒泡, 从小到大排序
	private function maopao($arr)
	{
	    //一共是多少趟
	    for($i = count($arr)-1; $i>0; $i--){
	        $flag = 0;
	        //每一趟进行相邻两个数进行比较
	        for($j = 0; $j < $i; $j++){
	            if($arr[$j]>$arr[$j+1]){
	                $temp = $arr[$j];
	                $arr[$j] = $arr[$j+1];
	                $arr[$j+1] =$temp;
	                $flag = 1;
	            }
	        }
	        if($flag == 0){
	            break;
	        }
	    }
	    return $arr;
	}

	// 二维数组排序
	private function sort_two_array($array, $direction = 'SORT_DESC', $field = '')
	{	  	  
		$sort = array(  
		        'direction' => $direction, //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序  
		        'field'     => $field,       //排序字段  
		);  
		$arrSort = array();  
		foreach($array AS $uniqid => $row){  
		    foreach($row AS $key=>$value){  
		        $arrSort[$key][$uniqid] = $value;  
		    }  
		}  
		if($sort['direction']){  
		    array_multisort($arrSort[$sort['field']], constant($sort['direction']), $array);  
		}  
		return $array;
	}
}