<?php
namespace app\mobile\controller;

use think\facade\Db;
use app\mobile\service\MessageInbox;

class OmsMessages extends OmsBase {
    public function records() { return $this->guarded(function() {
        $this->requireMethod('GET'); $account=$this->current(); $service=new MessageInbox($this->app);
        $scope=$this->request->get('scope','pending'); $business=$this->request->get('business',''); $page=$this->request->get('page',1);
        if (!in_array($scope,['pending','done','notice'],true) || !is_scalar($business) || ($business!=='' && !isset(MessageInbox::LABELS[$business])) || !is_scalar($page) || !preg_match('/^[1-9][0-9]{0,5}$/',(string)$page)) $this->fail('消息查询条件不正确');
        $counts=$service->sync($account);
        $query=Db::name('message')->where(['auth_id'=>$account['id'],'state'=>$scope]);
        $categories=[];
        foreach((clone $query)->field('business,COUNT(*) total')->group('business')->select()->toArray() as $row) $categories[]=['key'=>$row['business'],'label'=>MessageInbox::LABELS[$row['business']],'total'=>(int)$row['total']];
        if($business!=='')$query->where('business',$business);
        $total=(clone $query)->count();
        $order=$scope==='pending'?'CASE WHEN deadline>0 AND deadline<'.time().' THEN 0 ELSE 1 END,task_at desc,id desc':($scope==='done'?'handled_at desc,id desc':'task_at desc,id desc');
        $items=[];
        foreach($query->orderRaw($order)->page((int)$page,15)->select()->toArray() as $row) {
            $items[]=['id'=>(int)$row['id'],'business'=>$row['business'],'businessLabel'=>MessageInbox::LABELS[$row['business']],
                'title'=>$row['title'],'stage'=>$row['stage'],'state'=>$row['state'],'fields'=>json_decode($row['fields'],true) ?: [],
                'route'=>$row['route'],'read'=>(bool)$row['read_at'],'time'=>$row['task_at']?date('Y-m-d H:i',$row['task_at']):'',
                'handledAt'=>$row['handled_at']?date('Y-m-d H:i',$row['handled_at']):'',
                'deadline'=>$row['deadline']?date('Y-m-d H:i',$row['deadline']):'','overdue'=>$scope==='pending' && $row['deadline']>0 && $row['deadline']<time()];
        }
        return json(['code'=>0,'message'=>'成功','data'=>['items'=>$items,'total'=>$total,'page'=>(int)$page,'counts'=>$counts,'categories'=>$categories]]);
    }); }
    public function summary() { return $this->guarded(function() {
        $this->requireMethod('GET'); $account=$this->current();
        return json(['code'=>0,'message'=>'成功','data'=>(new MessageInbox($this->app))->summary($account)]);
    }); }
    public function read() { return $this->guarded(function() {
        $this->requireMethod('POST'); $account=$this->current(); $id=$this->request->post('id');
        if(!is_scalar($id) || !preg_match('/^[1-9][0-9]{0,18}$/',(string)$id))$this->fail('消息编号不正确');
        $row=Db::name('message')->where(['id'=>$id,'auth_id'=>$account['id']])->find();
        if(!$row)$this->fail('消息不存在或不属于本人',404);
        if(!$row['read_at'])Db::name('message')->where(['id'=>$id,'auth_id'=>$account['id'],'read_at'=>0])->update(['read_at'=>time()]);
        return json(['code'=>0,'message'=>'成功','data'=>null]);
    }); }
}
