Areasite.php备份231205 10.8 KB
<?php

namespace app\admin\controller\inspection;


use addons\inspection\library\QRcode;
use app\admin\model\inspection\Lnglat;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 巡检点管理
 *
 * @icon fa fa-circle-o
 */
class Areasite extends Backend
{
    
    /**
     * Area模型对象
     * @var \app\admin\model\inspection\Area
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inspection\Areasite();


        $tree = Tree::instance();
        $areaModel = new \app\admin\model\inspection\Area();
        $tree->init(collection($areaModel->order('weigh asc,id asc')->select())->toArray(), 'pid');
        $areadata = ['' => ['area_name' => '请选择巡检区域']];
        foreach ($tree->getTreeList($tree->getTreeArray(0), 'area_name') as $k => $v) {
            $areadata[$v['id']] = $v;
        }

        $this->view->assign("areaList", $areadata);
    }

    /**
     * 联动搜索
     */
    public function cxselect()
    {
        $list = $this->model->field('id as value, site_name as name')->select();
        $this->success('', null, $list);
    }

    /**
     * 添加
     */
    public function add()
    {
        $info = get_addon_info('address');
        if(empty($info)){
            $this->error('请到后台插件管理安装《地图位置(经纬度)选择插件》插件');
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if(!$this->is_reservoir($params['area_id'])){
                    $this->error('该区域不是水库区域');
                }
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                //$model = new \app\admin\model\inspection\Areasite();
                $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);
                    }
                    if($params['verify'] == 1){
                        if(empty($params['lng']) || empty($params['lat'])){
                            $this->error("请完善经纬度信息");
                        }
                        $params['lnglat'] = $params['lng'].",".$params['lat'];
                    }


                    $result = $this->model->allowField(true)->save($params);
                    if ($result > 0) {
                        $id = $this->model->id;
                        $qrCode = \addons\qrcode\library\Service::qrcode(['text'=>Request::instance()->domain() . "/api/inspection/project/getProjectByAreasite?id=".$id]);
                        $qrcodePath = ROOT_PATH . 'public/xj/qrcode/';
                        if (!is_dir($qrcodePath)) {
                                @mkdir($qrcodePath);
                        }
                        if (is_really_writable($qrcodePath)) {
                            $filename = date('YmdHis') . '.png';
                            $filePath = $qrcodePath . $filename;
                            $qrCode->writeFile($filePath);
                            Db::name('inspection_area_site')->where('id',$id)->update(['qrcode_src'=>'/xj/qrcode/'.$filename]);
                        }
                    }
                    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', ''));
        }

        $area_id = $this->request->param('area_id');
        $this->assign('area_id',$area_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if(!$this->is_reservoir($params['area_id'])){
                    $this->error('该区域不是水库区域');
                }
                $params = $this->preExcludeFields($params);
                $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 . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['verify'] == 1){
                        if(empty($params['lng']) || empty($params['lat'])){
                            $this->error("请完善经纬度信息");
                        }
                        $params['lnglat'] = $params['lng'].",".$params['lat'];
                    }

                    $result = $row->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 updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $lnglat = $row['lnglat'];
        $lnglatArr = explode(",",$lnglat);
        $row['lng'] = empty($lnglatArr[0])?'':$lnglatArr[0];
        $row['lat'] = empty($lnglatArr[1])?'':$lnglatArr[1];

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }




    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $area_id = $this->request->param('area_id',-1);
            if($area_id == -1){
                $_where = [];
            }else{
                //获取下级所有子部门ID
                $tree = Tree::instance();
                $areasiteModel = new \app\admin\model\inspection\Area();
                $tree->init(collection($areasiteModel->order('id asc')->select())->toArray(), 'pid');
                $area_ids = $tree->getChildrenIds($area_id);
                array_push($area_ids,$area_id);
                $_where = ['area_id'=>['in',$area_ids]];
            }
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取经纬度
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getlnglat(){
        $id = $this->request->param("id");
        $distance = $this->request->param("distance",0);
        $lnglatModel = new Lnglat();
        $lnglatInfo = $lnglatModel->where(['areasite_id'=>$id])->find();
        if($lnglatInfo){
            if($lnglatInfo['distance'] != $distance){
                $lnglatInfo->save(['distance'=>$distance]);
            }
        }else{
            $lnglatModel = new Lnglat();
            $lnglatModel->save([
                'areasite_id'=>$id,
                'distance'=>$distance
            ]);
        }
        $lnglatModel = new Lnglat();
        $lnglatInfo = $lnglatModel->where(['areasite_id'=>$id])->find();
        $this->success("请求成功","",$lnglatInfo);
    }

    public function ercode(){
        $id = $this->request->param("id");
        $value = Request::instance()->domain() . "/addons/inspection/index/lnglat?id=".$id;         //二维码内容
        //$value = Request::instance()->domain() . "/api/inspection/project/getProjectByAreasite?id=".$id;         //二维码内容
        $errorCorrectionLevel = 'H';  //容错级别
        $matrixPointSize = 20;      //生成图片大小
        $qr_path = 'assets/addons/inspection/qrcode/' . $id . '.png';

        QRcode::png($value, $qr_path, $errorCorrectionLevel, $matrixPointSize, 3);

        $this->assign('qrpath',Request::instance()->domain()."/".$qr_path);

        return $this->fetch();
    }
    //判断区域是否是水库
    public function is_reservoir($area_id){
        $reservoir_id = Db::name('inspection_area')->where('id',$area_id)->value('reservoir_id');
        return $reservoir_id;
    }
    //二维码页面
    public function qrcode(){
        $id = $id = $this->request->param("ids");
        $res = $this->model->get($id);
        $this->assign('qrpath',$res->qrcode_src);
        return $this->view->fetch();
    }

}