<?php

namespace app\api\controller\dataview;

use app\api\controller\BaseApiController;
use app\common\model\device\Device;
use app\common\model\device\MonitorAlarm;
use app\common\model\device\MonitorThreshold;
use app\common\model\land\Land;
use app\common\model\land\LandPlant;
use app\common\model\land\Product;
use app\common\model\LandCollection;
use think\facade\Db;
use think\exception\ValidateException;

class LandController extends BaseApiController
{

    public array $notNeedLogin = ['plantProductCount',
                                'landCollectionList',
                                'landMonitorAlarmHistory',
                                'productList',
                                'landList',
                                'centralCount',
                                'areaPlantTypeCount',
                                'monitorInfo',
                                'deviceCount'
                               ];

    public $areaCode;
    public $streetCode;

    public function initialize()
    {
        parent::initialize();
        $this->areaCode = $this->request->param('areaCode', '');
        $this->streetCode = $this->request->param('streetCode', '');
        if ($this->areaCode == '') {
            throw new ValidateException('未获取到位置信息');
        }
    }


    // 溯源产品统计
    public function plantProductCount()
    {
        $list = LandPlant::alias('lp')->join('land l', 'l.id=lp.land_id')->field('lp.kind,lp.qr_code')
            ->where(function ($query) {
                if ($this->streetCode != '') {
                    $query->where('l.town_code', $this->streetCode);
                } else {
                    $query->where('l.county_code', $this->areaCode);
                }
            })->limit(30)->select();
        return $this->success('成功', compact('list'));
    }

    // 智能预警数据
    public function landCollectionList()
    {
        // 先排序，再分组
        $subQuery = Db::name('land_collection')
                    ->order('id', 'desc')
                    ->buildSql();

        $list = Db::table($subQuery)->alias('lc')
            ->field('lc.*,l.title')
            ->join('land l', 'l.id=lc.land_id')
            ->where(function ($query) {
                if ($this->streetCode != '') {
                    $query->where('l.town_code', $this->streetCode);
                } else {
                    $query->where('l.county_code', $this->areaCode);
                }
            })->order('lc.id', 'desc')->group('l.id')->limit(30)->select();
        return $this->success('成功', compact('list'));
    }

    // 预警历史记录
    public function landMonitorAlarmHistory()
    {
        $landId = $this->request->get('land_id');
        // 最近7日
        $start = date('Y-m-d', strtotime('-6 day'));
        $end= date('Y-m-d H:i:s', time());
        $typeRow = ['soil_temperature', 'soil_moisture', 'soil_PH', 'soil_potassium_phosphate_nitrogen', 'wind_speed', 'ambient_temperature', 'ambient_humidity', 'carbon_dioxide'];
        $list = [];
        foreach ($typeRow as $type) {
            // 土壤磷酸钾-氮磷钾
            if ($type == 'soil_potassium_phosphate_nitrogen') {
                $alarmCount = MonitorAlarm::where('land_id', $landId)
                    ->whereIn('type', ['soil_potassium_phosphate_nitrogen',
                                            'soil_potassium_phosphate_phosphorus',
                                            'soil_potassium_phosphate_potassium'
                                            ])
                    ->count();

                $dataList = LandCollection::where('land_id', $landId)
                    ->field(['soil_potassium_phosphate_nitrogen',
                        'soil_potassium_phosphate_phosphorus',
                        'soil_potassium_phosphate_potassium', "STR_TO_DATE(create_time, 
                        '%Y-%m-%d') as day"])
                    ->whereBetweenTime('create_time', $start, $end)
                    ->group("STR_TO_DATE(create_time, '%Y-%m-%d')")
                    ->select();


                // 组装折线图数据
                $historyList = [];
                $timeRow = [];
                $valueRow = [];
                foreach ($dataList as $row) {
                    $timeRow[] = $row['day'];
                    unset($row['day']);
                    $valueRow[] = $row;
                }
                $historyList[]['time'] = $timeRow;
                $historyList[]['value'] = $valueRow;
            }  else {
                $alarmCount = MonitorAlarm::where('land_id', $landId)
                    ->where('type', $type)
                    ->count();

                $dataList = LandCollection::where('land_id', $landId)
                    ->field("$type,STR_TO_DATE(create_time, '%Y-%m-%d') as day")
                    ->whereBetweenTime('create_time', $start, $end)
                    ->group("STR_TO_DATE(create_time, '%Y-%m-%d')")
                    ->select()->toArray();

                // 组装折线图数据
                $historyList = [];
                $timeRow = [];
                $valueRow = [];
                foreach ($dataList as $row) {
                    $timeRow[] = $row['day'];
                    $valueRow[] = $row[$type];
                }
                $historyList[]['time'] = $timeRow;
                $historyList[]['value'] = $valueRow;
            }

            $list[$type] = compact('alarmCount', 'historyList');
        }

        return $this->success('成功', compact('list'));
    }

    // 土地列表
    public function landList()
    {
        $list = Land::alias('l')->field('l.*,d.video_url,d.id as device_id')->join('land_product lp', 'lp.land_id=l.id')
            ->join('product_device pd', 'lp.product_id=pd.product_id')
            ->join('device d', 'pd.device_id=d.id')
            ->where(function ($query) {
            if ($this->streetCode != '') {
                $query->where('l.town_code', $this->streetCode);
            } else {
                $query->where('l.county_code', $this->areaCode);
            }
        })->select();
        return $this->success('成功', compact('list'));
    }

    public function productList()
    {
        $list =  Product::alias('p')->field('p.*')
            ->join('land_product lp', 'p.id=lp.product_id')
            ->join('land l', 'lp.land_id=l.id')
            ->where(function ($query) {
                if ($this->streetCode != '') {
                    $query->where('l.town_code', $this->streetCode);
                } else {
                    $query->where('l.county_code', $this->areaCode);
                }
            })->select();
        return $this->success('成功', compact('list'));
    }

    public function centralCount()
    {

        $query = Land::alias('l')->where(function ($query) {
                    if ($this->streetCode != '') {
                        $query->where('l.town_code', $this->streetCode);
                    } else {
                        $query->where('l.county_code', $this->areaCode);
                    }
                });
        // 地块数量
        $landCount = $query->count();
        // 种植面积
        $totalArea = $query->sum('total_area');
        // 种植种类
        $plantCount = $query->join('land_plant lp', 'l.id = lp.land_id')->group('kind')->count();

        return $this->success('成功', compact('landCount', 'totalArea', 'plantCount'));
    }

    // 第二页 种植面积/种类
    public function areaPlantTypeCount()
    {
        $landId = $this->request->get('land_id');
        $query = Land::alias('l')->where('l.id', $landId);
        // 种植面积
        $totalArea = $query->value('total_area');
        // 种植种类
        $plantKindList = $query->field('lp.land_id,lp.kind')->join('land_plant lp', 'l.id = lp.land_id')->group('lp.kind')->select();
        return $this->success('成功', compact('totalArea', 'plantKindList'));
    }

    // 第二页 气象环境监测
    public function monitorInfo()
    {
        $landId = $this->request->get('land_id');
        // 气象信息
        $landCollection = LandCollection::where('land_id', $landId)->order('id', 'desc')->find();
        $monitorThreshold = MonitorThreshold::select()->toArray()[0];
        $monitorThreshold['ambient_air_pressure_max'] = 120;
        $monitorThreshold['ambient_air_pressure_min'] = 10;
        return $this->success('成功', compact('landCollection', 'monitorThreshold'));
    }

    // 监测设备数量统计
    public function  deviceCount()
    {
        $landId = $this->request->get('land_id');
        $total = Land::alias('l')
            ->join('land_product lp', 'l.id=lp.land_id')
            ->join('product_device pd', 'lp.product_id=pd.product_id')
            ->join('device d', 'pd.device_id=d.id')
            ->where('l.id', $landId)
            ->count();

        $online = Land::alias('l')
            ->join('land_product lp', 'l.id=lp.land_id')
            ->join('product_device pd', 'lp.product_id=pd.product_id')
            ->join('device d', 'pd.device_id=d.id')
            ->where('l.id', $landId)
             ->where('d.is_online', 1)->count();

        $offline = Land::alias('l')
            ->join('land_product lp', 'l.id=lp.land_id')
            ->join('product_device pd', 'lp.product_id=pd.product_id')
            ->join('device d', 'pd.device_id=d.id')
            ->where('l.id', $landId)
            ->where('d.is_online', 2)->count();

        return $this->success('成功', compact('total', 'online', 'offline'));

    }
}