<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Ixudra\Curl\Facades\Curl;

class Template extends Controller
{


    /**
     * 模板消息
     */
    public static function send($touser, $template_id, $url, $array, $color = null)
    {
        $default_color = [
            'first' => '#173177',
            'remark' => '#FA8F98'
        ];
        $data = null;
        foreach ($array as $key => $value) {
            $data[$key] = [
                'value' => $value,
                'color' => @$color[$key] ?: @$default_color[$key],
            ];
        }
        $post = json_encode([
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'data' => $data
        ]);
        $http = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . Base::getAccessToken();
        $result = json_decode(Curl::to($http, $post)->withData($post)->post(), true);
        if ($result['errcode'] == 0) {
            return ['code' => $result['errcode'], 'msg' => $result['errmsg'], 'data' => ['msgid' => $result['msgid']]];
        } else {
            return ['code' => $result['errcode'], 'msg' => $result['errmsg']];
        }
    }
}
