<?php
namespace Smi\Controller;

use \Think\Controller;
use \Think\Log;

class DadaController extends BaseController
{
	protected $dada;// 达达配送实例
	protected $business_id;// 商户id

	public function __construct()
	{
		parent::__construct();
		$this->business_id = session('admin_id');
	}

	/**
	 * [get_dada_ie 获取达达配送实例]
	 * @AuthorHTL
	 * @DateTime  2018-03-28T10:24:56+0800
	 * @return    [type]                   [description]
	 */
	private function get_dada_ie()
	{
		// 多门店-主账号business_id   主账号绑定app_key  app_secret  source_id
		$parent_id = M('admin')->where(array('id' => $this->business_id))->getField('parent_id');
		if (empty($parent_id)) {
			$config_p_id = $this->business_id;// 主门店id
		} else {
			$config_p_id = $this->parent_id;// 主门店id
		}

		$dada_config = M('dada_business')->where(array('admin_id' => $config_p_id))->field('id, source_id, app_key, app_secret')->find();

		if (empty($dada_config) && !empty($parent_id)) {
			echo '<script>alert("请联系主门店后台，并添加达达配置参数");location.go(-1);</script>';die;
		} else if (empty($dada_config) && empty($parent_id)) {
			// 前去填达达配送配置信息
			echo '<script>location.href="'.U('/Smi/Dada/config').'"</script>';die;
		} else {
			$this->dada = new \Common\Controller\DadaController($config_p_id);
		}
	}

	/**
	 * [shopDetail 商户详情（多门店子账号不可查看）]
	 * @AuthorHTL
	 * @DateTime  2018-03-27T17:57:54+0800
	 * @return    [type]                   [description]
	 */
	public function BusinessDetail()
	{ 
		// 获取达达配送实例
		$this->get_dada_ie();
		// 获取商户余额（运费余额/红包余额）
		$balance = $this->dada->balanceQuery(array('category' => 3));// 查询运费账户类型（1：运费账户；2：红包账户，3：所有），默认查询运费账户余额

		$this->assign('balance', $balance);
		$this->display();
	}

	/**
	 * [shopAdd 门店详情-自动添加/更新门店信息]
	 * @return [type] [description]
	 */
	public function shopDetail()
	{
		// 获取达达配送实例
		$this->get_dada_ie();

		$business_info = M('admin')->where(array('id' => $this->business_id))->field('id, username, business_phone, business_name, business_address, dada_origin_shop_id, lnglat')->find();

		$lnglat = split(',', $business_info['lnglat']);
	    // 正则匹配门店地址
	    $matchs = array();
	    $address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)([\x7f-\xff_a-zA-Z0-9]+)$/';
	    preg_match($address_preg, $business_info['business_address'], $matchs);

	    if ($this->dada->commonUrl == $this->dada->url) {// 线上环境
	    	if (empty($business_info['dada_origin_shop_id']) || $business_info['dada_origin_shop_id'] == $this->dada->shop_no) {// 自动添加门店信息
		        $dada_return = $this->dada->shopAdd(
		                array(
		                    array(
		                        'station_name' => $business_info['business_name'],
		                        'business' => 5,// 其他业务类型
		                        'city_name' => split('市', $matchs[2])[0],
		                        'area_name' => $matchs[3],
		                        'station_address' => $matchs[4],
		                        'lng' => $lnglat[0],
		                        'lat' => $lnglat[1],
		                        'contact_name' => $business_info['username'],
		                        'phone' => $business_info['business_phone'],
		                        'status' => 1
		                        // 'username' => $business_info['business_phone'],
		                        // 'password' => $business_info['business_phone']
		                    )
		                )
		            );

		        if ($this->dada->errCode == 0) {
		            M('admin')->where(array('id' => $this->business_id))->setField('dada_origin_shop_id', $dada_return['successList'][0]['origin_shop_id']);
		        } 
			} else { // 更新门店信息
				$dada_return = $this->dada->shopUpdate(
		                array(
		                    	'origin_shop_id' => $business_info['dada_origin_shop_id'],
		                        'station_name' => $business_info['business_name'],
		                        // 'business' => 5,// 其他业务类型
		                        'city_name' => split('市', $matchs[2])[0],
		                        'area_name' => $matchs[3],
		                        'station_address' => $matchs[4],
		                        'lng' => $lnglat[0],
		                        'lat' => $lnglat[1],
		                        'contact_name' => $business_info['username'],
		                        'phone' => $business_info['business_phone']
		                )
		            );
			}
			
			Log::record('Date:'.date('Y-m-d H:i:s').'Log information：'.$this->dada->errMsg);	
	    } else {// 测试环境
	    	M('admin')->where(array('id' => $this->business_id))->setField('dada_origin_shop_id', $this->dada->shop_no);
	    }
		
		
		// 查询门店信息
	    if ($this->dada->commonUrl == $this->dada->url) {// 线上环境
	    	$origin_shop_id = M('admin')->where(array('id' => $this->business_id))->getField('dada_origin_shop_id');
	    } else {// 测试环境
	    	$origin_shop_id = $this->dada->shop_no;
	    }
		
		$dada_return = $this->dada->shopDetail(array('origin_shop_id' => $origin_shop_id));

		$this->assign('info', $dada_return);
		$this->display();
	}

	/**
	 * [config 更新达达配置信息]
	 * @AuthorHTL
	 * @DateTime  2018-03-27T18:36:09+0800
	 * @return    [type]                   [description]
	 */
	public function config()
	{
		// 多门店-主账号business_id   主账号绑定app_key  app_secret  source_id
		$parent_id = M('admin')->where(array('id' => $this->business_id))->getField('parent_id');
		if (empty($parent_id)) {
			$config_p_id = $this->business_id;// 主门店id
		} else {
			$config_p_id = $this->parent_id;// 主门店id
		}
		$dada_config = M('dada_business')->where(array('admin_id' => $config_p_id))->field('id, source_id, app_key, app_secret')->find();

		$data = I('post.');
		if (!empty($data)) {

			if (!empty($dada_config)) {
				$this->error('Do not repeat configuration parameters');die;
			}

			if (empty($data['app_key'])) {
				$this->error('App_key cannot be empty');die;
			}
			if (empty($data['app_secret'])) {
				$this->error('app_secret cannot be empty');die;
			}
			if (empty($data['source_id'])) {
				$this->error('source_id cannot be empty');die;
			}

			$result = M('dada_business')
						->add(
							array(
								'admin_id' => $this->business_id,
								'app_key' => $data['app_key'],
								'app_secret' => $data['app_secret'],
								'source_id' => $data['source_id'],
							)
						);
			if ($result) {
				$this->success('Add a success！');die;
			} else {
				$this->error('Add failure！');die;
			}
		}

		$this->assign('config', $dada_config);
		$this->display();
	}
}