<?php


namespace App\Services\marketing;

use Api\PhpServices\Ksy\Ks3Api;
use Api\PhpUtils\Http\Request;
use Api\PhpUtils\Http\HttpUtil;
use App\Exception\BaseException;
use App\Exception\custom\InterfaceException;
use App\Models\goods\mysql\Ota;
use App\Models\goods\mysql\PindanGoodsSku;
use App\Models\marketing\mysql\Marketing;
use App\Models\marketing\mysql\MarketingGoods;
use App\Models\goods\mysql\GoodsSku;
use Api\PhpServices\Idgen\Idgen;
use App\Exception\custom\MarketingException;
use Api\PhpServices\Sensitive\Sensitive;
use App\Models\marketing\mysql\MarketingPindan;
use App\Models\marketing\mysql\MarketingTakePlace;
use App\Models\marketing\mysql\TakePlace;
use App\Services\common\CommonService;
use App\Services\common\KafkaService;
use App\Services\goods\GoodsService;
use Daemon\Goods;
use App\Exception\custom\GoodsException;

class MarketingService
{
    const ONLINE_LIFE_ACCOUNT_ID = "19019625839230981";
    const ONLINE_LIFE_ACCOUNT_ID_TEST = "17963416161910792";
    const CHARGEFEE = 0.006;
    /**
     * 写死的自营生活号
     * @return string
     */
    public static function getPublicLifeAccountId()
    {
        $lifeAccountId = config('lifeaccount','life_account_id');
        return $lifeAccountId;
    }

    /**
     * op 后台获取活动需要参加的商品
     *
     * @param $params
     * @return array|mixed
     */
    public static function marketingGooodsList($params='')
    {
        $startTime = !empty($params['start_time']) ? $params['start_time'] : '';
        $endTime = !empty($params['end_time']) ? $params['end_time'] : '';
        $goodsSpuId = !empty($params['goods_spu_id']) ? $params['goods_spu_id'] : '';
        $lifeAccountId = !empty($params['life_account_id']) ? $params['life_account_id'] : '';

        if (empty($startTime)) {
             throw new MarketingException(['cus'=>8]);
        }

        if (empty($endTime)) {
            throw new MarketingException(['cus'=>9]);
        }

        // if ($startTime <= date("Y-m-d")) {
        //      throw new MarketingException(['cus'=>10]);
        // }

        if ($endTime <= date("Y-m-d")) {
            throw new MarketingException(['cus'=>11]);
        }

        if ($startTime >= $endTime) {
            throw new MarketingException(['cus'=>14]);
        }
        
        $goodsData = [
            "OR" => [
                "start_time[>=]" => $startTime,
                "end_time[>=]" => $startTime,
            ],
            'online_status' => 1,
        ];

        //已存在的活动
        $tmpMarketingList = Marketing::getMarketingList($goodsData);
        $tmpMarketingId = [];
        if (!empty($tmpMarketingList)) {
            $tmpMarketingId = array_column($tmpMarketingList, 'marketing_id');
        }
        //已加入活动的商品
        $marketingGoodsList = MarketingGoods::marketingGoodsList(['marketing_id' => $tmpMarketingId]);
        if (!empty($marketingGoodsList)) {
            $tmpGoodsSkuId = array_column($marketingGoodsList, 'goods_sku_id');
        }


        $where = [
            'online_status' => 1,
            //'rule_refund' => 2,
            "expiration_time[>]" => date("Y-m-d"),
        ];

        if (!empty($tmpGoodsSkuId)) {
            $where['goods_sku_id[!]'] = $tmpGoodsSkuId;
        }

        if (!empty($goodsSpuId)) {
            $where['goods_spu_id'] = $goodsSpuId;
        }

        if (!empty($lifeAccountId)) {
            $where['life_account_id'] = $lifeAccountId;
        }
        
        $goodsSkuList = GoodsSku::select('*', $where);

        $lifeAccountIds = [];
        if (!empty($goodsSkuList)) {
            $lifeAccountIds = array_column($goodsSkuList, 'life_account_id');
        }
        $lifeAccountList = CommonService::getlifeAccountList(['life_account_id' => $lifeAccountIds]);
        $list = [];
        foreach ($goodsSkuList as $key => $value) {
            $list[$key]['goods_sku_id'] = $value['goods_sku_id'];
            $list[$key]['goods_spu_id'] = $value['goods_spu_id'];
            $list[$key]['life_account_id'] = $value['life_account_id'];
            $list[$key]['goods_name'] = $value['goods_name'];
            $list[$key]['life_account_name'] = !empty($lifeAccountList[$value['life_account_id']]['life_account_name']) ? $lifeAccountList[$value['life_account_id']]['life_account_name'] : '';  
        }
        return $list;
    }

    /**
     * op 后台列表查询
     *
     * @param $params
     * @return array|mixed
     */
    public static function marketingList($params)
    {
        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : Marketing::MARKETING_TYPE_FENXIAO;
        if ($marketingType == Marketing::MARKETING_TYPE_FENXIAO) {
            return self::fenxiaoMarketingList($params);
        } else if ($marketingType == Marketing::MARKETING_TYPE_TUANGOU) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_MIAOSHA) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return self::pindanMarketingList($params);
        }
    }

    /**
     * 营销中心-活动列表
     * @param $params
     * @return array
     */
    public static function yingxiaoList($params)
    {
        $where["marketing_type"] = [Marketing::MARKETING_TYPE_LIEBIAN, Marketing::MARKETING_TYPE_TUANZHANG];
        $where['ORDER'] = ["create_time" => "DESC"];
        $lists = Marketing::getRecords($where);

        if ($lists && is_array($lists)) {
            $capitalPoolIds = array_column($lists, 'capital_pool_id');
            //获取资金池列表信息
            $url = config('interface', 'coupon.capitalpool.fetch_map_capitalpool');
            $capitalPoolList = (new Request())->get($url, ["capital_pool_ids" => $capitalPoolIds]);

            $capitalPoolList = $capitalPoolList['response']['result'] ?: [];
            $poolTotal = $poolUsed = $poolLock = 0;
            foreach ($lists as &$val) {
                if($capitalPoolList[$val['capital_pool_id']]) {
                    $val['capital_pool'] = $capitalPoolList[$val['capital_pool_id']];
                    foreach (['capital_pool_total','capital_pool_lock','capital_pool_used'] as $key){
                        $val['capital_pool'][$key] = sprintf("%0.02f",$val['capital_pool'][$key]/100);
                    }
                    $poolTotal += $val['capital_pool']['capital_pool_total'];
                    $poolUsed += $val['capital_pool']['capital_pool_used'];
                    $poolLock += $val['capital_pool']['capital_pool_lock'];
                }else {
                    $val['capital_pool'] = [];
                }
                $val['online_status_desc'] = Marketing::$onlineStatusDesc[$val['online_status']];

            }
            unset($val);
        }

        $poolbalance = $poolTotal - $poolUsed - $poolLock;
        $poolAnalysis = ['total'=>$poolTotal,'used'=>$poolUsed,'lock'=>$poolLock,'balance'=>$poolbalance];

        return ['anlysis'=>$poolAnalysis,'list' => $lists];
    }

    /**
     * 分销活动列表
     * @param $params
     * @return array
     */
    private static function fenxiaoMarketingList($params)
    {
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 20;
        $page = ($params['page'] - 1) * $limit;

        $where["marketing_type"] = Marketing::MARKETING_TYPE_FENXIAO;
        if (!empty($params['marketing_name'])) {
            $where['marketing_name'] = $params['marketing_name'];
        }

        if (!empty($params['marketing_id'])) {
            $where['marketing_id'] = $params['marketing_id'];
        }


        $where['life_account_id'] = self::getPublicLifeAccountId();


        if (!empty($params['online_status'])) {
            if (is_array($params['online_status'])) {
                foreach ($params['online_status'] as $key => $valu) {
                    if (!empty($valu)) {
                        $where['online_status'][$key] = $valu;
                    }else{
                        $where['online_status'] = [1,2];
                        break;
                    }
                }
            }else{
                $where['online_status'] = $params['online_status'];
            }
        }

        if (!empty($params['goods_spu_id'])) {
            $goodsSpuId = $params['goods_spu_id'];
            $marketingGoodsList = MarketingGoods::marketingGoodsList(['goods_spu_id' => $goodsSpuId]);

            if (empty($marketingGoodsList)) {
                $where['marketing_id'] = "-1";
            }else{
                $marketingId = array_column($marketingGoodsList, 'marketing_id');
                if (!empty($where['marketing_id'])) {
                    array_push($marketingId,$where['marketing_id']);
                }
                $where['marketing_id'] = $marketingId;
            }

        }

        $where['ORDER'] = ["create_time" => "DESC"];
        $where['LIMIT'] = [$page, $limit];
        $list = Marketing::getRecords($where);
        $lists = [];
        foreach ($list as $key => $value) {
            $lists[$key] = $value;
            $lists[$key]['first_commission_value'] = !empty($value['first_commission_value']) ? $value['first_commission_value']/100 : 0;
            $lists[$key]['second_commission_value'] = !empty($value['second_commission_value']) ? $value['second_commission_value']/100 : 0;
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = Marketing::getCount($where);
        $data = ['result' => $lists,'count' => $count];
        return $data;
    }

    /**
     * 拼单活动列表
     * @param $params
     * @return array
     */
    private static function pindanMarketingList($params)
    {
        $params['activity_status'] = !empty($params['activity_status']) ? $params['activity_status'] : 0;
        //默认from=0，主要是判断小程序（from=1）时候特殊逻辑
        $params['from'] = !empty($params['from']) ? $params['from'] : 0;
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 20;
        $page = ($params['page'] - 1) * $limit;
        //排序规则
        $sortField = $params['sort_field'] ?? 'update_time';
        $sortType = isset($params['sort_type']) ? strtoupper($params['sort_type']) : 'desc';

        //验证sort合法性
        if(!in_array($params['sort_field'],['create_time','update_time','end_time','start_time'])) {
            $sortField = 'update_time';
        }
        if(!in_array($params['sort_type'],['asc','desc'])) {
            $sortType = 'DESC';
        }

        $where["marketing_type"] = Marketing::MARKETING_TYPE_PINDAN;
        if (!empty($params['marketing_name'])) {
            $where['marketing_name[~]'] = $params['marketing_name'];
        }
        if (!empty($params['online_status'])) {
            $where['online_status'] = $params['online_status'];
        }

        $now = date("Y-m-d H:i:s");
        if ($params["activity_status"] == MarketingPindan::ACTIVITY_STATUS_NO_START) {
            $where["start_time[>]"] = $now;
        } elseif ($params["activity_status"] == MarketingPindan::ACTIVITY_STATUS_IN_PROGRESS) {
            $where["start_time[<=]"] = $now;
            $where["end_time[>=]"] = $now;
        } elseif ($params["activity_status"] == MarketingPindan::ACTIVITY_STATUS_FINISHED) {
            $where["end_time[<]"] = $now;
            //七日内结束的活动
            if (!empty($params['from']) && $params['from'] == 1) {
                $beforeSevenDay = date("Y-m-d H:i:s", strtotime("-7 day"));
                $where["end_time[>]"] = $beforeSevenDay;
            }
        } elseif ($params["activity_status"] == MarketingPindan::ACTIVITY_STATUS_START_TODAY) {//今日上新-未开始
            $where["start_time[>]"] = $now;
            $where["start_time[<=]"] = date("Y-m-d 00:00:00",strtotime('+1 days'));
            $where["end_time[>=]"] = $now;
        }

        $where['life_account_id'] = self::getPublicLifeAccountId();

        $where['ORDER'] = [$sortField => $sortType];
        $where['LIMIT'] = [$page, $limit];
        $list = Marketing::select(["marketing_id", "marketing_name", "start_time", "end_time",
                "online_status", "update_time", "create_time"]
            , $where);

        $lists = [];
        if (!empty($list)) {
            $marketingIds = [];
            foreach ($list as $key => $value) {
                $marketingIds[] = $value["marketing_id"];
            }
            //参与人数：当前拼单成功支付的订单总数量
            if(isset($params['need_buy_num']) && $params['need_buy_num']) {
                $userCount = self::getHaveBuyGoodsUserCount(["marketing_id" => $marketingIds]);
            }else {
                $userCount = [];
            }

            $marketingPindanData = MarketingPindan::select(["marketing_id", "publish_life_account_id",
                    "min_price", "max_price", "pindan_desc","participate_number", "pindan_pic"]
                , ["marketing_id" => $marketingIds]);
            $priceData = [];
            if (!empty($marketingPindanData)) {
                foreach ($marketingPindanData as $item) {
                    $priceData[$item["marketing_id"]] = $item;
                }
            }
            $publishLifeAccountIds = array_unique(array_column($marketingPindanData, "publish_life_account_id"));
            $lifeAccountList = CommonService::getlifeAccountList(['life_account_id' => $publishLifeAccountIds]);

            $defaultPic = "SHQ_goods_0_012Xh1AQcMqu";
            foreach ($list as $key => $value) {
                $lists[$key] = $value;
                $lists[$key]["online_status_desc"] = Marketing::$onlineStatusDesc[$value["online_status"]];
                if (!empty($priceData[$value["marketing_id"]])) {
                    $currentLifeAccountId = $priceData[$value["marketing_id"]]["publish_life_account_id"];

                    $lists[$key]["publish_life_account_id"] = $currentLifeAccountId;
                    if (!empty($lifeAccountList[$currentLifeAccountId])) {
                        $lists[$key]["life_account_icon"] = $lifeAccountList[$currentLifeAccountId]["life_account_icon"];
                        $lists[$key]["life_account_name"] = $lifeAccountList[$currentLifeAccountId]["life_account_name"];
                    }

                    $picUrl = GoodsService::getUrlList($priceData[$value["marketing_id"]]["pindan_pic"]);
                    $lists[$key]["min_price"] = sprintf("%.2f", $priceData[$value["marketing_id"]]["min_price"] / 100);
                    $lists[$key]["max_price"] = sprintf("%.2f", $priceData[$value["marketing_id"]]["max_price"] / 100);
                    $lists[$key]["pindan_pic_url"] = $picUrl;
                    $lists[$key]["pindan_desc"] = $priceData[$value["marketing_id"]]["pindan_desc"];
                    $lists[$key]["participate_number"] = empty($userCount[$value['marketing_id']]) ? 0 : $userCount[$value['marketing_id']];

                    $shareDefaultStr = empty($priceData[$value["marketing_id"]]["pindan_pic"]) ? $defaultPic : $priceData[$value["marketing_id"]]["pindan_pic"];
                    $strList = explode(",", $shareDefaultStr);
                    $shareStr = $strList[0];
                    $shareRes = Ks3Api::picEncryptUrl($shareStr, 500, 400);
                    $shareUrl = empty($shareRes["response"]["data"]["url"]) ? "" :  $shareRes["response"]["data"]["url"];
                    $lists[$key]["share_url"] = $shareUrl;
                }
            }
        }

        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = Marketing::count("*", $where);
        return ['result' => $lists,'count' => $count];
    }

    /**
     * 创建活动
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase|array
     * @throws MarketingException
     * @throws \App\Exception\custom\CodeSpecialException
     */
    public static function addMarketing($params)
    {
        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : Marketing::MARKETING_TYPE_FENXIAO;
        if ($marketingType == Marketing::MARKETING_TYPE_FENXIAO) {
            return self::addFenxiaoMarketing($params);
        } else if ($marketingType == Marketing::MARKETING_TYPE_TUANGOU) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_MIAOSHA) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return self::addPindanMarketing($params);
        }
    }

    /**
     * 增加分销活动
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws MarketingException
     * @throws \App\Exception\custom\CodeSpecialException
     */
    private static function addFenxiaoMarketing($params)
    {
        $commissionMode = !empty($params['commission_mode']) ? $params['commission_mode'] : 1;

        $marketingName = !empty($params['marketing_name']) ? $params['marketing_name'] : '';

        $firstCommissionRate = !empty($params['first_commission_value']) ? $params['first_commission_value']*100 : 0;
        $secondCommissionRate = !empty($params['second_commission_value']) ? $params['second_commission_value']*100 : 0;
        $createUserEmail = !empty($params['op_cur_user']) ? $params['op_cur_user'] : '';
        $startTime = !empty($params['start_time']) ? $params['start_time'] : '';
        $endTime = !empty($params['end_time']) ? $params['end_time'] : '';
        $type = !empty($params['marketing_type']) ? $params['marketing_type'] : 1;
        $goodsSkuId = !empty($params['goods_sku_id']) ? explode(",", $params['goods_sku_id']) : [];

        if ($commissionMode == 1) {
            $rate = $firstCommissionRate + $secondCommissionRate;
            if ($rate > 5000) {
                throw new MarketingException(['cus'=>15]);
            } 
        }

        if (empty($goodsSkuId)) {
            throw new MarketingException(['cus'=>12]);
        }

        if (empty($marketingName)) {
            throw new MarketingException(['cus'=>0]);
        }

        // if (empty($firstCommissionRate)) {
        //     throw new MarketingException(['cus'=>3]);
        // }

        if (empty($secondCommissionRate)) {
            throw new MarketingException(['cus'=>4]);
        }

        if (self::utf8Strlen($marketingName) > 50) {
            throw new MarketingException(['cus'=>1]);
        }

        if (empty($startTime)) {
            throw new MarketingException(['cus'=>8]);
        }

        if (empty($endTime)) {
            throw new MarketingException(['cus'=>9]);
        }

        // if ($startTime <= date("Y-m-d")) {
        //      throw new MarketingException(['cus'=>10]);
        // }

        if ($endTime <= date("Y-m-d")) {
            throw new MarketingException(['cus'=>11]);
        }

        if ($startTime >= $endTime) {
            throw new MarketingException(['cus'=>14]);
        }

        $lifeAccountId = config('lifeaccount','life_account_id');

        $tmpMarketingId = [];
        $tmpGoodsSkuId = [];
        $goodsData = [
            "OR" => [
                "start_time[>=]" => $startTime,
                "end_time[>=]" => $startTime,
            ],
            "online_status" => 1,
        ];

        //存在的活动
        $tmpMarketingList = Marketing::getMarketingList($goodsData);

        if (!empty($tmpMarketingList)) {
            $tmpMarketingId = array_column($tmpMarketingList, 'marketing_id');
        }

        $marketingGoodsList = MarketingGoods::marketingGoodsList(['marketing_id' => $tmpMarketingId]);

        if (!empty($marketingGoodsList)) {
            $tmpGoodsSkuId = array_column($marketingGoodsList, 'goods_sku_id');
        }

        if (!empty($tmpGoodsSkuId)) {
            if (array_intersect($goodsSkuId, $tmpGoodsSkuId)) {
                throw new MarketingException(['cus'=>13]);
            }
        }


        $detectParams = [
            'businessId' => 1,
            'text' => !empty($marketingName) ? $marketingName : '',
            'scene' => 1,
        ];
        $sensitive =  (new Sensitive)->detect($detectParams);
        if (!empty($sensitive['data'])) {
            throw new MarketingException(['cus'=>2]);
        }

        // //判断重复
        // if (!self::isName($name)) {
        //     throw new ShopException(['cus'=>6]);
        // }
        //$res = self::getIdgenId(1, 'goods', $count = 1);
        //$stores_id = !empty($res[0]) ? $res[0] : '';

        Marketing::beginTransaction();
        $colums = [
            //'marketing_id' => $marketing_id,
            'marketing_name' => $marketingName,
            'first_commission_value' => $firstCommissionRate,
            'second_commission_value' => $secondCommissionRate,
            'create_user_email' => $createUserEmail,
            'good_count' => 0,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'online_status' => 1,
            'marketing_type' => $type,
            'update_user_email' => $createUserEmail,
            'update_time' => date("Y-m-d H:i:s"),
            'create_time' => date("Y-m-d H:i:s"),
            'commission_mode' => $commissionMode,
            'life_account_id' => $lifeAccountId,
        ];
        $marketingId = Marketing::insertRecord($colums);
        if (empty($marketingId)) {
            Marketing::rollback();
            throw new MarketingException(['cus' => 5]);
        }
        $colums = [];
        $goodCount = !empty($goodsSkuId) ? count($goodsSkuId) : 0;
        $goodsSkuList = GoodsSku::select('*', ['goods_sku_id' => $goodsSkuId]);
        foreach ($goodsSkuList as $key => $value) {
            $clearPrice = !empty($value["clear_price"]) ? $value["clear_price"] : 0;
            $price = !empty($value["price"]) ? $value["price"] : 0;
            $chargeFee = !empty($price) ? (float)bcmul($price , self::CHARGEFEE,2) : 0; //手续费 (分)
            if ($chargeFee < 1) {
                $chargeFee = 0;
            }
            if (!empty($clearPrice) && $clearPrice > 0) {
                if ($commissionMode == Marketing::COMMISSION_MODE_RATE) {
                    $commissionTotal = ($firstCommissionRate + $secondCommissionRate) / 10000 * $price;
                    if (($price - $commissionTotal-$chargeFee) < $clearPrice) {
                        throw new GoodsException(['cus' => 48]);
                    }
                }

                if ($commissionMode == Marketing::COMMISSION_MODE_FIXED) {
                    $commissionTotal = ($firstCommissionRate + $secondCommissionRate);
                    if (($price - $commissionTotal - $chargeFee)< $clearPrice) {
                        throw new GoodsException(['cus' => 48]);
                    }
                }
            }else{
                //比例计算
                if ($commissionMode == Marketing::COMMISSION_MODE_RATE) {
                    $commissionTotal = ($firstCommissionRate + $secondCommissionRate) / 10000 * $price;
                    if ($price < ($commissionTotal+$chargeFee)) {
                        throw new MarketingException(['cus'=>33]);
                    }
                }
                
                //固定金额
                if ($commissionMode == Marketing::COMMISSION_MODE_FIXED) {
                    $commissionTotal = ($firstCommissionRate + $secondCommissionRate);
                    if ($price < ($commissionTotal+$chargeFee)) {
                        throw new MarketingException(['cus'=>33]);
                    }
                }
            }
            
            

            $colums[$key]['marketing_id'] = $marketingId;
            $colums[$key]['goods_spu_id'] = $value['goods_spu_id'];
            $colums[$key]['goods_sku_id'] = $value['goods_sku_id'];
            $colums[$key]['update_time'] = date("Y-m-d H:i:s");
            $colums[$key]['create_time'] = date("Y-m-d H:i:s");
        }

        $info = MarketingGoods::insertRecord($colums);
        if (empty($info)) {
            Marketing::rollback();
            throw new MarketingException(['cus' => 5]);
        }

        $srt = Marketing::updateRecord(['good_count' => $goodCount], ['marketing_id' => $marketingId]);
        if (!empty($srt)) {
            Marketing::commit();
            return $srt;
        }else{
            Marketing::rollback();
            throw new MarketingException(['cus' => 5]);
        }
    }

    /**
     * 增加拼单活动
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws MarketingException
     */
    private static function addPindanMarketing($params)
    {
        $marketingName = !empty($params['marketing_name']) ? $params['marketing_name'] : '';
        $pindanPic = !empty($params['pindan_pic']) ? $params['pindan_pic'] : '';
        $pindanDesc = !empty($params['pindan_desc']) ? $params['pindan_desc'] : '';
        $createUserEmail = !empty($params['op_cur_user']) ? $params['op_cur_user'] : '';
        $startTime = !empty($params['start_time']) ? $params['start_time'] : '';
        $endTime = !empty($params['end_time']) ? $params['end_time'] : '';
        $type = Marketing::MARKETING_TYPE_PINDAN;
        $goodsSkuId = !empty($params['goods_sku_id']) ? explode(",", $params['goods_sku_id']) : [];
        $takePlaceIds = !empty($params['take_place_ids']) ? explode(",", $params['take_place_ids']) : [];
        //$publicLifeAccountId = self::getPublicLifeAccountId();
        $lifeAccountId = config('lifeaccount','life_account_id');
        if (empty($marketingName)) {
            throw new MarketingException(['cus' => 0]);
        }
        if (empty($startTime)) {
            throw new MarketingException(['cus' => 8]);
        }
        if (empty($endTime)) {
            throw new MarketingException(['cus' => 9]);
        }
        if ($startTime >= $endTime) {
            throw new MarketingException(['cus' => 21]);
        }
        if (empty($takePlaceIds)) {
            throw new MarketingException(['cus' => 22]);
        }

        //重复判断
        $marketing = Marketing::getRecord(["marketing_name" => $marketingName], ["marketing_id"]);
        if (!empty($marketing)) {
            $marketingPindan = MarketingPindan::getRecord(["marketing_id" => $marketing["marketing_id"]]);
            if (!empty($marketingPindan) && $lifeAccountId == $marketingPindan["publish_life_account_id"]) {
                throw new MarketingException(['cus' => 18]);
            }
        }

        if (empty($goodsSkuId)) {
            throw new MarketingException(['cus' => 12]);
        }

        //获取商品的最大最小值
        $skuInfoList = PindanGoodsSku::getRecordMaster(["goods_sku_id" => $goodsSkuId]
            , ["goods_sku_id", "goods_spu_id", "price"]);
        $priceList = [];
        foreach ($skuInfoList as $skuInfo) {
            $priceList[] = $skuInfo["price"];
        }
        $uniquePriceList = array_unique($priceList);
        sort($uniquePriceList);
        $minPrice = $uniquePriceList[0];
        $maxPrice = end($uniquePriceList);

        Marketing::beginTransaction();
        $marketingParams = [
            'marketing_name' => $marketingName,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'online_status' => 1,
            'marketing_type' => $type,
            'good_count' => count($goodsSkuId),
            'create_user_email' => $createUserEmail,
            'update_user_email' => $createUserEmail,
            'update_time' => date("Y-m-d H:i:s"),
            'create_time' => date("Y-m-d H:i:s"),
            'life_account_id' => $lifeAccountId
        ];
        $marketingId = Marketing::insertRecord($marketingParams);
        if (empty($marketingId)) {
            Marketing::rollback();
            throw new MarketingException(['cus' => 5]);
        }

        $pindanParams = [
            "marketing_id" => $marketingId,
            "publish_life_account_id" => $lifeAccountId,
            "pindan_pic" => $pindanPic,
            "pindan_desc" => $pindanDesc,
            "min_price" => $minPrice,
            "max_price" => $maxPrice,
        ];
        $pindanId = MarketingPindan::insertRecord($pindanParams);
        if (empty($pindanId)) {
            Marketing::rollback();
            throw new MarketingException(['cus' => 5]);
        }

        $marketingGoods = [];
        $tempSkuInfoList = array_column($skuInfoList, null, "goods_sku_id");
        foreach ($goodsSkuId as $key => $skuId) {
            if (empty($tempSkuInfoList[$skuId]["goods_spu_id"])) {
                continue;
            }
            $marketingGoods[$key]["goods_spu_id"] = $tempSkuInfoList[$skuId]["goods_spu_id"];
            $marketingGoods[$key]["goods_sku_id"] = $skuId;
            $marketingGoods[$key]["marketing_id"] = $marketingId;
        }

        MarketingGoods::save($marketingGoods);

        //自提点
        if (!empty($takePlaceIds)) {
            $takePlaceList = TakePlace::select(["take_place_id", "take_place_name"], ["take_place_id" => $takePlaceIds]);
            $tmpTakePlaceList = [];
            foreach ($takePlaceList as $item) {
                $tmpTakePlaceList[$item["take_place_id"]] = $item["take_place_name"];
            }

            $marketingTakePlaces = [];
            foreach ($takePlaceIds as $key => $takePlaceId) {
                $marketingTakePlaces[$key]["take_place_id"] = $takePlaceId;
                $marketingTakePlaces[$key]["marketing_id"] = $marketingId;
                $marketingTakePlaces[$key]["take_place_name"] = $tmpTakePlaceList[$takePlaceId];
            }
            MarketingTakePlace::save($marketingTakePlaces);
        }

        if (!Marketing::commit()) {
            Marketing::rollback();
            throw new MarketingException(["cus" => 5]);
        }

        $picList  = GoodsService::getUrlList($pindanPic);
        KafkaService::productMarketingUpdate([
            'activityId'   =>  $marketingId,
            'startDate'    =>  $startTime,
            'endDate'      =>  $endTime,
            'userId'       =>  $lifeAccountId,
            'activityName' =>  $marketingName,
            'text'         =>  $pindanDesc,
            'imageId'      =>  $picList[0] ?? '',
            'createTime'   =>  date('Y-m-d H:i:s'),
            'onlineStatus' =>  Marketing::ONLINE_STATUS_QIDONG,
        ]);

        return $pindanId;
    }

    /**
     * 更新数据
     *
     */
    public static function updateMarketing($params, $where, $originParams)
    {
        $marketingType = !empty($originParams['marketing_type']) ? $originParams['marketing_type'] : Marketing::MARKETING_TYPE_FENXIAO;
        if ($marketingType == Marketing::MARKETING_TYPE_FENXIAO) {
            $where['marketing_id'] = !empty($where['marketing_id']) ? $where['marketing_id'] : '';
            return Marketing::updateRecord($params, $where);
        } else if ($marketingType == Marketing::MARKETING_TYPE_TUANGOU) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_MIAOSHA) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return self::updatePindanMarketing($originParams);
        }
    }

    /**
     * 增加拼单活动
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws MarketingException
     */
    private static function updatePindanMarketing($params)
    {
        $marketingId = $params["marketing_id"];
        //重复判断
        $marketing = Marketing::getRecord(["marketing_id" => $marketingId]);
        if (empty($marketing)) {
            throw new MarketingException(['cus' => 19]);
        }
        $marketingPindan = MarketingPindan::getRecord(["marketing_id" => $marketingId]);
        if (empty($marketingPindan)) {
            throw new MarketingException(['cus' => 19]);
        }

        $marketingName = !empty($params['marketing_name']) ? $params['marketing_name'] : '';
        $pindanPic = !empty($params['pindan_pic']) ? $params['pindan_pic'] : '';
        $pindanDesc = !empty($params['pindan_desc']) ? $params['pindan_desc'] : '';
        $createUserEmail = !empty($params['op_cur_user']) ? $params['op_cur_user'] : '';
        $startTime = !empty($params['start_time']) ? $params['start_time'] : '';
        $endTime = !empty($params['end_time']) ? $params['end_time'] : '';
        $type = Marketing::MARKETING_TYPE_PINDAN;
        $goodsSkuId = !empty($params['goods_sku_id']) ? explode(",", $params['goods_sku_id']) : [];
        $takePlaceIds = !empty($params['take_place_ids']) ? explode(",", $params['take_place_ids']) : [];
        if (empty($goodsSkuId)) {
            throw new MarketingException(['cus' => 12]);
        }
        if (empty($marketingName)) {
            throw new MarketingException(['cus' => 0]);
        }
        if (empty($startTime)) {
            throw new MarketingException(['cus' => 8]);
        }
        if (empty($endTime)) {
            throw new MarketingException(['cus' => 9]);
        }
        if ($startTime >= $endTime) {
            throw new MarketingException(['cus' => 21]);
        }
        if (empty($takePlaceIds)) {
            throw new MarketingException(['cus' => 22]);
        }

        //获取商品的最大最小值
        $skuInfoList = PindanGoodsSku::getRecordMaster(["goods_sku_id" => $goodsSkuId]
            , ["goods_sku_id", "goods_spu_id", "price"]);
        $priceList = [];
        foreach ($skuInfoList as $skuInfo) {
            $priceList[] = $skuInfo["price"];
        }
        $uniquePriceList = array_unique($priceList);
        sort($uniquePriceList);
        $minPrice = $uniquePriceList[0];
        $maxPrice = end($uniquePriceList);

        Marketing::beginTransaction();
        $marketingParams = [
            'marketing_name' => $marketingName,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'online_status' => Marketing::ONLINE_STATUS_QIDONG,
            'marketing_type' => $type,
            'good_count' => count($goodsSkuId),
            'update_user_email' => $createUserEmail,
            'update_time' => date("Y-m-d H:i:s"),
        ];
        Marketing::updateRecord($marketingParams, ["marketing_id" => $marketingId]);

        $pindanParams = [
            "pindan_pic" => $pindanPic,
            "pindan_desc" => $pindanDesc,
            "min_price" => $minPrice,
            "max_price" => $maxPrice,
        ];
        MarketingPindan::updateRecord($pindanParams, ["marketing_id" => $marketingId]);

        //活动商品
        $marketingGoods = MarketingGoods::getRecords(["marketing_id" => $marketingId]);
        if (!empty($marketingGoods)) {
            $ids = array_column($marketingGoods, "id");
            $delRes = MarketingGoods::delete(["id"=>$ids]);
            if ($delRes == 0) {
                throw new MarketingException(['cus' => 7]);
            }
        }
        $marketingGoods = [];
        $tempSkuInfoList = array_column($skuInfoList, null, "goods_sku_id");
        foreach ($goodsSkuId as $key => $skuId) {
            if (empty($tempSkuInfoList[$skuId]["goods_spu_id"])) {
                continue;
            }
            $marketingGoods[$key]["goods_spu_id"] = $tempSkuInfoList[$skuId]["goods_spu_id"];
            $marketingGoods[$key]["goods_sku_id"] = $skuId;
            $marketingGoods[$key]["marketing_id"] = $marketingId;
        }

        MarketingGoods::save($marketingGoods);

        //自提点
        $marketingTakePlaces = MarketingTakePlace::getRecords(["marketing_id" => $marketingId]);
        if (!empty($marketingTakePlaces)) {
            $ids = array_column($marketingTakePlaces, "marketing_take_place_id");
            $delRes = MarketingTakePlace::delete(["marketing_take_place_id"=>$ids]);
            if ($delRes == 0) {
                throw new MarketingException(['cus' => 7]);
            }
        }

        if (!empty($takePlaceIds)) {
            $takePlaceList = TakePlace::select(["take_place_id", "take_place_name"], ["take_place_id" => $takePlaceIds]);
            $tmpTakePlaceList = [];
            foreach ($takePlaceList as $item) {
                $tmpTakePlaceList[$item["take_place_id"]] = $item["take_place_name"];
            }

            $marketingTakePlaces = [];
            foreach ($takePlaceIds as $key => $takePlaceId) {
                $marketingTakePlaces[$key]["take_place_id"] = $takePlaceId;
                $marketingTakePlaces[$key]["marketing_id"] = $marketingId;
                $marketingTakePlaces[$key]["take_place_name"] = $tmpTakePlaceList[$takePlaceId];
            }
            MarketingTakePlace::save($marketingTakePlaces);
        }

        if (!Marketing::commit()) {
            Marketing::rollback();
            throw new MarketingException(["cus" => 5]);
        }

        $picList  = GoodsService::getUrlList($marketingPindan['pindan_pic']);

        KafkaService::productMarketingUpdate([
            'activityId'   =>  $marketingId,
            'startDate'    =>  $startTime,
            'endDate'      =>  $endTime,
            'userId'       =>  config('lifeaccount','life_account_id'),
            'activityName' =>  $marketingName,
            'text'         =>  $pindanDesc,
            'imageId'      =>  $picList[0] ?? '',
            'createTime'   =>  $marketing['create_time'],
            'onlineStatus' =>  Marketing::ONLINE_STATUS_QIDONG,
        ]);

        return true;
    }

    /**
     * 修改活动的状态
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function updateMarketingOnlineStatus($params)
    {
        $marketingId = $params["marketing_id"];
        $marketingType = $params["marketing_type"];
        $onlineStatus = Marketing::ONLINE_STATUS_DAOQI;
        $endTime = date("Y-m-d H:i:s");
        if ($params["online_status"] == Marketing::ONLINE_STATUS_QIDONG) {
            $onlineStatus = Marketing::ONLINE_STATUS_QIDONG;
            $endTime = date("Y-m-d H:i:s", strtotime("+7 day"));
        }
        if ($params["online_status"] == Marketing::ONLINE_STATUS_GUANBI) {
            $onlineStatus = Marketing::ONLINE_STATUS_GUANBI;
            $endTime = date("Y-m-d H:i:s");
        }
        $marketingParams = [
            'online_status' => $onlineStatus,
            'end_time' => $endTime,
        ];

        if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            $marketing = Marketing::getRecord(["marketing_id" => $marketingId]);
            $marketingPindan = MarketingPindan::getRecord(["marketing_id" => $marketingId]);

            $picList  = GoodsService::getUrlList($marketingPindan['pindan_pic']);
            KafkaService::productMarketingUpdate([
                'activityId'   =>  $marketingId,
                'startDate'    =>  $marketing['start_time'],
                'endDate'      =>  $endTime,
                'userId'       =>  config('lifeaccount','life_account_id'),
                'activityName' =>  $marketing['marketing_name'],
                'text'         =>  $marketingPindan['pindan_desc'],
                'imageId'      =>  $picList[0] ?? '',
                'createTime'   =>  $marketing['create_time'],
                'onlineStatus' =>  $onlineStatus,
            ]);
        }


        Marketing::updateRecord($marketingParams, ["marketing_id" => $marketingId, "marketing_type" => $marketingType]);
    }

    /**
     * 切换活动状态
     * @param $marketingId
     * @param $onlineStatus
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function toogleOnlineStatus($marketingId,$onlineStatus)
    {
        if(!in_array($onlineStatus,array_keys(Marketing::$onlineStatusDesc))) {
            return 0;
        }

        $data = [
            'online_status' => $onlineStatus,
        ];
        return Marketing::updateRecord($data, ["marketing_id" => $marketingId]);
    }

    /**
     * 分销活动详情
     * @param $params
     * @return array|mixed
     * @throws \App\Exception\custom\InterfaceException
     */
    public static function marketingInfo($params)
    {
        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : Marketing::MARKETING_TYPE_FENXIAO;
        if ($marketingType == Marketing::MARKETING_TYPE_FENXIAO) {
            return self::fenxiaoMarketingInfo($params);
        } else if ($marketingType == Marketing::MARKETING_TYPE_TUANGOU) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_MIAOSHA) {
            return [];
        } else if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return self::pindanMarketingInfo($params);
        }
    }

    /**
     * 分销活动详情
     * @param $params
     * @return mixed
     * @throws \App\Exception\custom\InterfaceException
     */
    private static function fenxiaoMarketingInfo($params)
    {
        $marketing_info = Marketing::getRecord(['marketing_id' => $params['marketing_id'], "marketing_type" => Marketing::MARKETING_TYPE_FENXIAO]);

        $goodsSkuList = MarketingGoods::marketingGoodsList(['marketing_id' => $params['marketing_id']]);

        $goodsSkuId = array_column($goodsSkuList , 'goods_sku_id');


        $goodsSkuList = GoodsSku::select('*', ['goods_sku_id' => $goodsSkuId]);

        $lifeAccountIds = [];
        if (!empty($goodsSkuList)) {
            $lifeAccountIds = array_column($goodsSkuList, 'life_account_id');
        }
        $lifeAccountList = CommonService::getlifeAccountList(['life_account_id' => $lifeAccountIds]);
        $list = [];

        if (!empty($goodsSkuList)) {
            foreach ($goodsSkuList as $key => $value) {
                $list[$key]['goods_sku_id'] = $value['goods_sku_id'];
                $list[$key]['goods_spu_id'] = $value['goods_spu_id'];
                $list[$key]['life_account_id'] = $value['life_account_id'];
                $list[$key]['goods_name'] = $value['goods_name'];
                $list[$key]['life_account_name'] = !empty($lifeAccountList[$value['life_account_id']]['life_account_name']) ? $lifeAccountList[$value['life_account_id']]['life_account_name'] : '';
            }
        }

        $marketing_info['first_commission_value'] = !empty($marketing_info['first_commission_value']) ? $marketing_info['first_commission_value']/100 : 0;
        $marketing_info['second_commission_value'] = !empty($marketing_info['second_commission_value']) ? $marketing_info['second_commission_value']/100 : 0;

        $info['marketing_info'] = $marketing_info;
        $info['goods_list'] = $list;
        return $info;
    }

    /**
     * 获取生活号加入生活圈天数
     * @param $createTime
     * @return false|float
     */
    private static function countAccountRegisterDays($createTime)
    {
        return ceil((time() - strtotime($createTime)) / 86400);
    }

    /**
     * 拼单活动详情
     * @param $params
     * @return mixed
     * @throws \App\Exception\custom\InterfaceException
     */
    private static function pindanMarketingInfo($params)
    {
        $marketingInfo = Marketing::getRecord(['marketing_id' => $params['marketing_id'], "marketing_type" => Marketing::MARKETING_TYPE_PINDAN]);

        if (empty($marketingInfo))
            throw new GoodsException(['cus' => GoodsException::NOT_FIND_MARKETING]);

        $pindanMarketing = MarketingPindan::getRecord(['marketing_id' => $params['marketing_id']]);
        $lifeAccountList = CommonService::getlifeAccountList(['life_account_id' => [$pindanMarketing["publish_life_account_id"]]]);

        $marketingGoodsList = MarketingGoods::marketingGoodsList(['marketing_id' => $params['marketing_id'], "ORDER" => ["id" => "ASC"]]);
        if (!empty($marketingGoodsList)) {
            $goodsSkuId = array_column($marketingGoodsList , 'goods_sku_id');
            $goodsSkuList = PindanGoodsSku::select('*', ['goods_sku_id' => $goodsSkuId]);
        }
        empty($goodsSkuList) && $goodsSkuList = [];

        $userCount = self::getHaveBuyGoodsUserCount(["marketing_id" => $params['marketing_id']]);
        $userCount = empty($userCount[$params['marketing_id']]) ? 0 : $userCount[$params['marketing_id']];

        $marketingData["life_account_name"] = $marketingData["life_account_icon"] = "";
        if (!empty($lifeAccountList[$pindanMarketing["publish_life_account_id"]])) {
            $marketingData["life_account_admin_id"] = strval($lifeAccountList[$pindanMarketing["publish_life_account_id"]]["life_account_admin_id"]);//客户端需要字符串格式
            $marketingData["life_account_name"] = $lifeAccountList[$pindanMarketing["publish_life_account_id"]]["life_account_name"];
            $marketingData["life_account_icon"] = $lifeAccountList[$pindanMarketing["publish_life_account_id"]]["life_account_icon"];
            $marketingData["life_account_register_days"] = self::countAccountRegisterDays($lifeAccountList[$pindanMarketing["publish_life_account_id"]]['create_time']);
        }
        $marketingData["id"] = $marketingInfo["marketing_id"];
        $marketingData["marketing_name"] = $marketingInfo["marketing_name"];
        $marketingData["good_count"] = $marketingInfo["good_count"];
        $marketingData["start_time"] = $marketingInfo["start_time"];
        $marketingData["end_time"] = $marketingInfo["end_time"];
        $marketingData["online_status"] = $marketingInfo["online_status"];
        $marketingData["marketing_type"] = $marketingInfo["marketing_type"];
        $marketingData["publish_life_account_id"] = $pindanMarketing["publish_life_account_id"];
        $marketingData["pindan_pic"] = $pindanMarketing["pindan_pic"];
        $marketingData["pindan_pic_url"] = GoodsService::getUrlList($marketingData["pindan_pic"]);
        $marketingData["pindan_desc"] = $pindanMarketing["pindan_desc"];
        $marketingData["max_price"] = sprintf("%.2f", $pindanMarketing["max_price"] / 100);
        $marketingData["min_price"] = sprintf("%.2f", $pindanMarketing["min_price"] / 100);
        $marketingData["participate_number"] = $userCount;
        $marketingData["create_time"] = $marketingInfo["create_time"];

        $defaultPic = "SHQ_goods_0_012Xh1AQcMqu";
        $shareDefaultStr = empty($marketingData["pindan_pic"]) ? $defaultPic : $marketingData["pindan_pic"];
        $strList = explode(",", $shareDefaultStr);
        $shareStr = $strList[0];
        $shareRes = Ks3Api::picEncryptUrl($shareStr, 500, 400);
        $shareUrl = empty($shareRes["response"]["data"]["url"]) ? "" :  $shareRes["response"]["data"]["url"];
        $marketingData["share_url"] = $shareUrl;

        $info['marketing_info'] = $marketingData;

        //有用户登录时候，当前用户购买的商品数量信息
        $haveBuyGoodsStatistics = [];
        if (!empty($params["user_id"])) {
            $haveBuyGoodsStatistics = self::getHaveBuyGoodsStatistics(["user_id" => $params["user_id"], "marketing_id" => $marketingData["id"]]);
        }
        //活动中所有购买的商品数量信息
        $allHaveBuyGoodsStatistics = self::getHaveBuyGoodsStatistics(["marketing_id" => $marketingData["id"]]);


        if (!empty($goodsSkuList)) {
            $otaIds = array_unique(array_column($goodsSkuList, "ota_id"));
            $otas = Ota::select(["ota_id", "ota_name"], ["ota_id" => $otaIds]);
            foreach ($otas as $key => $item) {
                $otasData[$item["ota_id"]] = $item;
            }

            //这里是为了排序，按查 marketing_goods 出来的顺序排序
            $tempGoodsSkuList = array_column($goodsSkuList, null, "goods_sku_id");
            foreach ($marketingGoodsList as $key => $value) {
                if (empty($tempGoodsSkuList[$value["goods_sku_id"]])) {
                    continue;
                }
                $item = $tempGoodsSkuList[$value["goods_sku_id"]];
                $goodsSkuList[$key] = $item;
                $goodsSkuList[$key]["desc_pic_url_list"] = GoodsService::getUrlList($item["desc_pic_url"]);
                $goodsSkuList[$key]["ota_name"] = empty($otasData[$item["ota_id"]]["ota_name"]) ? "" : $otasData[$item["ota_id"]]["ota_name"];
                $goodsSkuList[$key]["original_price"] = empty($item["original_price"]) ? '' : sprintf("%.2f", (int)$item["original_price"] / 100);
                $goodsSkuList[$key]["price"] = sprintf("%.2f", $item["price"] / 100);
                $goodsSkuList[$key]["have_buy_goods_count"] = 0;
                //前端当前登录人的数据
                $haveBuyGoodsSkuIds = array_keys($haveBuyGoodsStatistics);
                if (in_array($item["goods_sku_id"], $haveBuyGoodsSkuIds)) {
                    $goodsSkuList[$key]["have_buy_goods_count"] = $haveBuyGoodsStatistics[$item["goods_sku_id"]];
                }

                //后台展示所有购买的数量
                $goodsSkuList[$key]["all_have_buy_goods_count"] = 0;
                $allHaveBuyGoodsSkuIds = array_keys($allHaveBuyGoodsStatistics);
                if (in_array($item["goods_sku_id"], $allHaveBuyGoodsSkuIds)) {
                    $goodsSkuList[$key]["all_have_buy_goods_count"] = $allHaveBuyGoodsStatistics[$item["goods_sku_id"]];
                    $goodsSkuList[$key]["total_amount_sold"] = $allHaveBuyGoodsStatistics[$item["goods_sku_id"]];
                }
            }

            //前端排序，后端不排库存
            if (!empty($params["from"])) {
                foreach ($goodsSkuList as $key => $item) {
                    if ($item["inventory_rest"] == 0) {
                        unset($goodsSkuList[$key]);
                        array_push($goodsSkuList, $item);
                    }
                }
                $goodsSkuList = array_values($goodsSkuList);
            }

        }

        $takePlaceIds = MarketingTakePlace::getRecords(["marketing_id" => $marketingData["id"]], ["take_place_id"]);
        $takePlaces = [];
        if (!empty($takePlaceIds)) {
            $takePlaceIds = array_column($takePlaceIds, "take_place_id");
            $takePlaces = TakePlace::select("*", ["take_place_id" => $takePlaceIds]);
        }

        $info['goods_list'] = !empty($goodsSkuList) ? $goodsSkuList : [];
        $info['take_place'] = $takePlaces;
        return $info;
    }


    public static function getMarketingList($params)
    {
        $where['marketing_id'] = !empty($params['marketing_id']) ? $params['marketing_id'] : '';
        if(!empty($params['marketing_type'])){
            $where['marketing_type'] = !empty($params['marketing_type']) ? $params['marketing_type'] : '';
        }
        $marketing_list = Marketing::getMarketingList($where);
        return $marketing_list;
    }

    /**
     *  获取多个活动的商品列表
     * @param $marketingIds
     * @return array
     * @throws InterfaceException
     */
    public static function getGoodsSkuListByMarketingIds($marketingIds)
    {
        $marketingGoodsList = MarketingGoods::marketingGoodsList(['marketing_id' => $marketingIds, "ORDER" => ["id" => "ASC"]]);

        $goodsSkuList = [];
        if (!empty($marketingGoodsList)) {
            $goodsSkuId = array_column($marketingGoodsList , 'goods_sku_id');
            $goodsSkuList = PindanGoodsSku::select('*', ['goods_sku_id' => $goodsSkuId]);
            $goodsSkuList = array_column((array)$goodsSkuList, null, "goods_sku_id");
        }

        $list = [];
        if (!empty($goodsSkuList)) {
            //活动sku购买数量
            $soldNum = self::getHaveBuyGoodsStatistics(["marketing_id" => $marketingIds]);

            //保持排序
            foreach ($marketingGoodsList as $key => $value) {
                if (empty($goodsSkuList[$value["goods_sku_id"]])) {
                    continue;
                }
                $list[$value['marketing_id']][$key] = $value;
                $item = $goodsSkuList[$value["goods_sku_id"]];
                $list[$value['marketing_id']][$key]['goods_name'] = $item['goods_name'];
                $list[$value['marketing_id']][$key]["desc_pic_url_list"] = GoodsService::getUrlList($item["desc_pic_url"]);
                $list[$value['marketing_id']][$key]["original_price"] = empty($item["original_price"]) ? '' : sprintf("%.2f", (int)$item["original_price"] / 100);
                $list[$value['marketing_id']][$key]["price"] = sprintf("%.2f", $item["price"] / 100);
                $list[$value['marketing_id']][$key]["all_have_buy_goods_count"] = $soldNum[$value["goods_sku_id"]] ?? 0;
                $list[$value['marketing_id']][$key]['inventory_rest'] = $item['inventory_rest'];
            }

            //没有库存的放在最下面
            foreach ($list as $marketingId => $item) {
                foreach($item as $key=>$value) {
                    if ($value["inventory_rest"] == 0) {
                        unset($list[$marketingId][$key]);
                        array_push($list[$marketingId], $value);
                    }
                }
                $list[$marketingId] = array_values($list[$marketingId]);
            }
        }

        return $list;
    }

    /**
     * 获取活动支付用户列表
     * @param $params
     * @return array|mixed
     * @throws InterfaceException
     */
    public static function getMarketingOrderUser($params)
    {
        $url = config('interface', 'order.marketing.marketing_user');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $res = HttpUtil::get($url, $params);
        $data = [];
        if ($res['code'] == 0 && isset($res['response']["result"])) {
            $data = $res["response"]["result"];
        }
        return $data;
    }

   /**
    *判断长度
    *
    */
    public static function utf8Strlen($string = null) {
        // 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
        // // 返回单元个数
        return count($match[0]);
    }
    
    /**
     * 通过发号器拿 id （非雪花）
     * number，获取店铺shop_id用生活号id后两位，商品相关的这里是shop_id的后两位
     * @param $number
     * @param $type
     * @param int $count
     * @return array|mixed
     */
    public static function getIdgenId($number, $type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [], [[
            "type" => $type,
            'number' => (int)$number,
            "count" => $count]]);
        return $res['id_datetime'][$type] ?? [];
    }

    public static function getSnowIdgenId($type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [[
            "type" => $type,
            "count" => $count]], []);
        return $res['id_snow'][$type] ?? [];
    }

    /**
     * 指定活动的已购买商品统计
     * @param array $params
     * @return array|mixed
     * @throws InterfaceException
     */
    public static function getHaveBuyGoodsStatistics($params = [])
    {
        $url = config('interface', 'order.order.have_buy_order_statistics');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $res = HttpUtil::get($url, $params);
        $data = [];
        if ($res['code'] == 0 && isset($res['response']["result"])) {
            $data = $res["response"]["result"];
        }
        return $data;
    }

    /**
     * 参与人数：当前拼单成功支付的订单总数量，退款订单不刨除
     * @param array $params
     * @return array|mixed
     * @throws InterfaceException
     */
    public static function getHaveBuyGoodsUserCount($params = [])
    {
        $url = config('interface', 'order.order.have_buy_goods_user_count');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $res = HttpUtil::get($url, $params);
        $data = [];
        if ($res['code'] == 0 && isset($res['response']["result"])) {
            $data = $res["response"]["result"];
        }
        return $data;
    }
}