<?php
/**
 * 系统设置
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Account_group;
use Illuminate\Http\Request as Req;
use Illuminate\Support\Facades\DB;
use Request;

/**
 *
 */
class MessageController extends Controller
{
    /**
     * 活动公告
     */
    function Index(Req $req)
    {
        $request = array();
        $request['title'] = isset($req->title) ? trim ($req->title) : null;
        $request['type'] = isset($req->type) ? trim ($req->type) : null;
//        $request['message_type'] = isset($req->message_type) ? trim($req->message_type) : null;
        $request['toname'] = isset($req->toname) ? trim ($req->toname) : null;
        $request['fromname'] = isset($req->fromname) ? trim ($req->fromname) : null;

        $dt = \App\Lib\DataTable\DataTable::init ();
        $dt->setDataSource ('/admin/Message/getArticle');
        $dt->setLang ('notice');
        // $dt->addColsFields('id');
        $dt->addColsFields ('title');
        $dt->addColsFields ('toname');
        $dt->addColsFields ('group_name');
        $dt->addColsFields ('formname');
        $dt->addColsFields ('add_type');
        $dt->addColsFields ('is_show');
        // $dt->addColsFields('content');
        $dt->addColsFields ('add_time');
//        $dt->addColsFields('message_type');
        $dt->addColsFields ('type');
        $dt->enableCheckBox ();
        $arr[] = 'view';
        $dt->setToolBar ($arr, array('width' => 140));
        return view ('admin.Manager/arictle', $dt->render ($request));
    }

    //获取信息
    //获取活动信息
    function getArticle()
    {
        $limit = Request::has ('limit') ? Request::get ('limit') : 10;

        $title = Request::has ('title') ? Request::get ('title') : '';
        $content = Request::has ('content') ? Request::get ('content') : '';
        $message_type = Request::has ('message_type') ? Request::get ('message_type') : '';
        $type = Request::has ('type') ? Request::get ('type') : '';
        $forname = Request::has ('forname') ? Request::get ('forname') : '';
        $toname = Request::has ('toname') ? Request::get ('toname') : '';
        $add_time = Request::has ('add_time') ? Request::get ('add_time') : '';


        $where = array();
        if (!empty($title)) {
            $where[] = array('title', 'like', '%' . $title . '%');
        }
        if (!empty($type)) {
            $where[] = array('type', '=', $type);
        } else {
            $where[] = array('type', '!=', 2);
            $where[] = array('type', '!=', 4);
        }
        if (!empty($content)) {
            $where[] = array('content', 'like', '%' . $content . '%');
        }
        if (!empty($forname)) {
            $where[] = array('formname', 'like', '%' . $forname . '%');
        }
        if (!empty($toname)) {
            $where[] = array('toname', 'like', '%' . $toname . '%');
        }
        if (!empty($add_time)) {
            $add_time = date ('Y-m-d H:i:s', strtotime ($add_time));
            $where[] = array('add_time', '<=', $add_time);
        }

        $db = new \App\Models\Manager();
        $data = $db->getlist ($limit, $where);
        if (!($data < 0)) {
            $langinfo = trans ('status.manager');
            $messged = trans ('notice.message_status');
            $show = trans ('notice.show');
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['type'] = $langinfo[$v['type']];
                if (!empty($v['add_type'])) {
                    $data['data'][$k]['add_type'] = $messged[$v['add_type']];
                }
                $data['data'][$k]['is_show'] = $show[$v['is_show']];
            }
        }
        return \App\Lib\DataTable\DataTable::init ()->toJson ($data['data'], $data['total']);
    }

    function view(Req $req)
    {
        return $this->Edit ($req);
    }

    function Edit(Req $req)
    {
        $id = $req->id;
//        $id=Request::has('id')?Request::get('id'):'';
        if (intval ($id) < 1) {
            abort (404);
        }
        $db = new \App\Models\Manager;
        $groupdata = \App\Models\Account_group::getAllInfo ();
        if (!$req->isMethod ('post')) {
            $data = $db->getDmsg ($id, 1);
            if (!$data) {
                return responseToJson ($data);
            }
            return view ('admin.Manager/editNotice', ['data' => $data, 'group' => $groupdata]);
        } else {
            $data['title'] = $req->input ('title');
            $data['content'] = $req->desc;
            $res = $db->updateMsg ($data, $id);
//            $log = array(
//                session('adminInfo.admin_name'),
//            );
//            OperationLog(session('adminInfo.admin_id'), 'edit_game', $log);
            return responseToJson ($res);
        }
    }

    /**
     * 批量删除
     * [delete description]
     * @return [type] [description]
     */
    function delete(Req $req)
    {
        $id = $req->input ('id');
        if (empty($id)) {
            return responseToJson (-2001); //id����Ϊ��
        }
        $ids = explode (',', $id);
        if (!is_array ($ids) && intval ($ids) < 0) {
            return responseToJson (-2002); //id����
        }
        if (is_array ($ids) && count ($ids) > 0) {
            foreach ($ids as $k => $v) {
                if (intval ($v) < 1) {
                    unset($ids[$k]);
                }
            }
        }
        $rows = \App\Models\Manager::whereIn ('id', $ids)->delete ();
        if (!$rows) {
            return responseToJson (-2003); //id����
        }
        $log = array(
            session('adminInfo.admin_name'),
        );
        OperationLog(session('adminInfo.admin_id'), 'del_mess', $log);
        return responseToJson (1); //id����
    }

    function MessageView()
    {
        $id = Request::has ('id') ? Request::get ('id') : '';
        $admin_id = session ('adminInfo.admin_id');
        $where = [
            'id',
            $id
        ];
        $dataWhwew = [
            'message_id' => $id,
            'account_identity' => $admin_id,
//            'add_time'=>time()
        ];
        $db = new \App\Models\Manager();
        $dbRead = new \App\Models\MessageRead;
        $data = $db->getlistd ($where);
        $dataRead = $dbRead->Messagelist ($id, $admin_id);
        if ($dataRead < 0) {
            $dat = $dbRead->addMessage ($dataWhwew);
        }
        return view ('admin.Manager/view', ['data' => $data]);
    }

    /**
     * 添加消息
     * @param Req $req
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    function addNotice(Req $req)
    {
        $groupdata = \App\Models\Account_group::getAllInfo ();

        if (!$req->isMethod ('post')) {
            $groupdatas = $groupdata;
            return view ('admin.Manager/editNotice', ['select' => 1, 'group' => $groupdatas]);
        } else {
            $data['title'] = $req->input ('title');
            $data['type'] = $req->type ? intval ($req->type) : '';
            if (empty($data['type'])) {
                return responseToJson (-3001341);
            }
            $data['content'] = $req->desc;
            $log = array(
                session ('adminInfo.admin_name'),
                $data['title']
            );
            $data['add_time'] = date ('Y-m-d H:i:s');
            $data['formname'] = $req->input ('formname');
            $data['toname'] = str_replace ('，', ',', strip_tags (trim ($req->input ('toname'))));
            $data['add_type'] = isset($req->add_type) ? trim ($req->add_type) : '1';
            $data['is_show'] = isset($req->is_show) ? trim ($req->is_show) : 0;  //首页是否弹出显示
            $groups = $req->groups;
            $send = [
                'name' => $data['title'],
                'from' => $data['formname'],
                'content' => $data['content'],
                'time' => $data['add_time'],
                'type' => $data['type']
            ];
            $db = new \App\Models\Manager;
            //普通消息
            if ($data['type'] == 1) {
                $dataName = explode (',', $data['toname']);
                $send['to'] = $this->getIdBy ($dataName);//接收者列表
            }
            //系统消息
            if ($data['type'] == 2) {
                $data['formname'] = '系统消息';
                //$data['toname'] = 'all';
            }
            //系统通知
            if ($data['type'] == 3) {
                $data['formname'] = '系统通知';
                //获取发送用户组
                if (is_array ($groups) && count ($groups) > 0) {
                    $data['toname'] = 'groups';
                    $data['group_code'] = '0,' . implode (',', $groups) . ',';
                    $data['group_name'] = '|';
                    foreach ($groupdata as $k => $v) {
                        if (in_array ($v['group_code'], $groups)) {
                            $data['group_name'] .= $v['group_name'] . '|';
                        }
                    }
                }
                $groupcode = isset($data['group_code']) ? $data['group_code'] : 'all';

            }
            if (!$data['toname']) {
                $data['toname'] = 'all';
            }
            $res = $db->addNotice ($data);
            if ($res < 0)
                return responseToJson ($res);
            OperationLog (session ('adminInfo.admin_id'), 'add_no', $log);

            return responseToJson (1);
        }
    }


    /**
     * 根据用户账号查ID
     * @param $names
     * @return null
     */
    protected function getIdBy($names)
    {
        if (!is_array ($names)) $names = explode (',', $names);
        $names = array_unique ($names);
        if (!$names) return null;
        $ids = (new Account())->whereIn ('account', $names)->pluck ('identity');
        return $ids ? $ids->toArray () : null;
    }


}
