<?php
/**
 * +------------------------------------------------------------
 * | 站内信 message/controller/Api.php
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018/5/31
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018/5/31
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\message\controller;

use think\Db;

class Api extends Module
{
    /**
     * 获取消息列表
     * @param array $attr
     * @return \think\response\Json
     */
    function read($attr = [])
    {
        is_string($attr) && $attr = \json_decode($attr, true);
        $result = $this->query($attr);
        return json(['code' => 1, 'msg' => '', 'data' => $result]);
    }

    /**
     * 消息行为，已读，删除
     * @param array $id
     * @param string $action
     * @return \think\response\Json
     */
    function message($id = [], $action = '')
    {
        $where = [];
        if (!empty(session('user.id'))) {
            $where[] = ['user_id', '=', self::$user['id']];
        } else if (!empty(session('admin.id'))) {
            $where[] = ['admin_id', 'neq', '0'];
        } else {
            return json(['code' => 1000, 'msg' => '请登录']);
        }
        if ($id != 'all' && !empty($id)) {
            $where[] = ['id', 'in', (array)$id];
        }
        if ($action == 'read') {
            model('app\message\model\Message')->where($where)->setField('status', 1);
        }
        if ($action == 'delete') {
            model('app\message\model\Message')->where($where)->delete();
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 发送站内信
     */
    function send($attr = [])
    {
        $result = $this->validate($attr, [
            'content' => 'require'
        ], [
            'content.require' => '信息内容不能为空'
        ]);
        if ($result !== true) return json(['code' => 72001, 'msg' => $result]);
        if (empty($attr['user_id']) && empty($attr['admin_id'])) return json(['code' => 72002, 'msg' => '发送对象不能为空']);
        $attr['create_time'] = time();
        $attr['extend'] = empty($attr['extend']) ? '' : json_encode($attr['extend']);
        $attr['module'] = isset($attr['module']) ? $attr['module'] : self::$sys['module'];
        Db::name('message')->insert($attr);
        return json(['code' => 1, 'msg' => '发送成功']);
    }
}