<?php
namespace app\adminVue\controller;

use think\facade\Db;
use think\facade\Cache;
use think\facade\Log;

/** Uses the same configured template and auth bindings as the current mobile suggestion flow. */
class V2SuggestionNotice
{
    protected function settings()
    {
        return ['template'=>trim((string)env('wxoms.gzh_suggestion_template_id','')),'appid'=>env('wxoms.gzh_appid',''),
            'secret'=>env('wxoms.gzh_secret',''),'mini'=>env('wxoms.appid','')];
    }
    protected function request($url,$data)
    {
        $ch=curl_init($url);
        curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($data,JSON_UNESCAPED_UNICODE),CURLOPT_HTTPHEADER=>['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT=>5,CURLOPT_TIMEOUT=>10,CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2]);
        $ca=app()->getRootPath().'config/cacert.pem';if(is_file($ca))curl_setopt($ch,CURLOPT_CAINFO,$ca);
        $body=curl_exec($ch);$status=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);
        $result=json_decode((string)$body,true);
        if($status!==200||!is_array($result))throw new \RuntimeException('Notification transport unavailable');
        return $result;
    }
    public function send($row)
    {
        try{
            $binding=Db::name('auth')->where('admin_id',$row['owner'])->where('user_type','>',1)->where('status',1)->where('gzhOpenid','<>','')->value('gzhOpenid');
            if(!$binding)return ['status'=>'skipped','message'=>'分配已保存，责任人未绑定公众号，未发送待办通知'];
            $s=$this->settings();
            if(!$s['template']||!$s['appid']||!$s['secret'])return ['status'=>'skipped','message'=>'分配已保存，公众号通知配置不完整，未发送通知'];
            $key='admin-v2:suggestion-notice:'.hash('sha256',$s['appid']);$token=Cache::get($key);
            if(!$token){$r=$this->request('https://api.weixin.qq.com/cgi-bin/stable_token',['grant_type'=>'client_credential','appid'=>$s['appid'],'secret'=>$s['secret']]);
                if(empty($r['access_token']))throw new \RuntimeException('Notification token unavailable');$token=$r['access_token'];Cache::set($key,$token,max(60,(int)($r['expires_in']??7200)-120));}
            $r=$this->request('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.rawurlencode($token),[
                'touser'=>$binding,'template_id'=>$s['template'],'miniprogram'=>['appid'=>$s['mini'],'pagepath'=>'pages/suggestion/detail?id='.$row['id']],
                'data'=>['keyword1'=>['value'=>(string)$row['id']],'keyword2'=>['value'=>'合理化建议'],'keyword3'=>['value'=>'分配给你，请及时反馈'],
                    'keyword4'=>['value'=>$row['ename']],'keyword5'=>['value'=>date('Y-m-d H:i:s')]]]);
            if(!isset($r['errcode'])||(int)$r['errcode']!==0){if(in_array((int)($r['errcode']??0),[40001,40014,42001],true))Cache::delete($key);throw new \RuntimeException('Notification rejected');}
            return ['status'=>'sent','message'=>'分配已保存，待办通知已发送'];
        }catch(\Throwable $e){Log::warning('admin-v2 suggestion notification failed');return ['status'=>'failed','message'=>'分配已保存，但待办通知发送失败，请另行提醒责任人'];}
    }
}
