Article.php 11.4 KB
<?php

namespace app\admin\controller\notices;

use app\admin\model\inspection\Staff;
use app\admin\model\notices\Noticesnormal;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\library\Getui;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 公告管理
 *
 * @icon fa fa-circle-o
 */
class Article extends Backend
{
    
    /**
     * Article模型对象
     * @var \app\admin\model\notices\Article
     */
    protected $model = null;

    protected $searchFields = 'id,title,depart.depart_name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\notices\Article;
        $this->view->assign("typeDataList", $this->model->getTypeDataList());
    }

    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('depart')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('depart')->visible(['depart_name']);
            }

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

            return json($result);
        }
        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;
                }

                //验证通知字段
                if (!empty($params['type_data'])){
                    if ($params['type_data'] == 2){
                        if (empty($params['type_value2'])){
                            $this->error('请选择要通知的群组');
                        }else{
                            $params['type_value'] = $params['type_value2'];
                        }
                    }
                    if ($params['type_data'] == 3){
                        if (empty($params['type_value3'])){
                            $this->error('请选择要通知的人员');
                        }else{
                            $params['type_value'] = $params['type_value3'];
                        }
                    }
                }

                $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);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    //todo 发送通知, 系统人少的时候可以直接在这里通知,人多的时候可以把发送任务放到某张表里,用定时任务或队列去发送。
                    //发送推送消息
                    $userModel = new User();
                    $staffModel = new Staff();
                    if ($params['type_data'] == 1){
                        $users = $userModel->field('id,clientid')->select();
                    } elseif ($params['type_data'] == 2){
                        $users = $staffModel
                            ->field('u.id,u.clientid')
                            ->alias('d')
                            ->join('user u', 'u.id=d.user_id', 'LEFT')
                            ->where([
                                'depart_id' => ['in', $params['type_value']]
                            ])
                            ->select();
                    } elseif ($params['type_data'] == 3){
                        $users = $userModel->field('id,clientid')->where(['id' => ['in', $params['type_value']]])->select();
                    }
                    if (!empty($users)){
                        $getui = new Getui();
                        foreach ($users as $user){
                            $cid = $user['clientid'];
                            $notifyTitle = $params['title'] ?? '公告';
                            if (!empty($params['warning_id'])){
                                $warning = \app\admin\model\inspection\Warning::get($params['warning_id']);
                                if ($warning){
                                    $notifyTitle = $warning['title'];
                                }
                            }
                            $notifyBody = $notifyTitle . ',请及时查看';
                            $payload = ['notice_type' => 0, 'notices_article_id' => $this->model->id,'title' => $notifyTitle, 'content' => $notifyBody];
                            $resArr = $getui->pushToSingleByCid($cid, $notifyTitle, $notifyBody, 'payload', '', json_encode($payload));
                            //记录消息推送日志
                            $logData = [
                                'notice_type' => 0,
                                'notice_title' => $notifyTitle,
                                'notice_content' => $notifyBody,
                                'relation_table' => 'notices_article',
                                'relation_id' => $this->model->id,
                                'send_type' => 2,//管理员
                                'send_id' => $this->auth->id,
                                'rec_type' => 1,//会员
                                'rec_id' => $user['id']
                            ];
                            if ($resArr['code'] == 0){
                                $logData['taskid'] = '';
                                $logData['push_res'] = '';
                                foreach ($resArr['data'] as $taskid => $cr){
                                    $logData['taskid'] = $taskid;
                                    $logData['push_res'] = $cr[$cid] ?? '';
                                }
                            }else{
                                $logData['error_msg'] = $resArr['code'] . ':' . $resArr['msg'];
                            }
                            $noticesnormalModel = new Noticesnormal();
                            $noticesnormalModel->allowField(true)->save($logData);
                        }
                    }
                    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();
    }

    /**
     * 编辑
     */
    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) {
                $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);
                    }
                    $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', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}