<?php
namespace app\mainapp\controller;

use think\facade\Session;
use app\mainapp\BaseController;

use app\common\model\Param as ParamModel;
use app\common\model\Agent as AgentModel;
use app\common\model\AgentForm as AgentFormModel;

class Agent extends BaseController
{
	
	
	// 申请代理门店
	public function pageForm()
	{
		$param = ParamModel::where(1)->find();
		page_result(0, "", array(
			'param'		=> $param
		));
	}
	
	public function regAgent()
	{
		$realname = input('realname/s', "");
		$mobile = input('mobile/s', "");
		$address = input('address/s', "");
		$idcard = input('idcard/s', "");
		$recommender = input('recommender/s', "");
		if ( empty($realname) || empty($mobile) || empty($address) || empty($idcard) ){
			page_result(1, "姓名、手机号、当前住址、身份证号均不能为空。");
		}
		$form = new AgentFormModel;
		$form->save([
			'realname'			=> $realname,
			'mobile'			=> $mobile,
			'address'			=> $address,
			'idcard'			=> $idcard,
			'recommender'		=> $recommender,
			'status'			=> 1,
			'remark'			=> "",
			'createtime'		=> time()
		]);
		page_result(0, "", array());
	}
	


	// 代理门店详情
	public function getAgent()
	{
		$agentid = input('agentid/d', 0);
		$agent = AgentModel::where('id','=',$agentid)
				// ->field("*, ROUND( (2 * $EARTH* ASIN(SQRT(POW(SIN($PI*(".$lat."-latitude)/360),2)+COS($PI*".$lat."/180)* COS(latitude * $PI/180)*POW(SIN($PI*(".$lng."-longitude)/360),2))))/1000, 2 ) as juli")
				->findOrEmpty();
		if ($agent->isEmpty()){
			page_result(1, "代理门店信息不存在");
		}
		page_result(0, "", array(
			'agent'		=> $agent
			));
	}
	
	 
	// 代理门店列表
	public function listAgent()
	{
		$psize = input('psize/d', 5);
		$map[] = ['status','=',1];
		
		$lng = input('lng/f', 0);
		$lat = input('lat/f', 0);
	
		$plist = AgentModel::where($map)
				->field("*, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-latitude*PI()/180)/2),2)+COS($lat*PI()/180)*COS(latitude*PI()/180)*POW(SIN(($lng*PI()/180-longitude*PI()/180)/2),2))), 2) as juli")
				->order(['juli'=>'asc','priority'=>'desc','id'=>'desc'])->limit($psize)->select();
		page_result(0, "", array(
			'plist' => $plist,
			'pstatus' => $psize > count($plist) ? 'noMore' : 'more'
			));
	}



}