DispatchService.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. <?php
  2. namespace common\components\delivery\services;
  3. use biz\shop\classes\ShopClass;
  4. use bizGhs\express\classes\DeliveryAuthTokenClass;
  5. use bizGhs\express\classes\GhsDeliveryOrderClass;
  6. use bizGhs\order\classes\OrderClass;
  7. use bizGhs\order\classes\OrderItemClass;
  8. use bizHd\express\classes\HdDeliveryOrderClass;
  9. use common\components\delivery\helpers\HttpClient;
  10. use common\components\delivery\services\adapter\{DadaAdapter,
  11. DidiAdapter,
  12. Functions,
  13. ShansongAdapter,
  14. HuolalaAdapter,
  15. FengniaoAdapter,
  16. ShunfengAdapter}; // MeituanAdapter, UUAdapter,
  17. use common\components\util;
  18. use Yii;
  19. /**
  20. * 聚合调度逻辑(平台选择/优先级)
  21. * Class DispatchService
  22. * @package App\Services
  23. */
  24. class DispatchService
  25. {
  26. protected $adapters;
  27. protected $platformName = '';
  28. public function __construct($mainId, $platform='')
  29. {
  30. if ($platform == '') {
  31. $authPlatforms = DeliveryAuthTokenClass::getAllByCondition(['mainId'=>$mainId]);
  32. foreach($authPlatforms as $pt) {
  33. switch ($pt['platform']) {
  34. case 'shansong':
  35. $this->adapters['shansong'] = new ShansongAdapter($pt['accessToken'], $pt['shopId']);
  36. break;
  37. case 'huolala':
  38. $this->adapters['huolala'] = new HuolalaAdapter($pt['accessToken']);
  39. break;
  40. case 'fengniao':
  41. $adapter = new FengniaoAdapter($pt['accessToken']);
  42. // 动态设置商户ID与门店ID
  43. $adapter->setMerchantId($pt['merchantId']);
  44. $adapter->setShopId($pt['shopId']);
  45. $this->adapters['fengniao'] = $adapter;
  46. break;
  47. case 'shunfeng':
  48. $this->adapters['shunfeng'] = new ShunfengAdapter($pt, $pt['shopId']);
  49. break;
  50. case 'dada':
  51. $this->adapters['dada'] = new DadaAdapter($pt['accessToken'], $pt['shopId'], $pt['merchantId']);
  52. //$this->adapters['dada']->setShopNo($pt['shopId']);
  53. //$this->adapters['dada']->setSourceId($pt['merchantId']); // 用 merchanId 来保存 sourceId
  54. break;
  55. case 'didi':
  56. $this->adapters['didi'] = new DidiAdapter($pt['accessToken'], $pt['mainId']);
  57. break;
  58. }
  59. //检测 token 是否即将过期
  60. $tokenExpireTime = $pt['expiresAt'];
  61. if ($tokenExpireTime < time() + 86400 * 5) {
  62. Yii::info('刷新 token: ' . $pt['platform'] . ',refreshToken: ' . $pt['refreshToken'] . ',merchantId: ' . $pt['merchantId']);
  63. $this->refreshToken($pt['platform'], $pt['refreshToken'], ['merchantId' => $pt['merchantId']]);
  64. }
  65. }
  66. } else {
  67. $authPlatform = DeliveryAuthTokenClass::getByCondition(['mainId'=>$mainId, 'platform'=>$platform]);
  68. switch ($platform) {
  69. case 'shansong':
  70. $this->adapters['shansong'] = new ShansongAdapter($authPlatform['accessToken'], $authPlatform['shopId']);
  71. break;
  72. case 'huolala':
  73. $this->adapters['huolala'] = new HuolalaAdapter($authPlatform['accessToken']);
  74. break;
  75. case 'fengniao':
  76. //$this->adapters['fengniao'] = new FengniaoAdapter($authPlatform['accessToken']);
  77. $adapter = new FengniaoAdapter($authPlatform['accessToken']);
  78. // 动态设置商户ID与门店ID
  79. $adapter->setMerchantId($authPlatform['merchantId']);
  80. $adapter->setShopId($authPlatform['shopId']);
  81. $this->adapters['fengniao'] = $adapter;
  82. break;
  83. case 'shunfeng':
  84. $this->adapters['shunfeng'] = new ShunfengAdapter($authPlatform, $authPlatform['shopId']);
  85. break;
  86. case 'dada':
  87. $this->adapters['dada'] = new DadaAdapter($authPlatform['accessToken'], $authPlatform['shopId'], $authPlatform['merchantId']);
  88. //$this->adapters['dada']->setShopNo($authPlatform['shopId']);
  89. //$this->adapters['dada']->setSourceId($authPlatform['merchantId']); // 用 merchanId 来保存 sourceId
  90. break;
  91. case 'didi':
  92. $this->adapters['didi'] = new DidiAdapter($authPlatform['accessToken'], $authPlatform['mainId']);
  93. break;
  94. }
  95. $this->platformName = $platform;
  96. if($authPlatform['expiresAt'] < time() + 86400 * 5) {
  97. Yii::info('刷新 token: ' . $platform . ',refreshToken: ' . $authPlatform['refreshToken'] . ',merchantId: ' . $authPlatform['merchantId']);
  98. $this->refreshToken($platform, $authPlatform['refreshToken'], ['merchantId' => $authPlatform['merchantId']]);
  99. }
  100. }
  101. }
  102. public function validateOrder($order)
  103. {
  104. $errors = [];
  105. if(empty($order['address'])){
  106. $errors[] = '客户地址缺失';
  107. }
  108. if(empty($order['long']) || empty($order['lat'])){
  109. $errors[] = '客户经纬度缺失';
  110. }
  111. if(empty($order['customName'])){
  112. $errors[] = '客户姓名缺失';
  113. }
  114. if(empty($order['city'])){
  115. $errors[] = '客户城市信息缺失';
  116. }
  117. if(empty($order['customMobile']) && empty($order['receiveMobile']) && empty($order['bookMobile'])){
  118. $errors[] = '客户联系电话缺失';
  119. }
  120. if(!empty($errors)){
  121. util::fail(implode(', ', $errors));
  122. }
  123. return true;
  124. }
  125. /**
  126. * @param $order
  127. * @param string $orderType 订单类型:xhOrder 或 xhGhsOrder
  128. * @param $shopId
  129. * @param $params
  130. * @return mixed
  131. */
  132. public function createOrder($order, $orderType, $shopId, $params)
  133. {
  134. $order = $order->toArray();
  135. if(!in_array($orderType, ['xhOrder', 'xhGhsOrder'])){
  136. util::fail('订单类型错误');
  137. }
  138. $shop = ShopClass::getById($shopId, false, 'id,merchantName,shopName,fullAddress,lat,long,city,dist,floor,mobile,merchantName');
  139. $adapter = $this->getAdapter();
  140. $orderData = $adapter->formatOrderData($order, $orderType, $shop, $params);
  141. return $adapter->createOrder($orderData);
  142. }
  143. /**
  144. *
  145. */
  146. public function addTip($data)
  147. {
  148. $adapter = $this->getAdapter();
  149. return $adapter->addTip($data);
  150. }
  151. /**
  152. * @param $orderId 平台订单号
  153. * @param string $thirdOrderNo xhGhsOrder.orderSn
  154. */
  155. public function selectOrder($orderId, $thirdOrderNo='')
  156. {
  157. $adapter = $this->getAdapter();
  158. if ($adapter instanceof ShansongAdapter) {
  159. $deliveryOrder = $this->getDeliveryOrder($orderId, 'shansong');
  160. return $adapter->selectOrder($deliveryOrder['orderId'], $thirdOrderNo);
  161. }
  162. if ($adapter instanceof HuolalaAdapter) {
  163. $deliveryOrder = $this->getDeliveryOrder($orderId, 'huolala');
  164. return $adapter->selectOrder($deliveryOrder['orderId']);
  165. }
  166. if ($adapter instanceof FengniaoAdapter) {
  167. $deliveryOrder = $this->getDeliveryOrder($orderId, 'fengniao');
  168. //order_id 和 partner_order_code 必填一个
  169. return $adapter->selectOrder(['order_id'=>$deliveryOrder['orderId']]);
  170. }
  171. if ($adapter instanceof ShunfengAdapter) {
  172. $deliveryOrder = $this->getDeliveryOrder($orderId, 'shunfeng');
  173. return $adapter->selectOrder($deliveryOrder['orderId']);
  174. }
  175. if ($adapter instanceof DadaAdapter) {
  176. $ghsOrder = OrderClass::getById($orderId, false, 'id,orderSn');
  177. return $adapter->selectOrder($ghsOrder['orderSn']);
  178. }
  179. if ($adapter instanceof DidiAdapter) {
  180. $deliveryOrder = $this->getDeliveryOrder($orderId, 'didi', 'id,orderId,createdAt');
  181. $timeStamp = strtoTime($deliveryOrder['createdAt']);
  182. return $adapter->selectOrder($deliveryOrder['orderId'], $thirdOrderNo, $timeStamp);
  183. }
  184. return $adapter->selectOrder($orderId);
  185. }
  186. /**
  187. * 根据订单号查找配送订单
  188. *
  189. * @param string $orderId
  190. * @return object|null
  191. */
  192. private function getDeliveryOrder($orderId, $deliveryId, $fields=null)
  193. {
  194. $fields = $fields ?? 'id,orderId';
  195. // 查找批发配送订单
  196. $deliveryOrder = GhsDeliveryOrderClass::getByCondition([
  197. 'deliveryId' => $deliveryId,
  198. 'ghsOrderId' => $orderId,
  199. 'orderStatus' => ['not in', [-1, -2]],
  200. ], false, null, $fields);
  201. if ($deliveryOrder) {
  202. return $deliveryOrder;
  203. }
  204. // 查找零售配送订单
  205. $deliveryOrder = HdDeliveryOrderClass::getByCondition([
  206. 'deliveryId' => $deliveryId,
  207. 'hdOrderId' => $orderId,
  208. 'orderStatus' => ['not in', [-1, -2]],
  209. ], false, null, $fields);
  210. if ($deliveryOrder) {
  211. return $deliveryOrder;
  212. }
  213. util::fail('未找到对应的配送订单: ' . $orderId);
  214. }
  215. public function cancelOrder($orderId, $reason)
  216. {
  217. $adapter = $this->getAdapter();
  218. return $adapter->cancelOrder($orderId, $reason);
  219. }
  220. public function getCancelReasonList($orderId)
  221. {
  222. $adapter = $this->getAdapter();
  223. return $adapter->getCancelReasonList($orderId);
  224. }
  225. public function getAdapter()
  226. {
  227. return $this->adapters[$this->platformName];
  228. }
  229. /**
  230. * 获取所有平台的报价(使用 Guzzle 并发请求)
  231. *
  232. * 流程说明:
  233. * 1. 同步准备各平台的前置数据(如城市信息、订单商品等)
  234. * 2. 使用 Guzzle Pool 并发发送各平台的报价请求(5秒超时)
  235. * 3. 某个平台失败/超时不影响其他平台,继续等待结果
  236. *
  237. * @param array $order 订单信息
  238. * @param array $shop 店铺信息
  239. * @param string $pickupTime 取件时间
  240. * @return array 返回所有平台的报价结果
  241. */
  242. public function getAllPlatformPrice($order, $shop, $pickupTime)
  243. {
  244. // 第一步:准备前置数据(同步进行,因为某些平台需要这些数据)
  245. $preparedData = $this->preparePlatformData($order, $shop, $pickupTime);
  246. if (empty($preparedData)) {
  247. return ['error' => '所有平台数据准备失败'];
  248. }
  249. // 第二步:并发调用各平台的报价接口
  250. $results = $this->concurrentGetPrices($preparedData, $pickupTime);
  251. if (empty($results['success']) && empty($results['failed'])) {
  252. return ['error' => '没有可用的物流平台'];
  253. }
  254. // 格式化返回结果
  255. return [
  256. 'quotes' => $results['success'] ?? [],
  257. 'failed' => $results['failed'] ?? [],
  258. ];
  259. }
  260. /**
  261. * 为各平台准备订单数据(前置数据同步获取)
  262. * @param array $order 订单信息
  263. * @param array $shop 店铺信息
  264. * @param string $pickupTime 取件时间
  265. * @return array 各平台的订单数据
  266. */
  267. private function preparePlatformData($order, $shop, $pickupTime)
  268. {
  269. $preparedData = [];
  270. // 准备 Huolala 数据
  271. if (isset($this->adapters['huolala'])) {
  272. try {
  273. $preparedData['huolala'] = $this->prepareHuolalaData($order, $shop);
  274. } catch (\Exception $e) {
  275. Yii::warning("Huolala 数据准备失败: {$e->getMessage()}");
  276. }
  277. }
  278. // 准备 Fengniao 数据
  279. if (isset($this->adapters['fengniao'])) {
  280. try {
  281. /** @var FengniaoAdapter $fengniaoAdapter */
  282. $fengniaoAdapter = $this->adapters['fengniao'];
  283. $platformShopId = $fengniaoAdapter->getShopId();
  284. $preparedData['fengniao'] = $this->prepareFengniaoData($order, $shop, $platformShopId);
  285. } catch (\Exception $e) {
  286. Yii::warning("Fengniao 数据准备失败: {$e->getMessage()}");
  287. }
  288. }
  289. // 准备 Shansong 数据
  290. if (isset($this->adapters['shansong'])) {
  291. try {
  292. $preparedData['shansong'] = $this->prepareShansongData($order, $shop, $pickupTime);
  293. } catch (\Exception $e) {
  294. Yii::warning("Shansong 数据准备失败: {$e->getMessage()}");
  295. }
  296. }
  297. // 准备顺丰订单数据
  298. if (isset($this->adapters['shunfeng'])) {
  299. try {
  300. /** @var ShunfengAdapter $adapter */
  301. $adapter = $this->adapters['shunfeng'];
  302. // is_person_direct -- 店铺是否支持专人直送,0不支持 1支持 2只能发独享专送
  303. $isPersonDirect = $adapter->getIsPersonDirect();
  304. if($isPersonDirect != 2){
  305. $customSettings = [];//自定义用户设置:默认不专人直送
  306. $preparedData['shunfeng'] = $this->prepareShunfengData($order, $shop, $customSettings);
  307. }
  308. //添加专人直送的订单数据
  309. if(in_array($isPersonDirect, [1, 2])){ // 支持专人直送
  310. $customSettings = ['isPersonDirect' => 1];//自定义用户设置:专人直送
  311. $preparedData['shunfeng_1v1'] = $this->prepareShunfengData($order, $shop, $customSettings);
  312. // Yii::info('预创建订单 shunfeng_1v1 request data: ' . json_encode($preparedData['shunfeng_1v1']));
  313. }
  314. // else{
  315. // $customSettings = [];//自定义用户设置:默认不专人直送
  316. // $preparedData['shunfeng'] = $this->prepareShunfengData($order, $shop, $customSettings);
  317. // }
  318. } catch (\Exception $e) {
  319. Yii::warning("Shunfeng 数据准备失败: {$e->getMessage()}");
  320. }
  321. }
  322. // 准备达达订单数据
  323. if (isset($this->adapters['dada'])) {
  324. try {
  325. $dadaAdapter = $this->adapters['dada'];
  326. $shopNo = $dadaAdapter->getShopNo();
  327. // 拼送
  328. $customSettings = ['is_direct_delivery' => 0];
  329. $preparedData['dada'] = $this->prepareDadaData($order, $shopNo, $customSettings);
  330. // 专送
  331. //$customSettings = ['is_direct_delivery' => 1];
  332. //$preparedData['dada_1v1'] = $this->prepareDadaData($order, $shopNo, $customSettings);
  333. } catch (\Exception $e) {
  334. Yii::warning("Dada 数据准备失败: {$e->getMessage()}");
  335. }
  336. }
  337. // 准备滴滴订单数据
  338. if (isset($this->adapters['didi'])) {
  339. try {
  340. $preparedData['didi'] = $this->prepareDidiData($order, $shop);
  341. } catch (\Exception $e) {
  342. Yii::warning("Didi 数据准备失败: {$e->getMessage()}");
  343. }
  344. }
  345. return $preparedData;
  346. }
  347. /**
  348. * 准备货拉拉订单数据
  349. */
  350. private function prepareHuolalaData($order, $shop)
  351. {
  352. $formatCity = rtrim($order['city'], '市');
  353. $cities = include Yii::getAlias('@common/components/delivery/platform/huolala/cities.php');
  354. if (!isset($cities[$formatCity])) {
  355. throw new \Exception('城市编码表中没有找到城市: ' . $formatCity);
  356. }
  357. $cityId = $cities[$formatCity]['city_id'];
  358. $cityVehicleList = $this->adapters['huolala']->getCityVehicleList($cityId); // 产生外部请求
  359. $cityInfoRevision = $cityVehicleList['city_info_revision']; // 城市版本号
  360. $vehicleList = $cityVehicleList['vehicle_list']; // 所有车型列表
  361. if (empty($vehicleList)) {
  362. throw new \Exception('没有找到可选车型');
  363. }
  364. // 解析额外需求
  365. $specReqItem = $cityVehicleList['spec_req_item'] ?? [];
  366. $specReq = [];
  367. foreach ($specReqItem as $item) {
  368. $specReq[] = $item['type'] ?? null;
  369. }
  370. $specReq = array_filter($specReq);
  371. // 构建所需车型数据
  372. $vehicleTypeList = [];
  373. foreach ($vehicleList as $vehicle) {
  374. if(!in_array($vehicle['vehicle_name'], ['跑腿', '小面', '微面'])){ // && !$this->adapters['huolala']->getIsSandbox()
  375. continue;
  376. }
  377. $vehicleStd = [];
  378. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : "";
  379. $vehicleTypeList[$vehicle['order_vehicle_id']] = [
  380. 'order_vehicle_id' => $vehicle['order_vehicle_id'],
  381. 'city_info_revision' => $cityInfoRevision,
  382. 'order_time' => time() + 600,
  383. 'addr_info' => [
  384. [
  385. 'name' => $shop['merchantName'],
  386. 'addr' => $shop['fullAddress'],
  387. 'city_id' => $cityId,
  388. 'city_name' => $shop['city'],
  389. 'district_name' => $shop['dist'],
  390. 'house_number' => $shop['floor'],
  391. 'contacts_name' => $shop['mobile'],
  392. 'contacts_phone_no' => $shop['mobile'],
  393. 'lat_lon' => ['lat' => (float)$shop['lat'], 'lon' => (float)$shop['long']],
  394. ],
  395. [
  396. 'name' => empty($order['showAddress']) ? $order['customName'] : $order['showAddress'],
  397. 'addr' => $order['fullAddress'],
  398. 'city_id' => $cityId,
  399. 'city_name' => $order['city'],
  400. 'district_name' => $order['dist'],
  401. 'house_number' => $order['floor'],
  402. 'contacts_name' => $order['customName'],
  403. 'contacts_phone_no' => Functions::getMobile($order),
  404. 'lat_lon' => ['lat' => (float)$order['lat'], 'lon' => (float)$order['long']],
  405. ]
  406. ],
  407. 'vehicle_std' => $vehicleStd,
  408. 'spec_req' => array_values($specReq),
  409. //'coupon_id' => 0, // 优惠券信息,可以传指定券id,如果不传则会默认用最优券,如果不想用券则传0。下单时的券id需要和估价的策略一样,估价命中最优券,下单就必须传券id。不想用券就都传0
  410. 'invoice_type' => 1,
  411. 'order_service_type' => 1,
  412. '_meta' => [
  413. 'vehicle_type' => $vehicle['vehicle_name'],
  414. 'city_info_revision' => $cityInfoRevision,
  415. ]
  416. ];
  417. }
  418. return [
  419. 'platform' => 'huolala',
  420. 'city_id' => $cityId,
  421. 'vehicle_type_list' => $vehicleTypeList,
  422. ];
  423. }
  424. /**
  425. * 准备蜂鸟订单数据
  426. */
  427. private function prepareFengniaoData($order, $shop, $platformShopId)
  428. {
  429. // $this->adapters['fengniao']->setMerchantId(14594092); // adapter 创建时已经设置了
  430. $goodsItemList = [];
  431. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num');
  432. foreach ($itemInfos as $item) {
  433. $goodsItemList[] = [
  434. 'item_actual_amount_cent' => (int)($item['unitPrice'] * 100 * $item['num']),
  435. 'item_amount_cent' => (int)($item['unitPrice'] * 100),
  436. 'item_id' => $item['id'],
  437. 'item_name' => $item['name'],
  438. 'item_quantity' => $item['num'],
  439. ];
  440. }
  441. return [
  442. 'platform' => 'fengniao',
  443. 'partner_order_code' => $order['orderSn'],
  444. 'receiver_primary_phone' => Functions::getMobile($order),
  445. 'receiver_name' => $order['customName'],
  446. 'receiver_latitude' => (float)$order['lat'],
  447. 'receiver_longitude' => (float)$order['long'],
  448. 'receiver_address' => $order['fullAddress'],
  449. 'position_source' => 3, //坐标经纬度来源(1:腾讯地图,2:百度地图, 3:高德地图)
  450. 'goods_count' => count($goodsItemList),
  451. 'goods_weight' => (float)$order['weight'],
  452. 'goods_total_amount_cent' => (int)($order['actPrice'] * 100),
  453. 'goods_actual_amount_cent' => (int)($order['prePrice'] * 100),
  454. 'goods_item_list' => $goodsItemList,
  455. //'order_type' => 1,
  456. 'chain_store_id' => $platformShopId, // 蜂鸟平台 shopId
  457. 'order_remark' => $order['remark'] ?? '',
  458. ];
  459. }
  460. /**
  461. * 准备闪送订单数据
  462. */
  463. private function prepareShansongData($order, $shop, $pickupTime)
  464. {
  465. $data = [
  466. 'platform' => 'shansong',
  467. 'cityName' => $shop['city'],
  468. 'sender' => [
  469. 'fromAddress' => $shop['address'],
  470. 'fromAddressDetail' => $shop['floor'],
  471. 'fromSenderName' => $shop['shopName'] == '首店' ? $shop['merchantName'] : $shop['merchantName'].'-'.$shop['shopName'],
  472. 'fromMobile' => $shop['mobile'],
  473. 'fromLatitude' => (string)$shop['lat'],
  474. 'fromLongitude' => (string)$shop['long'],
  475. ],
  476. 'receiverList' => [
  477. [
  478. 'orderNo' => $order['orderSn'],
  479. 'toAddress' => $order['address'],
  480. 'toAddressDetail' => $order['floor'],
  481. 'toReceiverName' => $order['customName'],
  482. 'toMobile' => Functions::getMobile($order),
  483. 'toLatitude' => (string)$order['lat'],
  484. 'toLongitude' => (string)$order['long'],
  485. 'goodType' => 7, //鲜花
  486. 'weight' => (int)round($order['weight']),
  487. 'remarks' => $order['remark'] ?? '',
  488. ]
  489. ],
  490. 'appointType' => 0, //预约类型: 0立即单,1预约单
  491. 'travelWay' => 0,
  492. 'deliveryType' => 1,
  493. //补充额外的订单数据
  494. 'sendNum' => $order['sendNum'] ?? '',
  495. ];
  496. $timestamp = strtotime($pickupTime);
  497. $currentTime = time() + 3600;
  498. if($timestamp > $currentTime){
  499. $data['appointType'] = 1; // 修改成 1预约单
  500. $data['appointmentDate'] = $pickupTime; // 预约时间, yyyy-MM-dd HH:mm格式(例如:2020-02-02 22:00),指的是预约取件时间,只支持一个小时以后
  501. //两天以内
  502. if($timestamp > time() + 172800){
  503. throw new \Exception('取件时间不能超过两天');
  504. }
  505. // 'expectStartTime' 期望送达时间起始时间 -- 毫秒级时间戳。期望送达时间为时间点时,无需传本参数;期望送达时间为时间段时,期望送达时间为expectStartTime至expectEndTime
  506. // 'expectEndTime' 期望送达时间终止时间 -- 毫秒级时间戳。期望送达时间为时间点时,只需传本参数;期望送达时间为时间段时,期望送达时间为expectStartTime至expectEndTime
  507. $data['receiverList'][0]['expectStartTime'] = ($timestamp + 900) * 1000;
  508. $data['receiverList'][0]['expectEndTime'] = ($timestamp + 1800) * 1000;
  509. }
  510. return $data;
  511. }
  512. /**
  513. * 准备顺丰订单数据
  514. */
  515. private function prepareShunfengData($order, $shop, $customSettings)
  516. {
  517. // 获取订单商品信息
  518. // $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, unitWeight');
  519. // 计算商品总重量(单位:克)
  520. // $totalWeight = 0;
  521. // foreach ($itemInfos as $item) {
  522. // $totalWeight += (int)($item['unitWeight'] * $item['num']) * 1000;
  523. // }
  524. // 如果没有商品重量,使用订单重量
  525. // if ($totalWeight == 0 && isset($order['weight'])) {
  526. // $totalWeight = (int)$order['weight'] * 1000;
  527. // }
  528. // 默认重量为1000克(1公斤)
  529. // if ($totalWeight == 0) {
  530. // $totalWeight = 1000;
  531. // }
  532. return [
  533. 'platform' => 'shunfeng',
  534. 'user_lng' => (string)$order['long'], // 用户地址经度
  535. 'user_lat' => (string)$order['lat'], // 用户地址纬度
  536. 'user_address' => $order['fullAddress'], // 用户详细地址
  537. 'weight' => $order['weight'] * 1000, // 物品重量(单位:克)
  538. 'product_type' => 14, // 物品类型(14:鲜花)
  539. 'push_time' => time(), // 推单时间(秒级时间戳)
  540. //shop 平台级开发者需要传入
  541. // 'shop' => [ // 发货店铺信息
  542. // 'shop_name' => $shop['merchantName'], // 店铺名称
  543. // 'shop_address' => $shop['fullAddress'], // 店铺地址
  544. // 'shop_lng' => (string)$shop['long'], // 店铺经度
  545. // 'shop_lat' => (string)$shop['lat'], // 店铺纬度
  546. // 'shop_phone' => $shop['mobile'], // 店铺联系电话
  547. // ],
  548. //-------------------------- 非必填 -------------------------------
  549. 'city_name' => $order['city'], // 发单城市
  550. //'order_source' => '6', // 订单接入来源(6:京东秒送,可自定义)
  551. 'source_origin_order_id' => $order['orderSn'], // 商流订单号
  552. 'total_price' => (int)($order['actPrice'] * 100), // 用户订单总金额(单位:分)
  553. 'is_appoint' => 0, // 是否预约单(0:非预约单)
  554. //'appoint_type' => 0, // 预约单的时候传入,1:预约送达单;2:预约上门单
  555. //'expect_pickup_time' => 0, // TODO 用户期望上门时间 -- appoint_type=2时需必传,秒级时间戳
  556. //'expect_time' => 0, // TODO 用户期望送达时间
  557. //'shop_expect_time' => 0, // TODO 商家期望送达时间 -- 格式为:{timestamp},
  558. 'lbs_type' => 2, // 坐标类型(2:高德坐标)
  559. 'is_insured' => 0, // 是否保价(0:非保价)
  560. 'is_person_direct' => $customSettings['isPersonDirect'] ?? 0, // 是否专人直送(0:否 1:是)
  561. 'vehicle' => 0, // 配送交通工具,0:否;1:电动车;2:小轿车
  562. //'four_wheeler_type' => 0, // 车型 -- 只有vehicle = 2,⻋型字段才有效。
  563. //'declared_value' => 0, // 保价金额(单位:分)
  564. //'gratuity_fee' => 0, // 订单小费(单位:分)
  565. 'rider_pick_method' => 1, // 物流流向(1:从门店取件送至用户)
  566. 'return_flag' => 511, // 返回字段控制标志位(511:全部返回)
  567. 'multi_pickup_info' => [], // 多点取货信息(暂不使用)
  568. ];
  569. }
  570. /**
  571. * 准备达达订单数据
  572. */
  573. private function prepareDadaData($order, $shopNo, $customSettings)
  574. {
  575. $productList = [];
  576. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, bigNum, smallNum, xhUnitName');
  577. foreach ($itemInfos as $item) {
  578. $productList[] = [
  579. 'sku_name' => $item['name'],
  580. 'src_product_no' => (string)$item['id'],
  581. 'count' => (float)$item['num'],
  582. 'unit' => $item['xhUnitName'],
  583. ];
  584. }
  585. // 回调地址
  586. $callbackUrl = Yii::$app->params['ghsHost'] . '/delivery/dada-callback';
  587. $request = [
  588. 'platform' => 'dada',
  589. 'shop_no' => $shopNo,
  590. 'origin_id' => $order['orderSn'],
  591. 'cargo_price' => (float)$order['actPrice'],
  592. 'is_prepay' => 0, // 是否需要垫付 1:是 0:否 (垫付订单金额,非运费)
  593. 'receiver_name' => $order['customName'],
  594. 'receiver_address' => $order['fullAddress'],
  595. 'receiver_lat' => (float)$order['lat'],
  596. 'receiver_lng' => (float)$order['long'],
  597. 'callback' => $callbackUrl,
  598. 'cargo_weight' => isset($order['weight']) ? (float)$order['weight'] : 1.0,
  599. 'receiver_phone' => Functions::getMobile($order),
  600. //'tips' => 0, //小费(单位:元,精确小数点后一位,小费金额不能高于订单金额。)
  601. 'info' => $order['remark'] ?? '',
  602. 'product_list' => $productList,
  603. ];
  604. if(isset($customSettings['is_direct_delivery']) && $customSettings['is_direct_delivery'] == 1){
  605. // $request['origin_id'] = $order['orderSn'] . '_1v1'; // 根据达达的情况,必然会造成订单号出错
  606. $request['is_direct_delivery'] = 1; //是否选择直拿直送(0:不需要;1:需要。选择直拿直送后,同一时间骑士只能配送此订单至完成,同时,也会相应的增加配送费用)
  607. }
  608. return $request;
  609. }
  610. /**
  611. * 准备滴滴订单数据
  612. */
  613. private function prepareDidiData($order, $shop)
  614. {
  615. return [
  616. 'platform' => 'didi',
  617. 'sender' => [
  618. 'fromSenderName' => $shop['merchantName'],
  619. 'fromMobile' => $shop['mobile'],
  620. 'fromAddress' => $shop['address'],
  621. 'fromAddressDetail' => $shop['floor'],
  622. 'fromLatitude' => (float)$shop['lat'],
  623. 'fromLongitude' => (float)$shop['long'],
  624. ],
  625. 'receiverList' => [
  626. [
  627. 'toReceiverName' => $order['customName'],
  628. 'toMobile' => Functions::getMobile($order),
  629. 'toAddress' => $order['address'],
  630. 'toAddressDetail' => $order['floor'],
  631. 'toLatitude' => (float)$order['lat'],
  632. 'toLongitude' => (float)$order['long'],
  633. 'weight' => isset($order['weight']) ? (float)$order['weight'] : 1.0,
  634. 'goodType' => 8,
  635. ]
  636. ]
  637. ];
  638. }
  639. /**
  640. * 并发获取各平台报价(核心实现)
  641. *
  642. * 使用 HttpClient::postConcurrent 实现真正的并发调用,每个平台请求 10 秒超时。
  643. * 某个平台的超时或失败不会影响其他平台的执行。
  644. *
  645. * @param array $preparedData 准备好的各平台数据
  646. * @param string $orderTime 配送时间
  647. * @return array 包含成功和失败结果
  648. */
  649. private function concurrentGetPrices($preparedData, $orderTime)
  650. {
  651. $results = [
  652. 'success' => [],
  653. 'failed' => [],
  654. ];
  655. // 第一步:收集所有平台的请求信息
  656. $allRequests = [];
  657. $platformMapping = []; // 用于将请求标识映射回平台名称
  658. foreach ($preparedData as $platform => $data) {
  659. try {
  660. $adapterKey = $platform; //由于要支持特殊逻辑处理,把 $this->adapters[xxx] 的 xxx 单独取变量
  661. if (!isset($this->adapters[$platform])) {
  662. if (substr($platform, -4) === '_1v1') { //特殊处理 -- 专人直送的订单,使用对应平台适配器
  663. $adapterKey = substr($platform, 0, -4);
  664. } else {
  665. $results['failed'][$platform] = '平台适配器未初始化';
  666. Yii::warning("[DispatchService] {$platform} 平台适配器未初始化");
  667. continue;
  668. }
  669. }
  670. $adapter = $this->adapters[$adapterKey];
  671. // 根据平台类型调用相应的 buildPriceRequest(s) 方法
  672. if ($platform === 'huolala') {// 货拉拉返回多个请求(一个请求对应一个车型)
  673. $priceRequests = $adapter->buildPriceRequest($data, $orderTime);
  674. foreach ($priceRequests as $requestKey => $requestInfo) {
  675. $allRequests[$requestKey] = $requestInfo;
  676. $platformMapping[$requestKey] = ['platform' => 'huolala', 'data' => $data];
  677. }
  678. } else {
  679. // 其他平台各返回一个请求
  680. $requestInfo = $adapter->buildPriceRequest($data, $orderTime);
  681. $requestKey = "{$platform}_quote";
  682. $allRequests[$requestKey] = $requestInfo;
  683. $platformMapping[$requestKey] = ['platform' => $platform, 'data' => $data];
  684. }
  685. } catch (\Throwable $e) {
  686. $results['failed'][$platform] = "构建请求失败: {$e->getMessage()}";
  687. Yii::error("[DispatchService] {$platform} 构建请求异常: {$e->getMessage()}");
  688. }
  689. }
  690. if (empty($allRequests)) {
  691. return $results;
  692. }
  693. // 第二步:使用 postConcurrent 并发发送所有请求
  694. $startTime = microtime(true);
  695. $concurrentResults = HttpClient::postConcurrent($allRequests, 3);
  696. $totalDuration = microtime(true) - $startTime;
  697. Yii::info("[DispatchService] 所有报价请求完成 (" . round($totalDuration * 1000) . "ms)");
  698. // 第三步:处理并发请求的结果
  699. foreach ($concurrentResults['success'] as $requestKey => $response) {
  700. if (!isset($platformMapping[$requestKey])) {
  701. continue;
  702. }
  703. $mapping = $platformMapping[$requestKey];
  704. $platform = $mapping['platform'];
  705. $data = $mapping['data'];
  706. try {
  707. $adapterKey = $platform; //由于要支持特殊逻辑处理,把 $this->adapters[xxx] 的 xxx 单独取变量
  708. if (substr($platform, -4) === '_1v1') { //特殊处理 -- 专人直送的订单,使用对应平台适配器
  709. $adapterKey = substr($platform, 0, -4);
  710. }
  711. $adapter = $this->adapters[$adapterKey];
  712. $quote = null;
  713. if ($platform === 'huolala') {
  714. // 货拉拉的响应处理
  715. $quote = $adapter->processPriceResponse($response);
  716. if ($quote && !isset($results['success']['huolala'])) {
  717. // 第一次处理货拉拉的结果,初始化
  718. $results['success']['huolala'] = [
  719. 'platform' => 'huolala',
  720. 'city_id' => $data['city_id'],
  721. 'vehicle_type_list' => $data['vehicle_type_list'],
  722. 'price_info_list' => [],
  723. ];
  724. }
  725. $keyArr = explode('_', $requestKey);
  726. $vehicle_type_list_key = $keyArr[2];
  727. // 将该车型的报价加入到列表中
  728. if ($quote && isset($results['success']['huolala'])) {
  729. $results['success']['huolala']['price_info_list'][] = [
  730. 'calculate_price_info' => isset($quote['calculate_price_info_list']) ? $quote['calculate_price_info_list'][0] : [],
  731. 'vehicle_type' => $data['vehicle_type_list'][$vehicle_type_list_key]
  732. ];
  733. Yii::info("[DispatchService] {$platform} 报价成功");// . json_encode($quote));
  734. } else {
  735. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  736. $results['failed'][$platform] = $errorMsg;
  737. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  738. }
  739. } else {
  740. // 响应处理
  741. $quote = $adapter->processPriceResponse($response);
  742. if ($quote && !isset($quote['error'])) {
  743. $quote['_duration'] = $totalDuration;
  744. $results['success'][$platform] = $quote;
  745. Yii::info("[DispatchService] {$platform} 报价成功");// . json_encode($quote));
  746. } else {
  747. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  748. $results['failed'][$platform] = $errorMsg;
  749. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  750. if(strncmp($platform, 'shunfeng', 8) === 0) {
  751. /** @var ShunfengAdapter $adapter */
  752. if($errorMsg == '暂未开启专人直送服务') {
  753. $adapter->getShopInfo();
  754. }
  755. if($errorMsg == '当前店铺只能发独享专送') {
  756. $adapter->getShopInfo();
  757. }
  758. }
  759. }
  760. }
  761. } catch (\Throwable $e) {
  762. $results['failed'][$platform] = "处理响应失败: {$e->getMessage()}";
  763. Yii::error("[DispatchService] {$platform} 处理响应异常: {$e->getMessage()}");
  764. }
  765. }
  766. // 第四步:处理失败的请求
  767. foreach ($concurrentResults['failed'] as $requestKey => $errorMsg) {
  768. if (!isset($platformMapping[$requestKey])) {
  769. continue;
  770. }
  771. $platform = $platformMapping[$requestKey]['platform'];
  772. // 对于货拉拉,只记录某个车型失败,不影响整体平台状态
  773. if ($platform === 'huolala') {
  774. Yii::warning("[DispatchService] huolala 车型报价失败 ({$requestKey}): {$errorMsg}");
  775. } else {
  776. if (!isset($results['failed'][$platform])) {
  777. $results['failed'][$platform] = $errorMsg;
  778. Yii::error("[DispatchService] {$platform} 报价请求失败: {$errorMsg}");
  779. }
  780. }
  781. }
  782. // 为货拉拉添加元数据
  783. if (isset($results['success']['huolala'])) {
  784. $results['success']['huolala']['_duration'] = $totalDuration;
  785. }
  786. return $results;
  787. }
  788. public function openCitiesLists($platform)
  789. {
  790. $ap = $this->adapters[$platform];
  791. return $ap->cityList();
  792. }
  793. /**
  794. * 刷新 token
  795. */
  796. public function refreshToken($platform, $refreshToken, $data=[])
  797. {
  798. switch($platform) {
  799. case 'shansong':
  800. $auth = new \common\components\delivery\platform\shansong\Auth();
  801. $auth->refreshAccessToken($refreshToken);
  802. break;
  803. case 'huolala':
  804. $auth = new \common\components\delivery\platform\huolala\Auth();
  805. $auth->refreshAccessToken($refreshToken);
  806. break;
  807. case 'fengniao':
  808. $auth = new \common\components\delivery\platform\fengniao\Auth();
  809. $auth->refreshAccessToken($refreshToken, $data['merchantId']);
  810. break;
  811. case 'shunfeng':
  812. $auth = new \common\components\delivery\platform\shunfeng\Auth();
  813. $auth->refreshAccessToken($refreshToken);
  814. break;
  815. }
  816. }
  817. /**
  818. * 格式化各平台报价为前端展示格式
  819. *
  820. * @param array $platformQuotes 各平台报价结果(来自 getAllPlatformPrice)
  821. * @return array 格式化后的配送列表
  822. */
  823. public function formatPlatformQuotesForDisplay($platformQuotes)
  824. {
  825. $deliveryList = [];
  826. if (empty($platformQuotes['quotes'])) {
  827. return $deliveryList;
  828. }
  829. foreach ($platformQuotes['quotes'] as $platformKey => $item) {
  830. if(!isset($item['platform'])){
  831. Yii::error(json_encode($item));
  832. continue;
  833. }
  834. switch ($item['platform']) {
  835. case 'shunfeng':
  836. $deliveryList[] = [
  837. 'name' => '顺丰' . ($platformKey == 'shunfeng_1v1' ? ' (专送)' : ''),
  838. 'en_name' => 'shunfeng',
  839. 'price' => $item['real_pay_money'],
  840. 'distance' => $item['distance'],
  841. 'type' => '' . ($platformKey == 'shunfeng_1v1' ? '专人直送' : ''),
  842. 'isAble' => true
  843. ];
  844. break;
  845. case 'shansong':
  846. $deliveryList[] = [
  847. 'name' => '闪送',
  848. 'en_name' => 'shansong',
  849. 'price' => $item['total_amount'],
  850. 'distance' => $item['total_distance'],
  851. 'type' => '',
  852. 'issOrderNo' => $item['order_number'],
  853. 'isAble' => true
  854. ];
  855. break;
  856. case 'fengniao':
  857. // 循环遍历 goods_infos 数组,提取有效项的信息
  858. $validGoods = [];
  859. if (!empty($item['goods_infos']) && is_array($item['goods_infos'])) {
  860. foreach ($item['goods_infos'] as $good) {
  861. if (!empty($good['is_valid']) && $good['is_valid'] == 1) {
  862. $validGoods[] = [
  863. 'actual_delivery_amount_cent' => $good['actual_delivery_amount_cent'] ?? 0,
  864. 'service_goods_id' => $good['service_goods_id'] ?? ''
  865. ];
  866. $deliveryList[] = [
  867. 'name' => '蜂鸟'. ' (' .$good['base_goods_id'] . ')',
  868. 'base_goods_id' => $good['base_goods_id'],
  869. 'en_name' => 'fengniao',
  870. 'price' => $good['actual_delivery_amount_cent'],
  871. 'distance' => $item['distance'],
  872. 'valid_goods' => $validGoods,
  873. 'type' => $good['slogan'],
  874. 'isAble' => true
  875. ];
  876. } else {
  877. $deliveryList[] = [
  878. 'name' => '蜂鸟'. ' (' .$good['base_goods_id'] . ')',
  879. 'base_goods_id' => $good['base_goods_id'],
  880. 'en_name' => 'fengniao',
  881. 'price' => 0,
  882. 'distance' => $item['distance'],
  883. 'valid_goods' => $good,
  884. 'type' => $good['disable_reason'],
  885. 'isAble' => false
  886. ];
  887. }
  888. }
  889. }
  890. break;
  891. case 'huolala':
  892. foreach($item['price_info_list'] as $key => $arr) {
  893. $priceInfo = $arr['calculate_price_info'];
  894. $priceConditions = $priceInfo['price_conditions'] ?? []; //价格明细
  895. $distanceInfo = $priceInfo['distance_info'] ?? []; //距离信息
  896. $vehicleType = $arr['vehicle_type'];
  897. if(empty($priceConditions)){
  898. Yii::error('货拉拉 报价数据 priceConditions 为空:' . json_encode($item) . ' key: ' . $key);
  899. continue;
  900. }
  901. if(empty($distanceInfo)){
  902. Yii::warning('货拉拉 报价数据 distanceInfo 为空:' . json_encode($item) . ' key: ' . $key);
  903. }
  904. $priceCalculateId = $priceInfo['price_calculate_id'] ?? 0;
  905. if(!isset($priceInfo['price_calculate_id'])){
  906. Yii::warning('货拉拉 报价数据 priceInfo 缺少 price_calculate_id:' . json_encode($priceInfo) . ' key: ' . $key);
  907. }
  908. //车型信息
  909. $vehicleAttr = $priceInfo['vehicle_info']['vehicle_attr'] ?? 0;
  910. if(!isset($priceInfo['vehicle_info']['vehicle_attr'])){
  911. Yii::info('货拉拉 报价数据 vehicleAttr 为空:' . ' key: ' . $key); //json_encode($priceInfo) .
  912. }
  913. $priceCondition = !empty($priceConditions) ? $priceConditions[0] : [];
  914. $priceInfoData = $priceCondition['price_info'] ?? [];
  915. $huolalaPrice = $priceInfoData['total_price'] ?? 0;
  916. $couponId = $this->extractHuolalaCouponId($priceConditions);
  917. $deliveryList[] = [
  918. 'name' => '货拉拉' . ' (' . $vehicleType['_meta']['vehicle_type'] . ')',
  919. 'vehicle_type' => $vehicleType['_meta']['vehicle_type'],
  920. 'en_name' => 'huolala',
  921. 'price' => $huolalaPrice,
  922. 'distance' => !empty($distanceInfo) ? $distanceInfo['distance_total'] : 0,
  923. 'type' => $vehicleType['_meta']['vehicle_type'],
  924. 'isAble' => true,
  925. // ---------------------------------------------
  926. 'order_vehicle_id' => $vehicleType['order_vehicle_id'],
  927. 'city_id' => $item['city_id'],
  928. 'city_info_revision' => $vehicleType['city_info_revision'],
  929. // 下单需要透传的数据
  930. 'vehicle_std' => $vehicleType['vehicle_std'],
  931. 'spec_req' => $vehicleType['spec_req'],
  932. 'addr_info' => $vehicleType['addr_info'],
  933. 'order_time' => $vehicleType['order_time'],
  934. 'invoice_type' => $vehicleType['invoice_type'],
  935. 'total_price_fen' => $huolalaPrice,
  936. 'price_calculate_id' => $priceCalculateId,
  937. 'price_item_encryption' => $priceCondition['price_item_encryption'] ?? '',
  938. 'vehicle_attr' => $vehicleAttr,
  939. 'commodity_info' => $priceCondition['commodity_item'] ?? [],
  940. ];
  941. if (!empty($couponId)) {
  942. $deliveryList[count($deliveryList) - 1]['coupon_id'] = $couponId;
  943. }
  944. }
  945. break;
  946. case 'dada':
  947. $list = [
  948. 'name' => '达达'. ($platformKey == 'dada_1v1' ? ' (专送)' : ''),
  949. 'en_name' => 'dada',
  950. 'price' => $item['fee'],
  951. 'distance' => $item['distance'],
  952. 'type' => '',
  953. 'isAble' => true,
  954. // ---------------------------------------------
  955. 'deliverFee' => $item['deliverFee'],
  956. 'deliveryNo' => $item['deliveryNo'],
  957. ];
  958. if(isset($item['couponName']) && isset($item['couponFee'])){
  959. $list['couponName'] = $item['couponName'];
  960. $list['couponFee'] = $item['couponFee'];
  961. }
  962. $deliveryList[] = $list;
  963. break;
  964. case 'didi':
  965. if(!isset($item['estimateList'])){
  966. Yii::error('didi 报价数据为空:' . json_encode($item));
  967. continue 2;
  968. }
  969. $serviceType = [0 => '拼送', 1 => '直送'];
  970. foreach($item['estimateList'] as $arr) {
  971. $serType = $arr['serviceType'] ?? null;
  972. $type = empty($serType) ? '' : $serviceType[$serType]; //服务类型
  973. $deliveryList[] = [
  974. 'name' => '滴滴' . ' (' . $this->adapters['didi']->carType($arr['carType']) . $type . ')',
  975. 'en_name' => 'didi',
  976. 'price' => $arr['fee'],
  977. 'distance' => $arr['distance'],
  978. 'type' => $type,
  979. 'isAble' => true,
  980. // ---------------------------------------------
  981. 'estimateId' => $arr['estimateId'],
  982. 'bizType' => $arr['bizType'],
  983. 'discountFee' => $arr['discountFee'],
  984. 'icon' => $arr['icon']
  985. ];
  986. }
  987. break;
  988. }
  989. }
  990. return $deliveryList;
  991. }
  992. private function extractHuolalaCouponId($priceConditions)
  993. {
  994. if (empty($priceConditions) || !is_array($priceConditions)) {
  995. return null;
  996. }
  997. foreach ($priceConditions as $condition) {
  998. $couponId = $condition['coupon_info']['coupon_id'] ?? null;
  999. if (!empty($couponId)) {
  1000. return (string)$couponId; //转换为字符串,以免在传递过程中丢失精度(包括传递给前端时)
  1001. }
  1002. }
  1003. return null;
  1004. }
  1005. }