<?php
	
	namespace app\api\controller;
	
	use app\common\model\device\Device;
	use app\common\model\geo\City;
	use app\common\model\geo\County;
	use app\common\model\geo\Group;
	use app\common\model\geo\Province;
	use app\common\model\geo\Town;
	use app\common\model\geo\Village;
	use app\common\model\land\Land;
	use app\common\model\land\LandProduct;
	use app\common\model\land\Product;
	use app\common\model\product\ProductDevice;
	use think\facade\Db;
	use think\response\Json;
	
	class LandController extends BaseApiController
	{
		//土地列表
		public function list(): Json
		{
			$params = $this->request->get(['page_no','page_size','keyword']);
			$pageNo = empty($params['page_no']) ? 1 : $params['page_no'];
			$pageSize = empty($params['page_size']) ? 6 : $params['page_size'];
			$where = [
				['user_id','=',$this->userId]
			];
			if(!empty($params['keyword'])){
				$where[] = ['title','like','%'.$params['keyword'].'%'];
			}
			$data = Land::where($where)->page($pageNo,$pageSize)->order('create_time desc')->select()->each(function($item){
				$item['pic'] = json_decode($item['pic']);
				return $item;
			})->toArray();
			return $this->success('请求成功',$data);
		}
		
		//土地详情
		public function detail(): Json
		{
			$params = $this->request->get(['land_id']);
			if(empty($params['land_id'])){
				return $this->fail('缺少必要参数');
			}
			$data = Land::where('id',$params['land_id'])->findOrEmpty();
			if($data->isEmpty()){
				return $this->fail('土地信息不存在');
			}
			if($data['user_id'] != $this->userId){
				return $this->fail('土地信息与用户信息不匹配');
			}
			$data['pic'] = json_decode($data['pic'],true);
			return $this->success('请求成功',$data->toArray());
		}
		
		//添加土地
		public function add(): Json
		{
			//获取参数并验证
			$fields = ['title','area','province_code','city_code','county_code','address','master_name','master_phone','pic', 'longitude', 'latitude'];
			$params = $this->request->post($fields);
			foreach($fields as $v){
				if(!isset($params[$v]) || $params[$v] == ''){
					return $this->fail('缺少必要参数');
				}
			}
			//验证土地是否存在
			$land = Land::where('user_id',$this->userId)->where('title',$params['title'])->findOrEmpty();
			if(!$land->isEmpty()){
				return $this->fail('土地名称已存在');
			}
			//获取省市县镇村组名称
			$province = Province::field('province_name')->where('province_code',$params['province_code'])->findOrEmpty();
			if($province->isEmpty()){
				return $this->fail('省份编码错误');
			}
			$city = City::field('city_name')->where('province_code',$params['province_code'])->where('city_code',$params['city_code'])->findOrEmpty();
			if($city->isEmpty()){
				return $this->fail('城市编码错误');
			}
			$county = County::field('county_name')->where('city_code',$params['city_code'])->where('county_code',$params['county_code'])->findOrEmpty();
			if($county->isEmpty()){
				return $this->fail('区县编码错误');
			}
			//验证土地图片字段是否是json数组
			$pic = json_decode($params['pic'],true);
			if(empty($pic)){
				return $this->fail('图片数据格式错误');
			}
			//创建数据
			$landRes = Land::create([
				'user_id' => $this->userId,
				'title' => $params['title'],
				'total_area' => $params['area'],
				'residual_area' => $params['area'],
				'province_code' => $params['province_code'],
				'province_name' => $province['province_name'],
				'city_code' => $params['city_code'],
				'city_name' => $city['city_name'],
				'county_code' => $params['county_code'],
				'county_name' => $county['county_name'],
				'address' => $params['address'],
				'master_name' => $params['master_name'],
				'master_phone' => $params['master_phone'],
				'longitude' => floatval($params['longitude']),
				'latitude' => floatval($params['latitude']),
				'pic' => $params['pic'],
				'create_time' => time(),
				'update_time' => time(),
			]);
			return $landRes->id ? $this->success('土地添加成功') : $this->fail('土地添加失败');
		}
		
		//产品列表
		public function product(): Json
		{
			$data = Product::field('id as product_id,code,name')->where('status',1)->where('user_id', $this->userId)->select()->toArray();
			$result = [];
			foreach ($data as $k=>$v) {
				$productDevice = ProductDevice::where('product_id',$v['product_id'])->select()->toArray();
				if(!empty($productDevice)){
					$result[] = $v;
				}
			}
			return $this->success('请求成功',$result);
		}
		
		//绑定产品
		public function bind(): Json
		{
			$params = $this->request->post(['land_id','product_id']);
			if(empty($params['land_id']) || empty($params['product_id'])){
				return $this->fail('缺少必要参数');
			}
			$land = Land::where('id',$params['land_id'])->findOrEmpty();
			if($land->isEmpty()){
				return $this->fail('土地信息错误');
			}
			$landProduct = LandProduct::where('land_id',$params['land_id'])->findOrEmpty();
			if(!$landProduct->isEmpty()){
				return $this->fail('当前土地已绑定其他产品');
			}
			$product = Product::where('id',$params['product_id'])->findOrEmpty();
			if($product->isEmpty()){
				return $this->fail('产品信息错误');
			}
			$productDevice = ProductDevice::where('product_id',$params['product_id'])->column('device_id');
			if(empty($productDevice)){
				return $this->fail('该产品没有绑定设备，请先给该产品绑定设备');
			}
			$productLand = LandProduct::where('product_id',$params['product_id'])->findOrEmpty();
			if(!$productLand->isEmpty()){
				return $this->fail('该产品已被其他土地绑定');
			}
			//创建数据
			Db::transaction(function()use($land,$product,$productDevice) {
				LandProduct::create([
					'land_id' => $land['id'],
					'product_id' => $product['id'],
					'create_time' => time(),
					'update_time' => time(),
				]);
				Product::where('id',$product['id'])->update([
					'user_id' => $land['user_id'],
					'status' => 2,
					'update_time' => time(),
				]);
				Device::where('id','in',$productDevice)->update([
					'user_id' => $land['user_id'],
					'update_time' => time()
				]);
			});
			return $this->success('绑定成功');
		}
	}