<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\modules\customer\controllers;

use Yii;
use home\models\Area;
use home\controllers\Controller;
use home\modules\customer\models\District;
use home\modules\customer\models\DistrictLink;

/**
 * 客户所属区域控制器
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class DistrictController extends Controller
{
 	public function actions()
 	{
		$actions = parent::actions();
		unset($actions['delete']);
		$actions['create']['layout'] = '@home/views/layouts/modal.php';
		$actions['view']['layout']   = '@home/views/layouts/modal.php';
		$actions['update']['layout'] = '@home/views/layouts/modal.php';
		return $actions;
	}

//=======================================客户列表=======================================//
	/**
	 *  查找出负责人负责区域所有的省份，以及关联的市，区
	 */
	public function actionSelectCustomer()
	{
		$json = [
			'data' => '',
			'status' => 0
		];

		//判断是否为超级管理员，是否需要进行区域验证
		if (!Yii::$app->session->get('isSuperAdmin')) {
			$customerAddress = District::getCustomerAddress();
		}

		$request = Yii::$app->request;
		$type = $request->get('type');     //值为1为编辑客户    0为新增客户
		$province_id['area_id'] = (int)$request->get('province_id');   //编辑时传过来的省ID
		$city_id['area_id'] = (int)$request->get('city_id');           //编辑时传过来的市ID
		$area_id['area_id'] = (int)$request->get('area_id');           //编辑时传过来的区ID

		//查询出当前负责区域的所有的省份
		if (empty($customerAddress)) {
			$allProvince = Area::find()->where(['pid' => 0])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allProvince = Area::find()->where(['in', 'area_id' , $customerAddress['province']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$provinceOneId = $allProvince['0'];     //获得排序第一位的省份
		$provinceId = empty($type)?$provinceOneId : $province_id;    //判断为编辑时调用传过来的值，否则调用查出来的

		//查询出当前负责区域的所有的城市
		if (empty($customerAddress)) {
			$allCity = Area::find()->where(['pid'=> $provinceId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allCity = Area::find()->where(['in', 'area_id' , $customerAddress['city']['n']])->orWhere(['in', 'pid' , $customerAddress['city']['y']])->andWhere(['pid'=> $provinceId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$cityOneId = $allCity['0'];   //查询排序第一位的省份下面排序第一的城市
		if ( !empty($type) && !empty($city_id) ) {
			$cityId = $city_id;
		} else {
			$cityId = $cityOneId;
		}

		//查询出当前负责区域的所有区
		if (empty($customerAddress)) {
			$allArea = Area::find()->where(['pid'=> $cityId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allArea = Area::find()->where(['in', 'area_id' , $customerAddress['area']['n']])->orWhere(['in', 'pid' , $customerAddress['area']['y']])->andWhere(['pid'=> $cityId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$areaOneId = $allArea['0'];    //查询排序第一位的城市下面排序第一的区域
		if (!empty($type) && !empty($area_id)) {
			$areaId = $area_id;
		} else {
			$areaId = $areaOneId;
		}

		//省份
		$data = "<td><select class='form-control' id='province' name='Customer[province_id]' style='width:83px;float:left' >";
		foreach ($allProvince as $k => $v) {
			if($v['area_id'] == $provinceId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select>";

		//城市
		$data .= "<select class='form-control' id='city' name='Customer[city_id]' style='width:83px;float:left' >";
		foreach ($allCity as $k => $v) {
			if($v['area_id'] == $cityId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select>";

		//区域
		$data .= "<select class='form-control' id='area' name='Customer[area_id]' style='width:83px;float:left' >";
		foreach ($allArea as $k => $v) {
			if($v['area_id'] == $areaId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select></td>";

		$json = [
			'data' => $data,
			'status' => 1
		];
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		return $json;
	}

	/**
	*  当省份发生变化时，查找出对应省份下面所有负责的的城市
	*/
	public function actionSelectCity()
	{
		$json = [
			'data' => '',
			'status' => 0
		];
		$city = [];
		$request = Yii::$app->request;
        $id = (int) $request->get('id');
		//$title = $request->get('title');   //为后面合并预留字段

		if (!Yii::$app->session->get('isSuperAdmin')) {  //判断是否为超级管理员
			$customerAddress = District::getCustomerAddress();
		}

		if (empty($customerAddress)) {
			$city = Area::find()->where(['pid'=> $id])->asArray()->all();
		} else {
			$city = Area::find()->where(['in', 'area_id' , $customerAddress['city']['n']])->orWhere(['in', 'pid' , $customerAddress['city']['y']])->andWhere(['pid'=> $id])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}

		$data = "";
		foreach ($city as $k => $v) {
			$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
		}

		$json = [
			'data' => $data,
			'status' => 1
		];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $json;
	}

	/**
	*  当城市发生变化时，查找出对应城市下面所有负责的的区
	*/
	public function actionSelectArea()
	{
		$json = [
			'data' => '',
			'status' => 0
		];
		$area = [];
        $id = (int) Yii::$app->request->get('id');
		//$title = Yii::$app->request->get('title');   //为后面合并预留字段

		if (!Yii::$app->session->get('isSuperAdmin')) {  //判断是否为超级管理员
			$customerAddress = District::getCustomerAddress();
		}

		if (empty($customerAddress)) {
			$area = Area::find()->where(['pid'=> $id])->asArray()->all();
		} else {
			$area = Area::find()->where(['in', 'area_id' , $customerAddress['area']['n']])->orWhere(['in', 'pid' , $customerAddress['area']['y']])->andWhere(['pid'=> $id])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}

		$data = "";
		foreach ($area as $k => $v) {
			$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
		}
		$json = [
			'data' => $data,
			'status' => 1
		];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $json;
	}


//=======================================客户区域列表=======================================//

	/**
	 *  查找出负责区域所有的省份，以及关联的市，区
	 */
	public function actionSelectDistrict()
	{
		$json = [
			'data' => '',
			'status' => 0
		];
		$request = Yii::$app->request;
		$getId = (int)$request->get('id');
		$id = empty($getId) ? 0: $getId;
		$type = $request->get('type');     //值为1为编辑    没值为新增一行
		$province_id['area_id'] = (int)$request->get('province_id');   //传过来的省ID
		$city_id['area_id'] = (int)$request->get('city_id');           //传过来的市ID
		$area_id['area_id'] = (int)$request->get('area_id');           //传过来的区ID
		$DistrictId = (int)$request->get('district_id');               //当前select选择框的值

		$districtAddress = District::getDistrictAddress($DistrictId);

		//查询出当前负责区域的省
		if (empty($districtAddress)) {
			$allProvince = Area::find()->where(['pid' => 0])->orderBy(['area_id' => SORT_ASC])->asArray()->all();    //查询所有的省份
		} else {
			$allProvince = Area::find()->where(['in', 'area_id' , $districtAddress['province']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();    //查询所有的省份
		}
		$provinceOneId = $allProvince['0'];     //查询排序第一位的省份
		$provinceId = empty($type)?$provinceOneId : $province_id;    //当传值不为空的时候优先传值

		//查询出当前负责区域的市
		if (empty($districtAddress)) {
			$allCity = Area::find()->where(['pid'=> $provinceId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allCity = Area::find()->where(['in', 'area_id' , $districtAddress['city']['n']])->orWhere(['in', 'pid' , $districtAddress['city']['y']])->andWhere(['pid'=> $provinceId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$cityOneId = $allCity['0'];   //查询排序第一位的省份下面排序第一的城市
		if (!empty($type) && !empty($city_id['area_id'])) {
			$cityId = $city_id;
		} else {
			$cityId = $cityOneId;
		}
		//查询出当前负责区域的区
		if (empty($districtAddress)) {
			$allArea = Area::find()->where(['pid'=> $cityId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allArea = Area::find()->where(['in', 'area_id' , $districtAddress['area']['n']])->orWhere(['in', 'pid' , $districtAddress['area']['y']])->andWhere(['pid'=> $cityId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$areaOneId = $allArea['0'];    //查询排序第一位的城市下面排序第一的区域
		if (!empty($type) && !empty($area_id['area_id'])) {
			$areaId = $area_id;
		} else {
			$areaId = $areaOneId;
		}

		//省份
		$data = "<tr id='{$id}'><td><select class='form-control' id='province' name='district[" . $id . "][province_id]' style='width:130px;float:left' >";
		foreach ($allProvince as $k => $v) {
			if($v['area_id'] == $provinceId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select>";

		//城市
		$data .= "<select class='form-control' id='city' name='district[" . $id . "][city_id]' style='width:130px;float:left' >";
		if (!empty($city_id['area_id']) && !empty($type)) {      //编辑状态且传值部位空
			$data .= "<option value='0'>全部</option>";
			foreach ($allCity as $k => $v) {
				if($v['area_id'] == $cityId['area_id']) {
					$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
				} else {
					$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
				}
			}
		} else {
			$data .= "<option selected='selected' value='0'>全部</option>";
			foreach ($allCity as $k => $v) {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select>";

		//区域
		$data .= "<select class='form-control' id='area' name='district[" . $id . "][area_id]' style='width:130px;float:left' >";
		if (!empty($area_id['area_id']) && !empty($type)) {   //编辑状态且传值部位空
			$data .= "<option value='0'>全部</option>";
			foreach ($allArea as $k => $v) {
				if($v['area_id'] == $areaId['area_id']) {
					$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
				} else {
					$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
				}
			}
		} else {
			$data .= "<option selected='selected' value='0'>全部</option>";
//			foreach ($allArea as $k => $v) {
//				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
//			}
		}
		$data .= "</select></td>";

		$data .= "<td><a href='javascript:;' class='delete-district' id='new'>删除</a></td></tr>";
		$json = [
			'data' => $data,
			'status' => 1
		];
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		return $json;
	}

	/**
	 *  查找出客户区域所有的市
	 */
	public function actionDistrictCity()
	{
		$json = [
			'data' => '',
			'status' => 0
		];
		$city = [];
		$request = Yii::$app->request;
		$id = (int) $request->get('id');
		$title = $request->get('title');
		$DistrictId = (int)$request->get('district_id');
		$customerAddress = District::getDistrictAddress($DistrictId);

		if (empty($customerAddress)) {
			$city = Area::find()->where(['pid'=> $id])->asArray()->all();
		} else {
			$city = Area::find()->where(['in', 'area_id' , $customerAddress['city']['n']])->orWhere(['in', 'pid' , $customerAddress['city']['y']])->andWhere(['pid'=> $id])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}

		$data = "<option value='0'>全部</option>";
		foreach ($city as $k => $v) {
			$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
		}

		$json = [
			'data' => $data,
			'status' => 1
		];
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		return $json;
	}

	/**
	 *  查找出客户区域所有的区
	 */
	public function actionDistrictArea()
	{
		$json = [
			'data' => '',
			'status' => 0
		];
		$area = [];
		$request = Yii::$app->request;
		$id = (int) $request->get('id');
		$title = $request->get('title');
		$DistrictId = (int)$request->get('district_id');

		$customerAddress = District::getDistrictAddress($DistrictId);

		if (empty($customerAddress)) {
			$area = Area::find()->where(['pid'=> $id])->asArray()->all();
		} else {
			$area = Area::find()->where(['in', 'area_id' , $customerAddress['area']['n']])->orWhere(['in', 'pid' , $customerAddress['area']['y']])->andWhere(['pid'=> $id])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}

		$data = "<option value='0'>全部</option>";
		foreach ($area as $k => $v) {
			$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
		}

		$json = [
			'data' => $data,
			'status' => 1
		];
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		return $json;
	}

	/**
	 * 删除客户区域
	 */
	public function actionDelete()
	{
		$model = new District();

		$id = Yii::$app->request->get('id');
		$ids = Yii::$app->request->post('delete');
		$session = Yii::$app->getSession();

		if (empty($id) && empty($ids)) {
			$session->setFlash('error', '要删除的对象不存在');
		} else {
			!empty($id) && $ids[] = $id;
			$success = true;
			$canDelete = true;
			foreach ($ids as $id) {
				$model = District::findOne(['district_id' => $id ]);

				if (empty($model)) {
					$session->setFlash('error', 'ID为' . $id . '的对象不存在');
					$success = false;
					break;
				}
				if ( !$model->delete() ) {
					$session->setFlash('error', 'ID为' . $id . '的对象删除失败');
					$success = false;
					break;
				}
				DistrictLink::deleteAll('district_id = :district_id', [':district_id' => $id]);
			}
			if ($canDelete && $success) {
				$session->setFlash('success', '删除成功');
			}
		}
		return $this->redirect(['index']);
	}




	public function actionSelectOpportunity()
	{
		$json = [
			'data' => '',
			'status' => 0
		];

		//判断是否为超级管理员，是否需要进行区域验证
		if (!Yii::$app->session->get('isSuperAdmin')) {
			$customerAddress = District::getCustomerAddress();
		}

		$request = Yii::$app->request;
		$type = $request->get('type');     //值为1为编辑客户    0为新增客户
		$province_id['area_id'] = (int)$request->get('province_id');   //编辑时传过来的省ID
		$city_id['area_id'] = (int)$request->get('city_id');           //编辑时传过来的市ID
		$area_id['area_id'] = (int)$request->get('area_id');           //编辑时传过来的区ID

		//查询出当前负责区域的所有的省份
		if (empty($customerAddress)) {
			$allProvince = Area::find()->where(['pid' => 0])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allProvince = Area::find()->where(['in', 'area_id' , $customerAddress['province']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$provinceOneId = $allProvince['0'];     //获得排序第一位的省份
		$provinceId = empty($type)?$provinceOneId : $province_id;    //判断为编辑时调用传过来的值，否则调用查出来的

		//查询出当前负责区域的所有的城市
		if (empty($customerAddress)) {
			$allCity = Area::find()->where(['pid'=> $provinceId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allCity = Area::find()->where(['in', 'area_id' , $customerAddress['city']['n']])->orWhere(['in', 'pid' , $customerAddress['city']['y']])->andWhere(['pid'=> $provinceId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$cityOneId = $allCity['0'];   //查询排序第一位的省份下面排序第一的城市
		if ( !empty($type) && !empty($city_id) ) {
			$cityId = $city_id;
		} else {
			$cityId = $cityOneId;
		}

		//查询出当前负责区域的所有区
		if (empty($customerAddress)) {
			$allArea = Area::find()->where(['pid'=> $cityId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		} else {
			$allArea = Area::find()->where(['in', 'area_id' , $customerAddress['area']['n']])->orWhere(['in', 'pid' , $customerAddress['area']['y']])->andWhere(['pid'=> $cityId['area_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
		}
		$areaOneId = $allArea['0'];    //查询排序第一位的城市下面排序第一的区域
		if (!empty($type) && !empty($area_id)) {
			$areaId = $area_id;
		} else {
			$areaId = $areaOneId;
		}

		//省份
		$data = "<td><select class='form-control' id='province' name='Opportunity[province_id]' style='width:95px;float:left' >";
		foreach ($allProvince as $k => $v) {
			if($v['area_id'] == $provinceId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select>";

		//城市
		$data .= "<select class='form-control' id='city' name='Opportunity[city_id]' style='width:95px;float:left' >";
		foreach ($allCity as $k => $v) {
			if($v['area_id'] == $cityId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select>";

		//区域
		$data .= "<select class='form-control' id='area' name='Opportunity[area_id]' style='width:95px;float:left' >";
		foreach ($allArea as $k => $v) {
			if($v['area_id'] == $areaId['area_id']) {
				$data .= "<option selected='selected' value='{$v['area_id']}'>{$v['title']}</option>";
			} else {
				$data .= "<option value='{$v['area_id']}'>{$v['title']}</option>";
			}
		}
		$data .= "</select></td>";

		$json = [
			'data' => $data,
			'status' => 1
		];
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		return $json;
	}
	
}
