Rainfall.php 6.4 KB
<?php

namespace app\admin\controller\reservoir\rain;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 水库降雨量
 *
 * @icon fa fa-circle-o
 */
class Rainfall extends Backend
{

    /**
     * Rainfall模型对象
     * @var \app\admin\model\reservoir\rain\Rainfall
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\reservoir\rain\Rainfall;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("rainfallWarningList", $this->model->getRainfallWarningList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['reservoirlist', 'equipment'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('equipment')->visible(['name']);
                $row->getRelation('reservoirlist')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        //有雨量计的水库
        $wh = [];
        $wh["b.type"] = ["=", "5"];//设备类型:1=水位计,2=渗流计,3=渗压计,4=GNSS,5=雨量计,6=位移检测,7=其他
        $equipment = Db::name("reservoir_list")->alias("a")
            ->join("reservoir_equipment b", "b.reservoir_id=a.id")
            ->where($wh)
            ->field("a.id,b.deviceId,CONCAT(b.name,b.deviceId) as name")
            ->select();
        //最近一周
        $date = [];
        for ($i = 6; $i >= 0; $i--) {
            $beginTime = mktime(00, 00, 00, date('m'), date('d') - $i, date('Y'));
            $endTime = mktime(23, 59, 59, date("m"), date("d") - $i, date("Y"));
            array_push($date, date("Y-m-d", $beginTime));
        }

        $rainfall_series = [];
        if (!empty($equipment)) {
            foreach ($equipment as $k => $v) {
                //最近7天最后一条数据
                $date_value = [];
                $now_date = strtotime(date("Y-m-d")) + 9 * 3600;//当天 08:00

                for ($i = 6; $i >= 0; $i--) {
                    $beginTime = mktime(00, 00, 00, date('m'), date('d') - $i, date('Y'));
                    $endTime = mktime(8, 59, 59, date("m"), date("d") - $i + 1, date("Y"));
//                    array_push($date, date("m/d", $beginTime));
                    if ($i == 0 && time() < $now_date) {
                        //当前时间在当日08:00前
                        $rr = 0;
                    } else {
                        $rr = "";
                        $wh = [];
                        $wh["reservoir_id"] = ["eq", $v['id']];
                        $wh["number"] = ["eq", $v['deviceId']];
                        $wh["createtime"] = ["between", [$beginTime, $endTime]];
                        $rr = Db::name("reservoir_rain_rainfall")->where($wh)->order("createtime desc")->value("total_rainfall");
                    }
                    array_push($date_value, $rr?$rr:"--");
                }
                $rainfall_series[] = [
                    'type' => "line",
                    "stack" => 'Total',
                    "name" => $v['name'],
                    'data' => $date_value,
                ];
            }
        }

        $this->assignconfig("equipment", array_column($equipment, "name"));
        $this->assignconfig("date", $date);
        $this->assignconfig("rainfall_series", $rainfall_series);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['createtime'] = time();
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}