<?php

use Api\PhpUtils\Log\FileLog;
use App\Base\Base;
use App\Services\marketing\MarketingService;
use App\Exception\custom\MarketingException;
use App\Services\marketing\MarketingGoodsService;
use \Validate\MarketingGoodsRateValidate;
use \Validate\MarketingOnlineStatusValidate;
use \Validate\MarketingInfoValidate;
use App\Models\marketing\mysql\Marketing;
use App\Models\marketing\mysql\MarketingPindan;
use Api\PhpUtils\Redis\RedisUtil;

class MarketingController extends Base
{

    public function get_marketing_listAction()
    {
        $params = $this->params;
        $list = MarketingService::getMarketingList($params);
        $distributionList['result'] = $list;
        $this->success($distributionList);
    }

    /**
     * 营销列表
     * 后台管理
     */
    public function marketing_listAction()
    {
        $params = $this->params;
        $distributionList = MarketingService::marketingList($params);
        $this->success($distributionList);
    }

    /**
     * 创建活动
     * 后台管理
     */
    public function add_marketingAction()
    {
        $params = $this->params;
        $addMarketing = MarketingService::addMarketing($params);
        if (!empty($addMarketing)) {
            $this->success();
        }
    }

    /**
     * op后台获取创建活动
     * 需要勾选的商品
     *
     * @param $params
     * @return array|mixed
     */
    public function marketing_goods_listAction()
    {
        $params = $this->params;
        $goodsList = MarketingService::marketingGooodsList($params);
        $this->success(['result' => $goodsList]);
    }


    /**
     * 更新数据
     * 后台管理
     *
     */
    public function update_marketingAction()
    {
        $params = $this->params;

        $where['marketing_id'] = !empty($params['marketing_id']) ? $params['marketing_id'] : '';
        $param = [];
        if (empty($where['marketing_id'])) {
            throw new MarketingException(['cus' => 6]);
        }

        if (!empty($params['marketing_name'])) {
            $param['marketing_name'] = $params['marketing_name'];
        }

        if (!empty($params['op_cur_user'])) {
            $param['update_user_email'] = $params['op_cur_user'];
        }

        if (!empty($params['online_status'])) {
            $param['online_status'] = $params['online_status'];
        }

        if (!empty($params['commission_mode'])) {
            $param['commission_mode'] = $params['commission_mode'];
        }

        if (!empty($params['second_commission_value'])) {
            $param['second_commission_value'] = $params['second_commission_value'];
        }

        if (!empty($params['first_commission_value'])) {
            $param['first_commission_value'] = $params['first_commission_value'];
        }

        if (!empty($params['start_time'])) {
            $param['start_time'] = $params['start_time'];
        }

        if (!empty($params['end_time'])) {
            $param['end_time'] = $params['end_time'];
        }

        $srt = MarketingService::updateMarketing($param, $where, $params);

        if (!empty($srt)) {
            $this->success();
        } else {
            throw new MarketingException(['cus' => 7]);
        }
    }


    /**
     * 获取详情数据
     * 后台管理
     *
     */
    public function marketing_infoAction()
    {
        (new MarketingInfoValidate())->validate();

        $params = $this->params;
        $marketingInfo = MarketingService::marketingInfo($params);
        $this->success(['result' => $marketingInfo]);
    }

    /**
     * 获取指定商品分销活动的分成比例（第一分销人的分成比例）
     * @throws Exception
     */
    public function marketing_goods_rateAction()
    {
        (new MarketingGoodsRateValidate())->validate();

        $params = $this->params;
        $goodsSkuIds = explode(",", $params["goods_sku_ids"]);
        $marketingInfo = MarketingGoodsService::getRunningMarketing($goodsSkuIds);
        $this->success(['result' => $marketingInfo]);
    }

    /**
     * 拼单活动修改活动状态
     * @throws Exception
     */
    public function update_marketing_online_statusAction()
    {
        (new MarketingOnlineStatusValidate())->validate();

        MarketingService::updateMarketingOnlineStatus($this->params);
        $this->success();
    }

    /**
     * app内团餐活动列表
     * @throws \App\Exception\custom\InterfaceException
     */
    public function tuancan_listAction()
    {
        $this->params['marketing_type'] = Marketing::MARKETING_TYPE_PINDAN;//1分销 2团购 3秒杀 4团餐
        $this->params['online_status'] = Marketing::ONLINE_STATUS_QIDONG;//状态 ， 1启用，2关闭，3 到期
        $this->params['from'] = 1;//1 小程序前台 默认0 后台
        //正在进行中的 按结束时间正序
        $this->params['sort_field'] = 'end_time';
        $this->params['sort_type'] = 'asc';
        $this->params['need_buy_num'] = false;
        $this->params['activity_status'] = MarketingPindan::ACTIVITY_STATUS_IN_PROGRESS;//1 未开始，2进行中，3已结束
        $list['doing'] = MarketingService::marketingList($this->params)['result'];
        $list['doing'] = $list['doing'] ? array_column($list['doing'], null, 'marketing_id') : [];
        $marketingIdsDoing = array_keys($list['doing']);

        //当天即将开始的 按开始时间正序
        $this->params['page'] = 1;
        $this->params['sort_field'] = 'start_time';
        $this->params['sort_type'] = 'asc';
        $this->params['need_buy_num'] = false;
        $this->params['activity_status'] = MarketingPindan::ACTIVITY_STATUS_START_TODAY;//1 未开始，2进行中，3已结束, 4当日上新（即将开始）
        $list['prepare'] = MarketingService::marketingList($this->params)['result'];
        $list['prepare'] = $list['prepare'] ? array_column((array)$list['prepare'], null, 'marketing_id') : [];
        $marketingIdsPrepare = array_keys($list['prepare']);

        $marketingIds = array_merge($marketingIdsDoing, $marketingIdsPrepare);

        $list = $this->_fillSkuAndOrderInfo($marketingIds,$list);

        //已结束的  按结束时间倒序
        $list['end'] = $this->getTuanCanEndList();

        $list['life_account_id'] = MarketingService::getPublicLifeAccountId();

        $this->success(['result' => $list]);
    }

    private function getTuanCanEndList(){
        try{
            $redis = RedisUtil::getInstance('cache',['serializer'=>'none']);
            $key = "tuancan_endlist_".date('Ymd');
            $list['end'] = $redis->get($key);

            if(empty($list['end'])) {
                $this->params['page'] = 1;
                $this->params['page_size'] = 10;
                $this->params['sort_field'] = 'end_time';
                $this->params['sort_type'] = 'desc';
                $this->params['need_buy_num'] = false;
                $this->params['online_status'] = [Marketing::ONLINE_STATUS_QIDONG, Marketing::ONLINE_STATUS_GUANBI, Marketing::ONLINE_STATUS_DAOQI];//状态 ， 1启用，2关闭，3 到期
                $this->params['activity_status'] = MarketingPindan::ACTIVITY_STATUS_FINISHED;//1 未开始，2进行中，3已结束, 4当日上新（即将开始）
                $list['end'] = MarketingService::marketingList($this->params)['result'];
                $list['end'] = $list['end'] ? array_column($list['end'], null, 'marketing_id') : [];

                $marketingIdsEnd = array_keys($list['end']);
                $list = $this->_fillSkuAndOrderInfo($marketingIdsEnd,$list);

                $redis->set($key,json_encode($list['end']),['ex'=>86400]);//已结束列表 缓存一天
            }else {
                $list['end'] = json_decode($list['end'], true);
            }
        }catch (Exception $e) {
            FileLog::error("获取团餐已结束列表异常", $e->getMessage(), '', 'suntengda@yidian-inc.com');
        }

        return $list['end'] ?? [];
    }

    /**
     * 给列表填充sku和订单相关信息
     * @param $marketingIds
     * @param $list
     * @return mixed
     * @throws \App\Exception\custom\InterfaceException
     */
    private function _fillSkuAndOrderInfo($marketingIds,$list) {
        //获取活动的sku列表
        $skuList = MarketingService::getGoodsSkuListByMarketingIds($marketingIds);
        //获取活动支付用户列表
        $orderUser = MarketingService::getMarketingOrderUser(['marketing_id' => $marketingIds]);
        //获取活动支付用户数
        $buyNum = MarketingService::getHaveBuyGoodsUserCount(['marketing_id' => $marketingIds]);

        //组合sku和order信息
        foreach ($list as &$listPart) {
            foreach ($listPart as $marketingId => &$value) {
                $value['sku_list'] = $skuList[$marketingId] ?? [];
                $value['order_user'] = $orderUser[$marketingId] ?? [];
                $value['participate_number'] = $buyNum[$marketingId] ?? 0;
            }
            unset($value);
            $listPart = array_values($listPart);
        }
        unset($listPart);

        return $list;
    }





    /**
     * 切换活动状态
     * @throws \App\Exception\custom\ParamException
     */
    public function toogle_yingxiao_online_statusAction()
    {
        (new MarketingOnlineStatusValidate())->scene('yingxiao')->validate();
        $res = MarketingService::toogleOnlineStatus($this->params['marketing_id'],$this->params['online_status']);

        $this->success(['result' => $res]);
    }

    /**
     * 营销中心-活动列表
     * @throws Exception
     */
    public function yingxiao_listAction()
    {
        $lists = MarketingService::yingxiaoList($this->params);
        $this->success(['result' => $lists]);
    }
}