Take.php 14 KB

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