<?php
namespace app\adminVue\controller;
use think\facade\Db;
use app\mobile\service\RadioAccess;

class V2RadioSettings extends V2Base
{
    protected function initialize() { parent::initialize();Db::execute('SET NAMES utf8mb4'); }
    private function manager() { if((int)$this->actor['rightid']<=98)$this->fail('仅系统管理员可以配置播音室人员',403); }
    private function result($data=null) { return json(['code'=>0,'msg'=>'操作成功','data'=>$data]); }
    private function id() {
        $id=$this->request->post('accountId');if((!is_int($id)&&!is_string($id))||!preg_match('/^[1-9][0-9]{0,9}$/D',(string)$id)||(float)$id>2147483647)$this->fail('请选择有效账号');return (int)$id;
    }
    public function index() {
        $this->manager();$items=[];
        foreach(Db::name('radio_operator')->order('granted_at desc,account_id')->select()->toArray() as $row) {
            $account=Db::name('auth')->find($row['account_id']);$person=$account&&$account['username']===$row['username']?RadioAccess::person($account):null;
            $items[]=['accountId'=>(int)$row['account_id'],'username'=>$row['username'],'name'=>$person['name']??'账号已失效','active'=>(bool)$person,'grantedAt'=>date('Y-m-d H:i:s',$row['granted_at'])];
        }
        return $this->result(['items'=>$items]);
    }
    public function candidates() {
        $this->manager();$keyword=$this->request->get('keyword','');if(!is_string($keyword)||mb_strlen($keyword)>50)$this->fail('搜索内容最多50字');
        $query=Db::name('auth')->alias('a')->leftJoin('member_list m','m.id=a.user_id')->leftJoin('admin_user u','u.id=a.admin_id')->where('a.status',1);
        if(trim($keyword)!=='')$query->whereLike('a.username|m.ename|u.truename','%'.addcslashes(trim($keyword),'%_\\').'%');
        $items=[];
        foreach($query->field('a.id,a.username,a.user_type,a.user_id,a.admin_id,a.status')->order('a.id')->limit(50)->select()->toArray() as $a) {
            $person=RadioAccess::person($a);if($person)$items[]=['accountId'=>(int)$a['id'],'username'=>$a['username'],'name'=>$person['name']];
        }
        return $this->result(['items'=>$items]);
    }
    public function records() {
        $this->manager();$query=Db::name('radio_request');$date=$this->request->get('date','');
        if($date!=='') {
            if(!is_string($date)||!preg_match('/^20[0-9]{2}-[0-9]{2}-[0-9]{2}$/D',$date))$this->fail('播放日期无效');
            $parsed=\DateTimeImmutable::createFromFormat('!Y-m-d',$date);if(!$parsed||$parsed->format('Y-m-d')!==$date)$this->fail('播放日期无效');$query->where('play_date',$date);
        }
        foreach(['shift'=>2,'slot'=>2,'status'=>3] as $field=>$max) {
            $value=$this->request->get($field,'');if($value==='')continue;
            if((!is_int($value)&&!is_string($value))||!preg_match('/^[1-3]$/D',(string)$value)||(int)$value>$max)$this->fail('筛选参数无效');$query->where($field,(int)$value);
        }
        $keyword=$this->request->get('keyword','');if(!is_string($keyword)||mb_strlen($keyword)>50)$this->fail('搜索内容最多50字');
        if(trim($keyword)!=='')$query->whereLike('song|target|employee_name|employee_no','%'.addcslashes(trim($keyword),'%_\\').'%');
        $page=$this->request->get('page',1);if((!is_int($page)&&!is_string($page))||!preg_match('/^[1-9][0-9]{0,4}$/D',(string)$page))$this->fail('页码无效');
        $total=(clone $query)->count();$rows=$query->field('id,employee_no,employee_name,song,singer,target,blessing,play_date,shift,slot,status,cancel_reason,handler_name,created_at,played_at,notification_status')->order('id desc')->page((int)$page,15)->select()->toArray();
        foreach($rows as &$row)foreach(['id','shift','slot','status','created_at','played_at','notification_status'] as $field)$row[$field]=(int)$row[$field];unset($row);
        return $this->result(['items'=>$rows,'total'=>$total]);
    }
    public function grant() {
        $this->manager();$id=$this->id();$a=Db::name('auth')->find($id);
        if(!$a||!RadioAccess::person($a))$this->fail('账号已停用或没有有效人员关联');
        $row=['account_id'=>$id,'username'=>$a['username'],'granted_by'=>$this->actor['id'],'granted_at'=>time()];
        // 以账号主键覆盖同一人的授权，不接受客户端指定工号或姓名。
        Db::name('radio_operator')->replace()->insert($row);
        return $this->result();
    }
    public function revoke() {
        $this->manager();Db::name('radio_operator')->where('account_id',$this->id())->delete();return $this->result();
    }
}
