Take.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. namespace app\controller\api\douhuomall;
  3. use app\traits\GongApiRequest;
  4. use think\Exception;
  5. use think\facade\Db;
  6. use think\facade\Log;
  7. class Take
  8. {
  9. use GongApiRequest;
  10. /**
  11. * 同步 微唯宝 商品数据
  12. * @return string
  13. */
  14. public function get_goods_list()
  15. {
  16. try {
  17. // 1、不设置超时
  18. set_time_limit(0);
  19. // 2、循环拉取 商品 数据
  20. $allData = [];
  21. $page = 1;
  22. $limit = 100;
  23. $hasNextPage = true; // 是否有下一页的标志
  24. while ($hasNextPage) {
  25. $data = GongApiRequest::get_goods_list($page, $limit);
  26. if (!$data) {
  27. break; // 如果请求失败,停止循环
  28. }
  29. $allData = array_merge($allData, $data['list']); // 数据在list键下
  30. if (!count($data['list']) || count($data['list']) < $limit) {
  31. $hasNextPage = false; // 如果没有更多页面,停止循环
  32. } else {
  33. $page++; // 增加页码数
  34. }
  35. }
  36. // 3、获取 微唯宝 商品表 SPUId集合
  37. $goods_id_list = [];
  38. $spu_id_list = Db::name('douhuomall')->column('spu_id');
  39. // 4、
  40. // 同步到数据库
  41. foreach ($allData as $key => $value) {
  42. sleep(1);
  43. // if($key != 0) continue;
  44. // 4.1 获取商品详情
  45. $goodsInfo = GongApiRequest::get_goods_info($value['goods_id']);
  46. if (!$goodsInfo) continue;
  47. // 4.2 图片存放路径
  48. $targetDir = public_path() . 'images/gong/' . $value['goods_id'] . '/';
  49. // 4.3 清空路径下的文件
  50. $this->deleteFilesInDirectory($targetDir);
  51. // 4.4 获取图片地址 spuId_info商品详细信息处理
  52. $goodsInfo['cover_url'] = $this->seveImg($value['goods_id'], $goodsInfo['main_img'], $targetDir);
  53. $goodsInfo['spu_id'] = $goodsInfo['goods_id'];
  54. $goodsInfo['detail'] = "";
  55. $detail_img = $this->seveImg($value['goods_id'], $goodsInfo['detail_img'], $targetDir);
  56. foreach ($detail_img as $img_url) {
  57. $img_url = "<img src='" . $img_url . "' referrerpolicy='no-referrer' />";
  58. $goodsInfo['detail'] = $goodsInfo['detail'] . $img_url;
  59. }
  60. //sku信息处理
  61. $skuInfo = $goodsInfo['sku_list'];
  62. foreach ($skuInfo as $k => $v) {
  63. $skuInfo[$k]['img_url'] = $this->seveImg($value['goods_id'], $v['main_img'], $targetDir);//规格图片
  64. $skuInfo[$k]['cost_price'] = bcadd($v['plat_price'], bcmul($v['plat_price'], 0.03, 2), 2);//成本价格 原来进价的基础上加百分之3
  65. $skuInfo[$k]['market_price'] = bcadd($skuInfo[$k]['cost_price'], bcmul($skuInfo[$k]['cost_price'], 0.2, 2), 2);//销售价格 售价在成本价格的基础上加百分20
  66. $skuInfo[$k]['profit'] = bcdiv($skuInfo[$k]['market_price'], $skuInfo[$k]['cost_price'], 2);
  67. $skuInfo[$k]['mer_profit'] = bcsub($skuInfo[$k]['market_price'], $skuInfo[$k]['cost_price'], 2);
  68. $skuInfo[$k]['yanglaojin'] = '0.00';
  69. if (count($v['attr'])) {
  70. $skuInfo[$k]['attribute_json'] = $v['attr'];
  71. } else {
  72. $skuInfo[$k]['attribute_json'] = [['val' => '默认', 'name' => '默认']];
  73. }
  74. }
  75. unset($goodsInfo['sku_list']);
  76. $seveData = [
  77. 'spu_id' => $goodsInfo['spu_id'],
  78. 'skuId_info' => $skuInfo,
  79. 'sys_id' => '112',
  80. 'goods_id' => $goodsInfo['goods_id'],
  81. 'spuId_info' => $goodsInfo,
  82. 'sku_id' => $skuInfo[0]['sku_id'] ? $skuInfo[0]['sku_id'] : 0,
  83. 'status' => $goodsInfo['status'],
  84. 'cate_ids' => $goodsInfo['cate_ids'],
  85. 'title' => $goodsInfo['spu_name'],
  86. 'cxb_cate_id' => 0,
  87. ];
  88. // 4.5 保存商品信心到本地
  89. $this->add($seveData);
  90. $goods_id_list[] = $goodsInfo['spu_id'];
  91. // 4.6 如果上架到商品表 则更新商品表的图片
  92. $this->updata_product_img($goodsInfo['spu_id']);
  93. }
  94. // 5、将 未同步到的商品 进行下架
  95. $goodsIds = array_diff($spu_id_list, $goods_id_list);
  96. $this->remove($goodsIds);
  97. return 'sussess';
  98. } catch (Exception $e) {
  99. Log::error('供应链拉取数据:' . $e->getFile() . ':' . $e->getLine() . '【' . $e->getMessage() . '】');
  100. echo '供应链拉取数据:' . $e->getFile() . ':' . $e->getLine() . '【' . $e->getMessage() . '】';
  101. Db::name('log')->insert(['data' => '供应链拉取数据:' . $e->getFile() . ':' . $e->getLine() . '【' . $e->getMessage() . '】']);
  102. return 'error';
  103. }
  104. }
  105. public function updata_product_img($spu_id)
  106. {
  107. // 1、验证该 SPUId 是否上架了 如果上架了 需要去更新商品 图片
  108. $product_id = Db::name('store_product')->where('spu_id', $spu_id)->value('product_id');
  109. if (!$product_id) return true;
  110. // 2、查找微唯宝 商品
  111. $data = Db::name('douhuomall')->where('spu_id', $spu_id)->find();
  112. // 3、获取 商品主图
  113. $spuId_info = json_decode($data['spuId_info'], true);
  114. $slider_image = $spuId_info['detail_img_list'] ?? '';
  115. $image = $spuId_info['cover_url'] ?? '';
  116. try {
  117. $slider_image = implode(',', json_decode($slider_image, true));
  118. } catch (\Exception $exception) {
  119. $slider_image = $image;
  120. }
  121. //更新产品图片数据
  122. $product_insert_data = [
  123. 'image' => $image,
  124. 'slider_image' => $slider_image,
  125. ];
  126. Db::name('store_product')->where('product_id', $product_id)->update($product_insert_data);
  127. echo '更新产品图片数据成功' . json_encode($product_insert_data);
  128. $detail = $spuId_info['detail'];
  129. if (!is_null(json_decode($detail))) {
  130. $detail_list = json_decode($detail);
  131. $detail = '';
  132. foreach ($detail_list as $value) {
  133. $detail .= "<img src='" . $value . "' referrerpolicy='no-referrer' /></img>";
  134. }
  135. }
  136. Db::name('store_product_content')->where('product_id', $product_id)->update(['content' => $detail]);
  137. return true;
  138. }
  139. public function seveImg($goods_id, $img_url, $targetDir)
  140. {
  141. return $img_url;
  142. if (!$img_url) return $img_url;
  143. if (is_array($img_url)) {
  144. $new_img_url = [];
  145. foreach ($img_url as $value) {
  146. $new_img_url[] = $this->seveImgUrl($goods_id, $value, $targetDir);
  147. }
  148. } else {
  149. $new_img_url = $this->seveImgUrl($goods_id, $img_url, $targetDir);
  150. }
  151. return $new_img_url;
  152. }
  153. public function seveImgUrl($goods_id, $remoteImageUrl, $targetDir)
  154. {
  155. // 目标路径(确保目录存在)
  156. $targetDirTow = rand(1000, 10000) . $this->upImgName(basename($remoteImageUrl));
  157. $targetPath = $targetDir . $targetDirTow; // 使用basename获取文件名
  158. // 检查目标目录是否存在,如果不存在则创建
  159. if (!is_dir($targetDir)) {
  160. mkdir($targetDir, 0777, true); // 第二个参数是权限,第三个参数是递归创建
  161. }
  162. ini_set("max_execution_time", 2);
  163. // 获取远程图片内容
  164. $imageContent = @file_get_contents($remoteImageUrl);
  165. // 检查是否成功获取内容
  166. if ($imageContent !== false) {
  167. // 保存图片到指定路径
  168. if (file_put_contents($targetPath, $imageContent)) {
  169. $new_img_url = env('APP_URL') . '/images/gong/' . $goods_id . '/' . $targetDirTow;
  170. return $new_img_url;
  171. } else {
  172. echo "保存图片时发生错误。";
  173. return $remoteImageUrl;
  174. }
  175. } else {
  176. echo "无法获取远程图片内容。";
  177. return $remoteImageUrl;
  178. }
  179. }
  180. public function upImgName($filename)
  181. {
  182. $position = strpos($filename, '?');
  183. if ($position !== false) {
  184. $filename = substr($filename, 0, $position);
  185. }
  186. return $filename;
  187. }
  188. public function deleteFilesInDirectory($dir)
  189. {
  190. if (!is_dir($dir)) return true;
  191. // 打开目录
  192. $files = scandir($dir);
  193. // 遍历目录中的所有文件
  194. foreach ($files as $file) {
  195. // 如果是文件(排除 . 和 ..)
  196. if ($file !== '.' && $file !== '..') {
  197. $filePath = $dir . '/' . $file;
  198. // 删除文件
  199. if (is_file($filePath)) {
  200. unlink($filePath);
  201. }
  202. }
  203. }
  204. return true;
  205. }
  206. public function add($data)
  207. {
  208. $findData = Db::name('douhuomall')->where('spu_id', $data['spu_id'])->find();
  209. try {
  210. $data['create_time'] = date('Y-m-d H:i:s');
  211. $data['update_time'] = date('Y-m-d H:i:s');
  212. $skuInfo = $this->arrSort($data['skuId_info'], 'cost_price', SORT_ASC);
  213. $data['cost_price'] = isset($skuInfo[0]['cost_price']) ? $skuInfo[0]['cost_price'] : 0;
  214. $data['market_price'] = isset($skuInfo[0]['market_price']) ? $skuInfo[0]['market_price'] : 0;
  215. $data['ot_price'] = isset($skuInfo[0]['retail_price']) ? $skuInfo[0]['retail_price'] : 0;
  216. $data['mer_profit'] = isset($skuInfo[0]['mer_profit']) ? $skuInfo[0]['mer_profit'] : 0;
  217. $data['pension'] = isset($skuInfo[0]['yanglaojin']) ? $skuInfo[0]['yanglaojin'] : 0;
  218. $data['profit'] = empty($data['cost_price']) || empty($data['market_price']) ? 0 : bcdiv($data['market_price'], $data['cost_price'], 2);
  219. if (empty($findData)) {
  220. $data['skuId_info'] = json_encode($data['skuId_info']);
  221. $data['spuId_info'] = json_encode($data['spuId_info']);
  222. Db::name('douhuomall')->insert($data);
  223. } else {
  224. // 如果货物 属于已被删除状态,并且新更新进来的状态 非删除状态,并且成本价、零售价、市场价、利润率没有变动的话,
  225. // if ($findData['status'] == 3
  226. // && $data['status'] !== 3
  227. // && $data['cost_price'] == $findData['cost_price']
  228. // && $data['ot_price'] == $findData['ot_price']
  229. // && $data['market_price'] == $findData['market_price']
  230. // && $data['profit'] == $findData['profit']) {
  231. // $count = Db::name('store_product')
  232. // ->where('spu_id', '=', $data['spu_id'])
  233. // ->where('is_show', '=', 0)
  234. // ->where('is_status', '=', 0)
  235. // ->count();
  236. // if ($count) {
  237. // Db::name('store_product')->where('spu_id', '=', $data['spu_id'])->update([
  238. // 'is_show' => 1
  239. // ]);
  240. // }
  241. // }
  242. Db::name('douhuomall')->where('spu_id', $findData['spu_id'])->update([
  243. 'status' => $data['status'],
  244. // 'create_time' => date('Y-m-d H:i:s'),
  245. 'update_time' => date('Y-m-d H:i:s'),
  246. 'cost_price' => $data['cost_price'],
  247. 'market_price' => $data['market_price'],
  248. 'ot_price' => $data['ot_price'],
  249. 'mer_profit' => $data['mer_profit'],
  250. 'pension' => $data['pension'],
  251. 'profit' => $data['profit'],
  252. 'skuId_info' => json_encode($data['skuId_info']),
  253. 'spuId_info' => json_encode($data['spuId_info']),
  254. 'title' => $data['title'],
  255. 'cate_ids' => $data['cate_ids'],
  256. 'cxb_cate_id' => $data['cxb_cate_id']
  257. ]);
  258. }
  259. return true;
  260. } catch (Exception $e) {
  261. echo '供应链产品添加:' . $e->getFile() . ':' . $e->getLine() . '【' . $e->getMessage() . '】';
  262. return false;
  263. }
  264. }
  265. public function remove($goodsIds)
  266. {
  267. Db::startTrans();
  268. try {
  269. // 删除选品库对应的数据
  270. Db::name('douhuomall')->whereIn('spu_id', $goodsIds)->update([
  271. 'status' => 3,
  272. 'update_time' => date('Y-m-d H:i:s')
  273. ]);
  274. // 删除商品管理对应的数据
  275. Db::name('store_product')->whereIn('spu_id', $goodsIds)->update([
  276. // 'is_del' => 1,
  277. 'is_show' => 0
  278. ]);
  279. Db::commit();
  280. return true;
  281. } catch (Exception $e) {
  282. Db::rollback();
  283. Log::channel("gong")->error('供应链取消商品失败:' . $e->getMessage());
  284. return false;
  285. }
  286. }
  287. /**
  288. * 二维数组根据某个字段排序
  289. * @param array $array 要排序的数组
  290. * @param string $keys 要排序的键字段
  291. * @param string $sort 排序类型 SORT_ASC SORT_DESC
  292. * @return array 排序后的数组
  293. */
  294. function arrSort($array, $keys, $sort = SORT_DESC)
  295. {
  296. $keysValue = [];
  297. foreach ($array as $k => $v) {
  298. $keysValue[$k] = $v[$keys];
  299. }
  300. array_multisort($keysValue, $sort, $array);
  301. return $array;
  302. }
  303. }