<?php
namespace app\mobile\controller;

use app\mobile\service\ChatService;
use think\facade\Db;

/** 小程序公告板接口；沿用员工微信绑定，独立签发短期聊天凭证。 */
class Chat extends OmsBase
{
    protected function initialize() { ChatService::useChatCharset($this->app); parent::initialize(); }
    private function respond($data) { return json(['code'=>0,'data'=>$data,'serverTime'=>ChatService::now()]); }
    /** 新版小程序直接复用 OmsAuth 凭证，不再次登录微信或信任客户端身份。 */
    public function sessionV2() {
        return $this->guarded(function () {
            $this->requireMethod('POST');
            $account = $this->current();
            if ((int)$account['id'] <= 0 || (int)$account['id'] >= ChatService::AUTH_ID_OFFSET) $this->fail('员工身份编号不正确');
            $service = new ChatService($this->app);
            $user = $service->user(ChatService::AUTH_ID_OFFSET+(int)$account['id']);
            $service->rate('session:'.$user['id'],30,60);
            $token = bin2hex(random_bytes(32)); $expires = ChatService::now()+3600000;
            $service->storeSession($token,['id'=>$user['id'],'openid'=>$account['openid'],'expiresAt'=>$expires,'sourceKey'=>$this->cacheKey('session:'.hash('sha256',$this->bearer()))],3600);
            return $this->respond(['token'=>$token,'expiresAt'=>$expires,'serverTime'=>ChatService::now(),'user'=>$user]);
        });
    }
    public function session() {
        return $this->guarded(function () {
            $this->requireMethod('POST');
            $username = $this->requiredText('employeeNo', 20);
            $code = $this->requiredText('code', 256);
            $service = new ChatService($this->app);
            $service->rate('session:'.hash('sha256', $this->request->ip()), 30, 60);
            $config = $this->app->config->get('chat');
            if (empty($config['secret'])) $this->fail('公告板微信认证尚未配置，请联系管理员', 503);
            $result = $this->wechatRequest('https://api.weixin.qq.com/sns/jscode2session', ['appid'=>$config['appid'],'secret'=>$config['secret'],'js_code'=>$code,'grant_type'=>'authorization_code']);
            $account = Db::name('admin_user_mobile')->where('username', $username)->find();
            if (!$account || empty($account['openid']) || !hash_equals((string)$account['openid'], (string)$result['openid'])) $this->fail('请先用本人微信完成员工账号认证', 403);
            $user = $service->user((int)$account['id']);
            $token = bin2hex(random_bytes(32)); $expires = ChatService::now() + 3600000;
            $service->storeSession($token, ['id'=>$user['id'],'openid'=>$account['openid'],'expiresAt'=>$expires], 3600);
            return $this->respond(['token'=>$token,'expiresAt'=>$expires,'user'=>$user]);
        });
    }
    private function handle($action) {
        return $this->guarded(function () use ($action) {
            $this->requireMethod('POST');
            $service = new ChatService($this->app);
            $user = $service->authenticate($this->bearer());
            $data = $this->request->post();
            if ($action === 'image') $data['file'] = $this->request->file('image');
            return $this->respond($service->perform($action, $user, $data));
        });
    }
    public function hall() { return $this->handle('hall'); }
    public function attention() { return $this->handle('attention'); }
    public function rooms() { return $this->handle('rooms'); }
    public function room() { return $this->handle('room'); }
    public function create() { return $this->handle('create'); }
    public function messages() { return $this->handle('messages'); }
    public function send() { return $this->handle('send'); }
    public function read() { return $this->handle('read'); }
    public function join() { return $this->handle('join'); }
    public function members() { return $this->handle('members'); }
    public function mentionMembers() { return $this->handle('mentionMembers'); }
    public function invite() { return $this->handle('invite'); }
    public function approve() { return $this->handle('approve'); }
    public function extend() { return $this->handle('extend'); }
    public function close() { return $this->handle('close'); }
    public function update() { return $this->handle('update'); }
    public function mute() { return $this->handle('mute'); }
    public function remove() { return $this->handle('remove'); }
    public function leave() { return $this->handle('leave'); }
    public function recall() { return $this->handle('recall'); }
    public function report() { return $this->handle('report'); }
    public function image() { return $this->handle('image'); }
    public function connect() { return $this->handle('connect'); }
    public function adminReports() { return $this->handle('adminReports'); }
    public function resolveReport() { return $this->handle('resolveReport'); }
    public function imageContent() {
        return $this->guarded(function () {
            $service = new ChatService($this->app);
            $file = $service->imageContent((string)$this->request->get('ticket', ''));
            return response(file_get_contents($file['path']), 200, ['Content-Type'=>$file['mime'],'Cache-Control'=>'private, no-store','X-Content-Type-Options'=>'nosniff']);
        });
    }
}
