<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\message\model\Message as MessageList;
use think\facade\Db;

class MessageIndex extends ApiController
{	

    protected $middleware = [
    	Auth::class => ['except' => []]
    ];

    //收件箱
    public function inbox()
    {
        $param = get_params();
        $this->uid = JWT_UID;
        $param['status'] = 1;
        $map = [];
        if (!empty($param['keywords'])) {
            $map[] = ['title', 'like', '%' . $param['keywords'] . '%'];
        }
        if (!empty($param['read'])) {
            if($param['read']==1){
                $map[] = ['read_time', '=', 0];
            }else{
                $map[] = ['read_time', '>', 0];
            }                
        }
        if (!empty($param['template'])) {
            if($param['template']==0){
                $map[] = ['template', '=', 0];
            }else{
                $map[] = ['template', '>', 0];
            }
        }
        $map[] = ['to_uid', '=', $this->uid];
        $map[] = ['status', '=', $param['status']];
        //按时间检索
        $start_time = isset($param['start_time']) ? strtotime(urldecode($param['start_time'])) : 0;
        $end_time = isset($param['end_time']) ? strtotime(urldecode($param['end_time'])) : 0;
        if ($start_time > 0 && $end_time > 0) {
            $map[] = ['send_time', 'between', "$start_time,$end_time"];
        }
        $model = new MessageList();
        $list = $model->get_list($param, $map, $this->uid);
        $this->apiSuccess('获取成功', $list);
    }
   
    //查看消息
    public function read()
    {
        $param = get_params();
        $this->uid = JWT_UID;
        $id = $param['id'] ?? 0;
		$model = new MessageList();
        $detail = $model->detail($id);
        if (empty($detail)) {
            $this->apiError("消息不存在");
        }
        if ($detail['to_uid'] != $this->uid && $detail['from_uid'] != $this->uid) {
            $this->apiError("消息不存在");
        }
        Db::name('Message')->where(['id' => $id])->update(['read_time' => time()]);
        if($detail['from_uid']==0){
            $detail['person_name'] = '系统管理员';
        }
        else{
            $sender = get_admin($detail['from_uid']);
            $detail['person_name'] = $sender['name'];
        }
		if($detail['send_time']>0){
			$detail['send_time'] = date('Y-m-d H:i:s',$detail['send_time']);    
		}
		else{
			$detail['send_time'] = '-';
		}        
        //发送人查询
        $user_names=[];
        //已读回执
        $read_user_names = [];
		
        if($detail['from_uid'] == $this->uid){
            $mails= MessageList::where(['pid' => $id])->select()->toArray();
            $read_mails= MessageList::where([['pid','=',$id],['read_time','>',2]])->select()->toArray();
            $read_user_ids = array_column($read_mails, 'to_uid');
            $read_users = Db::name('Admin')->where('status', 1)->where('id', 'in', $read_user_ids)->select()->toArray();
            $read_user_names = array_column($read_users, 'name');
			
			$user_ids = array_column($mails, 'to_uid');
			$users = Db::name('Admin')->where('status', 1)->where('id', 'in', $user_ids)->select()->toArray();
			$user_names = array_column($users, 'name');
        }
		else{
			$users = Db::name('Admin')->where('id', $detail['to_uid'])->value('name');
			array_push($user_names,$users);
		}
        $detail['create_time'] = date('Y-m-d H:i:s', $detail['create_time']);
        $detail['update_time'] = date('Y-m-d H:i:s', $detail['update_time']);
        $detail['read_time'] = date('Y-m-d H:i:s', $detail['read_time']);
        $detail['users'] = implode(",", $user_names);
        $detail['read_users'] = implode(",", $read_user_names);
        $this->apiSuccess('查看成功', $detail);
    }

    //消息删除
    public function delete()
    {
        $param = get_params();
        $this->uid = JWT_UID;
        $param = get_params();
        $type = 4;
        $ids = empty($param['ids']) ? 0 : $param['ids'];
        $idArray = explode(',', $ids);
        $list = [];
        foreach ($idArray as $key => $val) {
            $list[] = [
                'status' => -1,
                'id' => $val,
                'update_time' => time(),
            ];
        }
        foreach ($list as $key => $v) {
            if (MessageList::update($v) !== false) {
                add_log('delete', $v['id'],[],'消息');
            }
        }
        $this->apiSuccess('操作成功');
    }

}
