<?php

namespace App\Services\marketing;

use App\Models\marketing\mysql\Marketing;
use App\Models\marketing\mysql\MarketingGoods;
use App\Models\goods\mysql\GoodsSku;
use App\Models\goods\mysql\GoodsSpu;
use App\Models\shop\mysql\SubShop;
use Api\PhpUtils\Validate\Validate;
use Api\PhpServices\Idgen\Idgen;
use Api\PhpServices\Ksy\Ksyun;
use App\Exception\custom\MarketingException;
use App\Services\common\CommonService;
use Api\PhpServices\Sensitive\Sensitive;
use App\Services\goods\GoodsService;
use Helpers\Aes;
class MarketingGoodsService
{
    public static function getMarketingGoodsList($params)
    {
        $goodsSkuId = !empty($params['goods_sku_id']) ? $params['goods_sku_id'] : '';
        $marketingWhere = [];
        $where = [
            'goods_sku_id' => $goodsSkuId,
        ];
        $data = MarketingGoods::marketingGoodsList($where);

        if (!empty($data)) {
           $marketingId = array_column($data, 'marketing_id');
           $marketingWhere['marketing_id'] = !empty($marketingId) ? $marketingId : [];
        }
        
        $marketingList = Marketing::getMarketingList($marketingWhere);
        $marketingList = array_column($marketingList,null,'marketing_id');        
        $list = [];
        foreach ($data as $key => $value) {
            $marketing = !empty($marketingList[$value['marketing_id']]) ? $marketingList[$value['marketing_id']] : [];
            $list[$key] = $value;
            $list[$key]['marketing_name'] = !empty($marketing['marketing_name']) ? $marketing['marketing_name'] : '';
            $list[$key]['commission_mode'] = !empty($marketing['commission_mode']) ? $marketing['commission_mode'] : '';
            $list[$key]['first_commission_value'] = !empty($marketing['first_commission_value']) ? $marketing['first_commission_value']/100 : '';
            $list[$key]['second_commission_value'] = !empty($marketing['second_commission_value']) ? $marketing['second_commission_value']/100 : '';
            $list[$key]['create_user_email'] = !empty($marketing['create_user_email']) ? $marketing['create_user_email'] : '';
            $list[$key]['good_count'] = !empty($marketing['good_count']) ? $marketing['good_count'] : '';
            $list[$key]['start_time'] = !empty($marketing['start_time']) ? $marketing['start_time'] : '';
            $list[$key]['end_time'] = !empty($marketing['end_time']) ? $marketing['end_time'] : '';
            $list[$key]['online_status'] = !empty($marketing['online_status']) ? $marketing['online_status'] : '';
            $list[$key]['marketing_type'] = !empty($marketing['marketing_type']) ? $marketing['marketing_type'] : '';
        }
        return ['result' => $list];
    }
    public static function marketingGoodsList($params)
    {   
        //@todo 分页放大100倍,主要解决商品到期和商品库存为零的过滤场景
        $limit = !empty($params['num']) ? $params['num']*100 : 1000;

        $userId = !empty($params['user_id']) ? $params['user_id'] : '';

        
        if (!empty($params['last_id'])) {
            $where['id[<]'] = $params['last_id'];
        }

        $where['LIMIT'] = $limit;
        $where['ORDER'] = ["create_time" => "DESC"];
        
    	$marketingWhere = [
			"end_time[>=]" => date("Y-m-d"),
            "start_time[<=]" => date("Y-m-d"),
			"online_status" => 1,
    	];
    	$marketingList = Marketing::getMarketingList($marketingWhere);
        $list = [];
        $lastId = "";
    	if (!empty($marketingList)) {
            $marketingId = array_column($marketingList, 'marketing_id');
            $where['marketing_id'] = !empty($marketingId) ? $marketingId : [];
            $data = MarketingGoods::marketingGoodsList($where);
            $goodsSkuId = [];
            if (!empty($data)) {
                $goodsSkuId =  array_column($data, 'goods_sku_id');
            }

            $goodsSkuList = [];
            if (!empty($goodsSkuId)) {
                $goodsSkuList = GoodsSku::getRecordMaster(['goods_sku_id' => $goodsSkuId]);
                $goodsSkuList = !empty($goodsSkuList) ? array_column($goodsSkuList,null,'goods_sku_id') : [];
            }
            $lastData = end($data);
            $lastId = !empty($lastData['id']) ? $lastData['id'] : '';

            $shopId = [];
            foreach ($data as $key => $value) {
                $shopId[$key] = !empty($goodsSkuList[$value['goods_sku_id']]['shop_id']) ? $goodsSkuList[$value['goods_sku_id']]['shop_id'] : '';
            }

            $subShopList = [];
            if (!empty($shopId)) {
                $subShopList = SubShop::getRecordMaster(['shop_id' => $shopId]);
                $subShopList = !empty($subShopList) ? array_column($subShopList,null,'shop_id') : [];
            }

            $marketingList =  !empty($marketingList) ? array_column($marketingList,null,'marketing_id') : [];

            $lifeAccountId = !empty($goodsSkuList) ? array_column($goodsSkuList, 'life_account_id') : [];

            $lifeAccountList = CommonService::getlifeAccountList(['life_account_id' => $lifeAccountId]);

            $i = 0;
            foreach ($data as $key => $value) {

                $inventoryRest = !empty($goodsSkuList[$value['goods_sku_id']]['inventory_rest']) ? $goodsSkuList[$value['goods_sku_id']]['inventory_rest'] : '';
                $expirationTime = !empty($goodsSkuList[$value['goods_sku_id']]['expiration_time']) ? $goodsSkuList[$value['goods_sku_id']]['expiration_time'] : '';

                $onlineStatus = !empty($goodsSkuList[$value['goods_sku_id']]['online_status']) ? $goodsSkuList[$value['goods_sku_id']]['online_status'] : '';

                if (!empty($inventoryRest) && $expirationTime > date("Y-m-d H:i:s") && $onlineStatus == 1 ) {
                    $list[$i]['inventory_rest'] = !empty($goodsSkuList[$value['goods_sku_id']]['inventory_rest']) ? $goodsSkuList[$value['goods_sku_id']]['inventory_rest'] : '';
                    $list[$i] = $value;
                    $list[$i]['life_account_id'] = !empty($goodsSkuList[$value['goods_sku_id']]['life_account_id']) ? $goodsSkuList[$value['goods_sku_id']]['life_account_id'] : '';

                    $publishUserId = !empty($goodsSkuList[$value['goods_sku_id']]['publish_user_id']) ? $goodsSkuList[$value['goods_sku_id']]['publish_user_id'] : '';

                    if (!empty($userId) && $userId == $publishUserId) {
                        $list[$i]['is_self_publish'] = 0;
                    }else{
                        $list[$i]['is_self_publish'] = 1;
                    }
                    //允许自己买自己的
                    $list[$i]['is_self_publish'] = 1;

                    $life_account_id = !empty($list[$i]['life_account_id']) ? $list[$i]['life_account_id'] : '';

                    $list[$i]['life_account_name'] = !empty($lifeAccountList[$life_account_id]['life_account_name']) ? $lifeAccountList[$life_account_id]['life_account_name'] : '';

                    $list[$i]['life_account_icon'] = !empty($lifeAccountList[$life_account_id]['life_account_icon']) ? $lifeAccountList[$life_account_id]['life_account_icon'] : '';

                    $list[$i]['shop_id'] = !empty($goodsSkuList[$value['goods_sku_id']]['shop_id']) ? $goodsSkuList[$value['goods_sku_id']]['shop_id'] : '';
                    $list[$i]['goods_name'] = !empty($goodsSkuList[$value['goods_sku_id']]['goods_name']) ? $goodsSkuList[$value['goods_sku_id']]['goods_name'] : '';

                    $list[$i]['goods_desc'] = !empty($goodsSkuList[$value['goods_sku_id']]['desc']) ? $goodsSkuList[$value['goods_sku_id']]['desc'] : '';
                    $list[$i]['goods_spu_id'] = !empty($goodsSkuList[$value['goods_sku_id']]['goods_spu_id']) ? $goodsSkuList[$value['goods_sku_id']]['goods_spu_id'] : '';
                    $list[$i]['original_price'] = !empty($goodsSkuList[$value['goods_sku_id']]['original_price']) ? $goodsSkuList[$value['goods_sku_id']]['original_price']/100 : '';
                    $list[$i]['price'] = !empty($goodsSkuList[$value['goods_sku_id']]['price']) ? $goodsSkuList[$value['goods_sku_id']]['price']/100 : '';
                    $list[$i]['total_amount_order'] = !empty($goodsSkuList[$value['goods_sku_id']]['total_amount_order']) ? $goodsSkuList[$value['goods_sku_id']]['total_amount_order'] : '';
                    $list[$i]['desc_pic_url'] = !empty($goodsSkuList[$value['goods_sku_id']]['desc_pic_url']) ? GoodsService::getUrlList($goodsSkuList[$value['goods_sku_id']]['desc_pic_url']) : '';

                    $shopId = !empty($list[$i]['shop_id']) ? $list[$i]['shop_id'] : '';
                    $list[$i]['shop_name'] = !empty($subShopList[$shopId]['shop_name']) ? $subShopList[$shopId]['shop_name'] : '';
                    $commissionMode = !empty($marketingList[$value['marketing_id']]['commission_mode']) ? $marketingList[$value['marketing_id']]['commission_mode'] : '';

                    $secondCommission = !empty($marketingList[$value['marketing_id']]['second_commission_value']) ? $marketingList[$value['marketing_id']]['second_commission_value']/100 : 0;
                    //
                    $list[$i]['share_price'] = 0;
                    //比例
                    if (!empty($secondCommission) && $commissionMode == 1) {
                        $price = !empty($list[$i]['price']) ? $list[$i]['price'] : 0;
                        $list[$i]['share_price'] = (float) substr(sprintf("%.4f",$secondCommission*$price/100),0,-2);
                    }

                    //固定
                    if (!empty($commissionMode) && $commissionMode == 2) {
                        $list[$i]['share_price'] =  (float) substr(sprintf("%.4f",$secondCommission),0,-2);
                    }

                    $content = $userId .'_' .$value['marketing_id'];
                    $goodsShareId = Aes::encrypt($content);
                    $list[$i]['goods_share_code'] = $goodsShareId;
                    $i++;
                }
            }
        }
        
        $hasmore = !empty($list) ? 1 : 0 ;
        $result = ['result' => $list ,'last_id' => $lastId, 'hasmore' => $hasmore];
        return $result;
    }

    /**
     * 获取指定商品分销活动的分成比例（第一分销人的分成比例）
     * @param $goodsSkuIds
     * @return array
     */
    public static function getRunningMarketing($goodsSkuIds)
    {
        $marketingInfoList = MarketingGoods::select(["marketing_id", "goods_sku_id"], ["goods_sku_id" => $goodsSkuIds]);
        if (!empty($marketingInfoList)) {
            foreach ($marketingInfoList as $marketingInfo) {
                $marketingInfoIds[$marketingInfo["goods_sku_id"]] = $marketingInfo["marketing_id"];
            }
            $marketingIds = array_values($marketingInfoIds);

            $now = date("Y-m-d H:i:s");
            $resMarketingList = Marketing::select("*", ["start_time[<]" => $now, "end_time[>]" => $now, "marketing_id" => $marketingIds, "marketing_type" => Marketing::MARKETING_TYPE_FENXIAO]);
            if (!empty($resMarketingList)) {
                foreach ($resMarketingList as $res) {
                    $marketingList[$res["marketing_id"]] = $res;
                }
            }

            $data = [];
            foreach ($marketingInfoIds as $goodsSkuId => $marketingId) {
                if (!empty($marketingList[$marketingId]["second_commission_value"]) && $marketingList[$marketingId]["commission_mode"] == 1) {
                    $data[$goodsSkuId] =  substr(sprintf("%.4f", $marketingList[$marketingId]["second_commission_value"]/10000), 0, -2);
                }

                if (!empty($marketingList[$marketingId]["second_commission_value"]) && $marketingList[$marketingId]["commission_mode"] == 2) {
                    $data[$goodsSkuId] =  substr(sprintf("%.4f", $marketingList[$marketingId]["second_commission_value"]/100), 0, -2);
                }
            }
            return $data;
        }
    }



    
    /**
     * 获取图片地址，这里因为bucket可能不同，不保证图片顺序
     * @param $picUrlStr
     * @return array
     */
    public static function getUrlList($picUrlStr)
    {
        $data = $ksyunParams = [];
        $strList = explode(",", $picUrlStr);
        foreach ($strList as $key => $str) {
            $arr = explode("/", $str);
            if (count($arr) != 2) {
                continue;
            }

            $bucket = $arr[0];
            $objectId = $arr[1];

            $url = Ksyun::getPicUrl("merchant-b", 'goods_temp', $bucket . '/' . $objectId, 200, 200, 'jpeg');
            $data[] = $url;
        }

        return $data;
    }
}



