<?php
namespace app\store\service\wxapp;
use app\store\model\Wxapp as WxappModel;
use app\store\model\Setting as SettingModel;
use app\common\library\helper;
use app\common\service\Basics;
use app\common\library\wechat\WxSubMsg;
use app\common\exception\BaseException;
class SubMsg extends Basics
{
private $WxSubMsg;
public function __construct($wxappId = null)
{
$wxConfig = WxappModel::getWxappCache($wxappId);
$this->WxSubMsg = new WxSubMsg($wxConfig['app_id'], $wxConfig['app_secret']);
}
public function shuttle()
{
$myList = $this->getMyTemplateList();
$addedList = $this->getNotAddedTemplates($myList);
$newList = $this->onBatchAdd($addedList);
$tplList = array_merge($newList, $myList);
return $this->saveAll($tplList);
}
private function saveAll($tplList)
{
$data = SettingModel::getItem('submsg');
foreach ($data as &$group) {
foreach ($group as &$item) {
if (!isset($item['title'])) continue;
$tpl = helper::arraySearch($tplList, 'title', $item['title']);
$tpl != false && $item['template_id'] = $tpl['priTmplId'];
}
}
return (new SettingModel)->edit('submsg', $data);
}
private function onBatchAdd($newList)
{
foreach ($newList as &$item) {
$response = $this->WxSubMsg->addTemplate($item['tid'], $item['kidList'], $item['sceneDesc']);
if ($response === false) {
throw new BaseException(['msg' => "添加模板[{$item['sceneDesc']}]失败:" . $this->WxSubMsg->getError()]);
}
$item['priTmplId'] = $response['priTmplId'];
}
return $newList;
}
private function getNotAddedTemplates($myList)
{
$templateLists = $this->getTemplates();
if (empty($myList)) return $templateLists;
$data = [];
foreach ($templateLists as $item) {
if (helper::arraySearch($myList, 'title', $item['title']) === false) {
$data[] = $item;
}
}
return $data;
}
private function getTemplates()
{
return [
[
'tid' => 9344,
'title' => '新订单提醒',
'kidList' => [1, 2, 4, 3],
'sceneDesc' => '新订单提醒',
],
[
'tid' => 855,
'title' => '订单发货通知',
'kidList' => [1, 2, 12, 11, 17],
'sceneDesc' => '订单发货通知',
],
[
'tid' => 5049,
'title' => '售后状态通知',
'kidList' => [1, 6, 2, 3, 4],
'sceneDesc' => '售后状态通知',
],
[
'tid' => 5008,
'title' => '拼团进度通知',
'kidList' => [1, 5, 7, 3, 6],
'sceneDesc' => '拼团进度通知',
],
[
'tid' => 4050,
'title' => '代理商入驻审核通知',
'kidList' => [1, 2, 3, 4],
'sceneDesc' => '分销商入驻审核通知',
],
[
'tid' => 2001,
'title' => '提现成功通知',
'kidList' => [1, 3, 4],
'sceneDesc' => '提现成功通知',
],
[
'tid' => 3173,
'title' => '提现失败通知',
'kidList' => [1, 3, 4],
'sceneDesc' => '提现失败通知',
],
];
}
private function getMyTemplateList()
{
$response = $this->WxSubMsg->getTemplateList();
if ($response === false) {
throw new BaseException(['msg' => '拉取模板列表失败:' . $this->WxSubMsg->getError()]);
}
return $response['data'];
}
}