<?php

namespace app\services\ThirdParty\Taobao;

use app\common\enum\CommonEnum;
use app\common\enum\third\ThirdPartyGoodCacheEnum;
use app\common\enum\third\ThirdPartyGoodEnum;
use app\utils\ArrayUtil;
use think\exception\ValidateException;

class ProductService extends TaobaoService
{

    protected $cat;

    public function __construct()
    {
        parent::__construct();

        $this->cat = $this->config['taobao']['cat'];
    }

    /**
     * 商品搜索 TbkDgMaterialRecommendRequest
     * 推广者使用，支持入参对应的“推广位”和官方提供的“物料id”，获取指定物料信息和推广链接。
     * Tack：taobao.tbk.dg.material.optional.upgrade
     * 官方文档地址：https://open.taobao.com/api.htm?spm=a219a.7386797.0.0.5cf2669aEojnlE&source=search&docId=64759&docType=2#responseParams
     * @param $params
     * @return mixed
     */
    public function searchProducts($params)
    {
        $req = new \TbkDgMaterialOptionalUpgradeRequest();
        $this->batchSetProperties($req, $params);
        $req->setAdzoneId($this->adzoneId);
        // 商品筛选-后台类目ID 和 商品筛选-查询词 必须填一个
        if (empty($req->getQ())) {
            $req->setCat($this->cat);
        }
        // SimpleXMLElement
        $res = $this->execute($req);
        if (!$res) {
            throw new ValidateException('网络错误，请稍后重试');
        }
        return $res;
    }

    /**
     * @param $res
     * @return array
     */
    public function generateUniversalTemplate($res): array
    {
        // 将 SimpleXMLElement 转换为数组
        $resMap = json_decode(json_encode($res), true);
        $productList = [];
        if (!empty($resMap['result_list']['map_data'])) {
            foreach ($resMap['result_list']['map_data'] as $data) {
                // $productList[] = $data;
                $coupon_money = [];
                // 链接-宝贝+券二合一页面链接 || 链接-宝贝推广链接
                $coupon_share_url = $data['publish_info']['coupon_share_url'] ?? ($data['publish_info']['click_url'] ?? '');
                // 商品佣金金额
                $commissionMoney = $data['publish_info']['income_info']['commission_amount'];
                $commissionMoney = bcmul($commissionMoney, 0.8, 2);

                // 到手价优惠路径列表 也就是 需要把列表内所有优惠叠加 才能从划线价 到达 到手价
                if (!empty($data['price_promotion_info']['final_promotion_path_list']['final_promotion_path_map_data'])) {
                    if (is_array($data['price_promotion_info']['final_promotion_path_list']['final_promotion_path_map_data'])) {
                        $depth = ArrayUtil::array_depth($data['price_promotion_info']['final_promotion_path_list']['final_promotion_path_map_data']);
                        if ($depth === 1) {
                            $coupon_money[] = [
                                'discount' => $data['price_promotion_info']['final_promotion_path_list']['final_promotion_path_map_data']['promotion_fee'], // 实际优惠金额（元）
                                'getStartTime' => '',
                                'getEndTime' => '',
                                'link' => $data['publish_info']['coupon_share_url'] ?? '',
                                'useStartTime' => '',
                                'useEndTime' => '',
                            ];
                        } else {
                            foreach ($data['price_promotion_info']['final_promotion_path_list']['final_promotion_path_map_data'] as $coupon) {
                                if (!empty($coupon['promotion_fee']) && (0.00 < (double)$coupon['promotion_fee'])) {
                                    $coupon_money[] = [
                                        'discount' => $coupon['promotion_fee'], // 实际优惠金额（元）
                                        'getStartTime' => '',
                                        'getEndTime' => '',
                                        'link' => $data['publish_info']['coupon_share_url'] ?? '',
                                        'useStartTime' => '',
                                        'useEndTime' => '',
                                    ];
                                }
                            }
                        }
                    }

                }

                if (empty($data['item_id'])) {
                    throw new ValidateException('缺少必要参数');
                }
                $skuId = $data['item_id'];
                $segments = explode('-', $skuId);
                $skuId = end($segments);
                $skuId = ThirdPartyGoodCacheEnum::PLATFORM['Taobao']['code'] . '_' . $skuId;

                $productList[] = [
                    // 商品信息-淘宝客新商品id；
                    'skuId' => $skuId,
                    'itemId' => $data['item_id'],
                    'type' => CommonEnum::ORDER_TYPE['TaobaoKe']['code'],
                    // 商品信息-商品标题
                    'name' => $data['item_basic_info']['title'] ?? '',
                    // 商品信息-商品主图
                    'thumb' => $data['item_basic_info']['pict_url'] ?? '',

                    'pv' => bcmul($commissionMoney, 0.7, 2),//PV金额
                    'gongxian' => bcmul($commissionMoney, 0.7, 2),
                    'jifen' => bcmul($commissionMoney, 0.7, 2),
                    'yanglaojin' => bcmul($commissionMoney, 0.3, 2),

                    // 商品佣金金额
                    'commission' => $data['publish_info']['income_info']['commission_amount'] ?? 0.00,
                    // 商品佣金比率
                    'commission_rate' => bcdiv($data['publish_info']['income_info']['commission_rate'] ?? 0, 100, 2),
                    // 优惠券集合
                    'coupon_money' => $coupon_money,
                    // 优惠券地址
                    'coupon_link' => $coupon_share_url,
                    // 最低 实际价格 促销信息-预估到手价(元)。若属于预售商品，付定金时间内，预估到手价价=定金+尾款的预估到手价
                    'lowestCouponPrice' => $data['price_promotion_info']['final_promotion_price'],
                    // 划线价 促销信息-销售价格，无促销时等于一口价，有促销时为促销价。若属于预售商品，付定金时间内，在线售卖价=预售价 ?? 商品信息-一口价通常显示为划线价
                    'price' => $data['price_promotion_info']['zk_final_price'] ?? $data['price_promotion_info']['reserve_price'],
                    'imageList' => $data['item_basic_info']['small_images']['string'] ?? [$data['item_basic_info']['pict_url'] ?? ''],
                    'materialUrl' => $coupon_share_url,
                    // 最低 实际价格 促销信息-预估到手价(元)。若属于预售商品，付定金时间内，预估到手价价=定金+尾款的预估到手价
                    'commission_' => $data['price_promotion_info']['final_promotion_price'],
                    'monthSales' => 0.00,
                    'cid' => 0
                ];
            }
        }
        return $productList;
    }
}