<?php
/**
 * 促销活动
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/12/18
 * Time: 12:08
 */

namespace JinDouYun\Model\Market;


use JinDouYun\Cache\ActivityLimitCache;
use JinDouYun\Controller\Common\Logger;
use JinDouYun\Dao\Market\DActivityGoodsUserLog;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Goods\MGoods;
use JinDouYun\Model\GoodsManage\MSku;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\GoodsBasicRelevant;
use JinDouYun\Dao\Market\DActivity;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\Price\MPrice;

class MActivity extends MBaseModel
{
    private $onlineUserId;

    private $onlineEnterpriseId;

    private $objDActivity;

    private $objMActivityGoods;

    private $areaCode;

    private $objActivityLimitCache;

    private $objMSku;

    /**
     * true=>app false=>manage
     * @var boolean
     */
    private $isFront;//是否是前台调用此Model

    /**
     * @var DActivityGoodsUserLog
     */
    private $objDActivityGoodsUserLog;

    /**
     * MActivity constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @param null $areaCode
     * @param bool $isFront
     * @throws \Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId, $areaCode = null,$isFront = true)
    {
        $this->isFront = $isFront;
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;
        $this->areaCode = $areaCode;
        parent::__construct($this->onlineEnterpriseId, $onlineUserId);
        $this->objDActivity = new DActivity('default');
        $this->objDActivity->setTable($this->objDActivity->get_Table() . '_' . $this->onlineEnterpriseId);
        $this->objMActivityGoods = new MActivityGoods($this->onlineUserId, $this->onlineEnterpriseId);
        //$this->objDActivity->setSearchIndex('activity_search')->setType('activity');
        $this->objMSku = new MSku($this->onlineUserId,$this->onlineEnterpriseId);
        $this->objDActivityGoodsUserLog = new DActivityGoodsUserLog();
        $this->objActivityLimitCache = new ActivityLimitCache($this->onlineEnterpriseId);
    }

    /**
     * 新增
     * @param $params
     * @return ResultWrapper
     */
    public function add($params)
    {
        $details = $params;
        $activityGoods = $params['activityGoods'];
        unset($params['activityGoods']);
        $sql = 'SELECT * FROM qianniao_activity_' . $this->onlineEnterpriseId . ' WHERE deleteStatus=' . StatusCode::$standard . ' AND activityType=' . $params['activityType'] . ' AND enableStatus=' . StatusCode::$standard . ' AND '.$params['startTime'].' >= startTime and '.$params['startTime'].' <= endTime';
        $dbResult = $this->objDActivity->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        if (!empty($dbResult)) {
            return ResultWrapper::fail('此时段已有启用活动', ErrorCode::$paramError);
        }
        $this->objDActivity->beginTransaction();
        $dbResult = $this->objDActivity->insert($params);
        if ($dbResult === false) {
            $this->objDActivity->rollBack();
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        foreach ($activityGoods as &$val) {
            $val['activityId'] = $dbResult;
        }
        $activityId = $dbResult;
        unset($dbResult);

        $dbResult = $this->objMActivityGoods->add($activityGoods, true);
        if (!$dbResult->isSuccess()) {
            $this->objDActivity->rollBack();
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }

        foreach ($activityGoods as $goods) {
            $values = explode('|', rtrim(str_repeat($goods['goodsId'] . '|', $goods['activityNum']), '|'));
            $this->objActivityLimitCache->lPush($activityId, $goods['goodsId'], $goods['skuId'], $values);
        }
        $this->objActivityLimitCache->writeActivity($activityId, $details);//缓存活动
        //self::updateEsData($activityId, $params);
        $this->objDActivity->commit();
        return ResultWrapper::success($dbResult);
    }

    /**
     * 更新ES
     * @param $id
     * @param $params
     */
    public function updateEsData($id, $params)
    {
        $esData = [
            'enterpriseId'     => $this->onlineEnterpriseId,//enterpriseId,
            'id'               => $id,//自增id,
            'activityType'     => $params['activityType'],//活动类型
            'title'            => $params['title'],//名称
            'remark'           => $params['remark'],//客户沟通
            'startTime'        => $params['startTime'],//活动开始时间,
            'endTime'          => $params['endTime'],//活动结束时间
            'enableStatus'     => $params['enableStatus'],
            'images'           => json_decode($params['images'], true),
            'useShop'          => $params['useShop'],//使用范围
            'customerRange'    => $params['customerRange'],//客户范围
            'customerSourceId' => isset($params['customerSourceId']) ? $params['customerSourceId'] : '',//客户id 1,2
            'sort'             => isset($params['sort']) ? $params['sort'] : 0,
            'describe'         => $params['describe'],
            'createTime'       => $params['createTime'],
            'updateTime'       => $params['updateTime'],
            'isEnd'            => StatusCode::$standard,
            'deleteStatus'     => StatusCode::$standard,
            'auditStatus'      => StatusCode::$auditStatus['auditing'],
        ];
        $_id = self::createEsDocumentId($id);
        $result = $this->objDActivity->addUpSearchIndexDocument($esData, $_id);

        if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
            //echo "es操作成功";
            //return;
        } else {
            //echo "es操作失败";
        }
    }

    /**
     * @param $id
     * @return string
     */
    private function createEsDocumentId($id)
    {
        return 'EnterpriseId_' . $this->onlineEnterpriseId . '_id_' . $id;
    }

    /**
     * 详情
     *
     * @param $id
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getInfo($id)
    {
        $dbResult = $this->objDActivity->get_by('id', $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        $activityGoods = $this->objMActivityGoods->getActivityGoods(
            ['activityId' => $id, 'deleteStatus' => StatusCode::$standard],
            'id,activityId,goodsId,basicGoodsId,skuId,price,shopId,activityNum,limitNum'
        );//获取详情数据
        if (!$activityGoods->isSuccess()) {
            return ResultWrapper::fail($activityGoods->getData(), ErrorCode::$dberror);
        }

        $allowActivityGoods = self::filterActivityGoods($activityGoods->getData());
        $dbResult['activityGoods'] = $allowActivityGoods;
        return ResultWrapper::success(self::format($dbResult));
    }




    /**
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    private function format($data)
    {
        if (empty($data)) return $data;
        $data['useShopName'] = '';
        if (isset($data['useShop'])) {
            $data['useShopName'] = ($data['useShop'] == 0) ? ['全店铺'] : array_values(self::getNameByShopId(explode(',', $data['useShop'])));
        }
        $activityGoods = $data['activityGoods'];
        $skuIds = array_column($activityGoods,'skuId');
        $objMSku = new MSku($this->onlineUserId,$this->onlineEnterpriseId);
        $skuMapRes = $objMSku->getSpecNameBySkuId($skuIds);
        $skuMap = [];
        if ($skuMapRes->isSuccess()){
            $skuMap = $skuMapRes->getData();
        }
        if (!empty($activityGoods)) {
            $objActivityLimitCache = new ActivityLimitCache($this->onlineEnterpriseId);
            foreach ($activityGoods as &$goods) {
                $goods['surplusNum'] = (int)$objActivityLimitCache->getLen($data['id'], $goods['goodsId'], $goods['skuId']);
                $goods['specGroup'] = isset($skuMap[$goods['skuId']]) ? $skuMap[$goods['skuId']]['specGroup'] : [];
            }
        }
        $data['activityGoods'] = $activityGoods;
        if (!empty($data['images'])) $data['images'] = json_decode($data['images'], true);
        return $data;
    }

    /**
     * 编辑
     *
     * @param $params
     * @param $id
     * @param $deleteArray
     * @return ResultWrapper
     */
    public function edit($params, $id, $deleteArray)
    {
        $details = $params;
        $activityGoods = $params['activityGoods'];
        unset($params['activityGoods']);
        $this->objDActivity->beginTransaction();
        $dbResult = $this->objDActivity->update($params, $id);
        if ($dbResult === false) {
            $this->objDActivity->rollBack();
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        $dbResult = $this->objMActivityGoods->edit($activityGoods, $id, $deleteArray);
        if (!$dbResult->isSuccess()) {
            $this->objDActivity->rollBack();
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }

        foreach ($activityGoods as $goods) {
            //先删除key
            $this->objActivityLimitCache->delKey($id, $goods['goodsId'],$goods['skuId']);
            //重新写入
            $values = explode('|', rtrim(str_repeat($goods['goodsId'] . '|', $goods['activityNum']), '|'));
            $this->objActivityLimitCache->lPush($id, $goods['goodsId'], $goods['skuId'], $values);
        }
        $this->objActivityLimitCache->writeActivity($id, $details);//缓存活动
        //self::updateEsData($id, $params);
        $this->objDActivity->commit();
        return ResultWrapper::success($dbResult);
    }

    /**
     * 审核
     * @param $params
     * @return ResultWrapper
     */
    public function updateAuditStatus($params)
    {

        $dbResult = $this->objDActivity->update(['auditStatus' => $params['auditStatus']], $params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        /*$_id = self::createEsDocumentId($params['id']);
        $this->objDActivity->esupdateTypeFieldVaule([
            'auditStatus' => $params['auditStatus'],
        ], $_id);*/
        return ResultWrapper::success($dbResult);
    }

    /**
     * 启用/禁用
     * @param $params
     * @return ResultWrapper
     */
    public function updateEnableStatus($params)
    {
        if ($params['enableStatus'] == StatusCode::$standard) {
            $dbResult = $this->objDActivity->get(['id' => $params['id']]);
            if ($dbResult === false) {
                return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
            }
            if (empty($dbResult)) {
                return ResultWrapper::fail('活动不存在', ErrorCode::$paramError);
            }
            $sql = 'SELECT * FROM qianniao_activity_' . $this->onlineEnterpriseId . ' WHERE deleteStatus=' . StatusCode::$standard . ' AND activityType=' . $params['activityType'] . ' AND enableStatus=' . StatusCode::$standard . ' AND ((startTime>=' . $dbResult['startTime'] . ' AND startTime <=' . $dbResult['endTime'] . ') OR (startTime <=' . $dbResult['startTime'] . ' AND endTime>=' . $dbResult['endTime'] . ') OR (endTime>=' . $dbResult['startTime'] . ' AND endTime<=' . $dbResult['endTime'] . '))';
            $dbResult = $this->objDActivity->query($sql);
            if ($dbResult === false) {
                return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
            }
            if (!empty($dbResult)) {
                return ResultWrapper::fail('此时段已有启用活动', ErrorCode::$paramError);
            }
        }

        $dbResult = $this->objDActivity->update(['enableStatus' => $params['enableStatus']], $params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }

        $activity = $this->objActivityLimitCache->getActivity($params['id']);
        if (!empty($activity)){
            //修改缓存数据
            $activity['enableStatus'] = $params['enableStatus'];
            $this->objActivityLimitCache->writeActivity($params['id'],$activity);
        }

        /*$_id = self::createEsDocumentId($params['id']);
        $this->objDActivity->esupdateTypeFieldVaule([
            'enableStatus' => $params['enableStatus'],
        ], $_id);*/
        return ResultWrapper::success($dbResult);
    }

    /**
     * 删除
     * @param $id
     * @return ResultWrapper
     * @throws \Exception
     */
    public function del($id)
    {
        $dbResult = $this->objDActivity->update(['deleteStatus' => StatusCode::$delete], $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        $selectParams = [
            'activityId' => $id
        ];
        $activityGoods = $this->objMActivityGoods->getActivityGoods($selectParams, '*', false);
        if (!$activityGoods->isSuccess()) {
            return ResultWrapper::fail($activityGoods->getData(), ErrorCode::$dberror);
        }
        $activityGoods = $activityGoods->getData();
        foreach ($activityGoods as $goods) {
            //删除key
            $this->objActivityLimitCache->delKey($id, $goods['goodsId'], $goods['skuId']);
        }
        /*$_id = self::createEsDocumentId($id);
        $this->objDActivity->esupdateTypeFieldVaule([
            'deleteStatus' => StatusCode::$delete
        ], $_id);*/
        return ResultWrapper::success($dbResult);
    }

    /**
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAll($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $where = 'deleteStatus = '.StatusCode::$standard;
        if( isset($selectParams['title']) && !empty($selectParams['title']) ){
            $where .= ' and title like "%'.$selectParams['title'].'%"';
        }
        if( isset($selectParams['useShop']) && !empty($selectParams['useShop']) ){
            $where .= ' and useShop  ='.$selectParams['useShop'];
        }
        if( isset($selectParams['isEnd']) && !empty($selectParams['isEnd']) ){
            $where .= ' and isEnd  ='.$selectParams['isEnd'];
        }
        if( isset($selectParams['enableStatus']) && !empty($selectParams['enableStatus']) ){
            $where .= ' and enableStatus  ='.$selectParams['enableStatus'];
        }
        if( isset($selectParams['start']) && !empty($selectParams['start']) ){
            $where .= ' and createTime  >='.$selectParams['start'];
        }
        if( isset($selectParams['end']) && !empty($selectParams['end']) ){
            $where .= ' and createTime  <='.$selectParams['end'];
        }


        $dbResult = $this->objDActivity->select($where, '*', 'createTime DESC', $limit, $offset);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        $total = $this->objDActivity->count($selectParams);
        $return = [
            'data'  => self::formatAll($dbResult),
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * @param $data
     * @return mixed
     */
    private function formatAll($data)
    {
        if (empty($data)) return $data;
        foreach ($data as &$val) {
            $val['useShopName'] = ($val['useShop'] == 0) ? ['全店铺'] : array_values(self::getNameByShopId(explode(',', $val['useShop'])));
        }
        return $data;
    }

    /**
     *
     * @param $shopIds
     * @return array
     */
    public function getNameByShopId($shopIds)
    {
        $objGoodsBasicRelevantCache = new GoodsBasicRelevant($this->onlineEnterpriseId);
        $result = [];
        foreach ($shopIds as $shopId) {
            if (!empty($shopId)) $result[] = $objGoodsBasicRelevantCache->getNameByShopId($shopId);
        }
        return $result;
    }

    /**
     * 搜索
     * @param $selectParams
     * @return ResultWrapper
     */
    public function search($selectParams)
    {
        $defaultDSL = [
            'from' => $selectParams['offset'],
            'size' => $selectParams['limit'],
            'sort' => [
                'createTime' => [
                    'order' => 'desc'
                ],
            ],
        ];

        $dsl = [];
        $dsl['query']['bool']['must'][] = [
            'term' => ['enterpriseId' => $this->onlineEnterpriseId],
        ];

        //名称
        if (!empty($selectParams['title'])) {
            $dsl['query']['bool']['must'][] = [
                'multi_match' => [
                    'fields'    => ['title'],
                    'query'     => $selectParams['title'],
                    'fuzziness' => 'AUTO',
                ],
            ];
        }

        //使用范围
        if (!empty($selectParams['useShop'])) {
            $dsl['query']['bool']['must'][] = [
                'multi_match' => [
                    'fields'    => ['useShop'],
                    'query'     => $selectParams['useShop'],
                    'fuzziness' => 'AUTO',
                ],
            ];
        }

        //发放方式
        if (!empty($selectParams['activityType'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['activityType' => $selectParams['activityType']]];
        }

        //审核状态
        if (!empty($selectParams['enableStatus'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['enableStatus' => $selectParams['enableStatus']]];
        }

        //审核状态
        if (!empty($selectParams['auditStatus']) && isset($selectParams['auditStatus'])) {
            $dsl['query']['bool']['filter'][] =
                ['term' => ['auditStatus' => $selectParams['auditStatus']]];
        }


        //时间
        if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
            $dsl['query']['bool']['must'][] = [
                'range' => [
                    'createTime' => [
                        'gte' => $selectParams['start'],
                        'lte' => $selectParams['end'],
                    ]
                ]
            ];
        } else {
            if (!empty($selectParams['start'])) {
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'createTime' => [
                            'gte' => $selectParams['start'],
                        ]
                    ]
                ];
            }

            if (!empty($selectParams['end'])) {
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'createTime' => [
                            'lte' => $selectParams['end'],
                        ]
                    ]
                ];
            }
        }

        //活动是否结束
        if (!empty($selectParams['isEnd'])) {
            $nowTime = time();
            if ($selectParams['isEnd'] == StatusCode::$standard) {
                //未结束
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'startTime' => [
                            'gte' => $nowTime,
                        ]
                    ]
                ];
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'endTime' => [
                            'lte' => $nowTime,
                        ],
                    ]
                ];
            } elseif ($selectParams['isEnd'] == StatusCode::$delete) {
                //已结束
                $dsl['query']['bool']['must'][] = [
                    'range' => [
                        'endTime' => [
                            'lte' => $nowTime,
                        ],
                    ]
                ];
            }
        }

        $dsl = array_merge($defaultDSL, $dsl);
        $result = $this->objDActivity->getSearchQueryDsl($dsl);
        if (isset($result['status']) && $result['status'] == 400) {
            return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return ResultWrapper::success([
                'data'  => [],
                'total' => 0
            ]);
        }
        $total = $result['hits']['total'];
        $dbResult = $result['hits']['hits'];

        $list = [];
        foreach ($dbResult as $key => &$value) {
            $data = [];
            $data = $value['_source'];
            $list[] = $data;
        }

        $return = [
            'data'  => self::formatAll($list),
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 获取活动
     * ['goodsId','activityType','customerType']
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getActivity($selectParams)
    {
        $this->objDActivity->setTable('qianniao_activity_goods_'.$this->onlineEnterpriseId );

        $nowTime = time();
        if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])) {
            $sql = 'SELECT a.id as activityId,a.images,a.title,a.startTime,a.endTime,a.remark,a.activityType,g.activityNum,g.limitNum,g.price,g.basicGoodsId,g.id as goodsActivityId,g.skuId,g.goodsId,g.shopId FROM qianniao_activity_' . $this->onlineEnterpriseId . ' as a LEFT JOIN qianniao_activity_goods_' . $this->onlineEnterpriseId . ' as g ON a.id=g.activityId WHERE a.enableStatus=' . StatusCode::$standard . ' AND a.deleteStatus=' . StatusCode::$standard . ' AND a.auditStatus=' . StatusCode::$auditStatus['auditPass'] . ' AND g.deleteStatus=' . StatusCode::$standard . ' AND a.startTime<' . $nowTime . ' AND a.endTime> ' . $nowTime . ' AND (a.customerRange=' . StatusCode::$standard . ' OR FIND_IN_SET(' . $selectParams['customerType'] . ',a.customerSourceId))';
        } else {
            $sql = 'SELECT a.id as activityId,a.images,a.title,a.startTime,a.endTime,a.remark,a.activityType,g.activityNum,g.limitNum,g.price,g.basicGoodsId,g.id as goodsActivityId,g.skuId,g.goodsId,g.shopId FROM qianniao_activity_' . $this->onlineEnterpriseId . ' as a LEFT JOIN qianniao_activity_goods_' . $this->onlineEnterpriseId . ' as g ON a.id=g.activityId WHERE a.enableStatus=' . StatusCode::$standard . ' AND a.deleteStatus=' . StatusCode::$standard . ' AND a.auditStatus=' . StatusCode::$auditStatus['auditPass'] . ' AND g.deleteStatus=' . StatusCode::$standard . ' AND a.startTime<' . $nowTime . ' AND a.endTime> ' . $nowTime . ' AND (a.customerRange=' . StatusCode::$standard . ')';
        }

        if (isset($selectParams['skuIds']) && !empty($selectParams['skuIds'])){
            $sql .= ' AND g.skuId IN(' . $selectParams['skuIds'] . ')';
        }

        if (isset($selectParams['goodsId']) && !empty($selectParams['goodsId'])) {
            $sql .= ' AND g.goodsId IN(' . $selectParams['goodsId'] . ')';
        }
        if (isset($selectParams['activityType']) && !empty($selectParams['activityType'])) {
            $sql .= ' AND a.activityType=' . $selectParams['activityType'];
        }
        $dbResult = $this->objDActivity->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivity->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取秒杀活动
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getActivityAll()
    {
        //首页未登录获取秒杀活动
        if (!empty($this->onlineUserId)) {
            $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
            $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
            if (!$dbResult->isSuccess()) {
                return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
            }
            $customer = $dbResult->getData();
            unset($dbResult);
            $selectParams['customerType'] = $customer['type'];
        }
        $selectParams['activityType'] = StatusCode::$activityType['secKill'];
        $dbResult = self::getActivity($selectParams);
        if (!$dbResult->isSuccess()) {
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }

        $allowActivityGoods = self::filterActivityGoods($dbResult->getData());
        $return = [
            'data' => self::formatActivity($allowActivityGoods),
        ];
        return ResultWrapper::success($return);
    }

    /**
     * @param $data
     * @return ResultWrapper
     * @throws \Exception
     */
    public function formatActivity($data)
    {
        if (empty($data)) return $data;
        $objGoodsBasicRelevant = new GoodsBasicRelevant($this->onlineEnterpriseId);
        $objMInventory = new MPrice($this->onlineUserId, $this->onlineEnterpriseId);


        $selectParam = [];
        foreach ($data as &$val) {
            if (isset($val['images']) && !empty($val['images'])) $val['activityImages'] = json_decode($val['images'], true);
            $val['goodsName'] = $objGoodsBasicRelevant->getNameByBasicId($val['basicGoodsId'], 'title');
            $val['images'] = $objGoodsBasicRelevant->getNameByBasicId($val['basicGoodsId'], 'images');
            $val['description'] = htmlspecialchars_decode($objGoodsBasicRelevant->getNameByBasicId($val['basicGoodsId'], 'description'));
            $selectParam['material'][$val['shopId']][] = $val['goodsId'];
        }

        $dbResult = $objMInventory->getPrice($selectParam);
        if (!$dbResult->isSuccess()) {
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }
        //商品价格信息
        $goodsArr = [];
        foreach ($dbResult->getData() as $shopPriceArr) {
            foreach ($shopPriceArr as $goodsId => $goodsSkuArr) {
                $goodsArr[$goodsId] = $goodsSkuArr;
            }
        }

        //拼接单位+属性
        $skuMapping = [];
        $skuResult = $this->objMSku->getSpecNameBySkuId(array_column($data,'skuId'));
        if (!$skuResult->isSuccess()){
            file_put_contents('/www/wwwroot/logs/apiqnys.liuniukj.com/MActivity_error.log', date('Y-m-d H:i:s') . '错误信息|sql错误 ：' . var_export($skuResult->getData()) . PHP_EOL, FILE_APPEND);
        }else{
            $skuMapping = $skuResult->getData();
        }

        unset($val);
        foreach ($data as &$val) {
            $priceInfo = isset($goodsArr[$val['goodsId']][$val['skuId']]) ? $goodsArr[$val['goodsId']][$val['skuId']] : [];//此商品规格的价格信息
            $val['salePrice'] = isset($priceInfo['salePrice']) ? $priceInfo['salePrice'] : '0.00';
            $val['unitName'] = isset($skuMapping[$val['skuId']]) ? $skuMapping[$val['skuId']]['unitName'] : '';
            $val['specGroup'] = isset($skuMapping[$val['skuId']]) ? $skuMapping[$val['skuId']]['specGroup'] : [];
        }

        return $data;
    }

    /**
     * 按区域过滤活动商品 (只保留有效商品)
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function filterActivityGoods($data)
    {
        $goodsIds = array_values(array_column($data, 'goodsId'));
        $objMGoods = new MGoods($this->onlineEnterpriseId, true, $this->onlineUserId);
        $pageParams = pageToOffset(1, count($data));
        $selectParams = [
            'limit'        => $pageParams['limit'],
            'offset'       => $pageParams['offset'],
            'userCenterId' => $this->onlineUserId,
            'areaCode'     => $this->areaCode,
            'goodsIds'     => $goodsIds
        ];

        $result = $objMGoods->search($selectParams);
        if (!$result->isSuccess()) {
            return $data;
        }
        $allowGoods = [];
        $searchData = $result->getData();
        if (empty($searchData) && $this->isFront === true){
            //所有商品都不在此区域销售
            return [];
        }else{
            return $data;
        }
        $searchData = isset($searchData['data']) ? $searchData['data'] : [];
        foreach ($searchData as $key => $val) {
            $allowGoods[$val['id']] = $val;
        }

        foreach ($data as $key => $val) {
            if (!isset($allowGoods[$val['goodsId']])) {
                unset($data[$key]);
                continue;
            }
            //拼接当前商品sku的市场价和原价
            foreach ($allowGoods[$val['goodsId']]['skuData'] as $sku) {
                if (isset($val['skuId']) && isset($sku['skuId']) && $val['skuId'] == $sku['skuId']) {
                    $data[$key]['originPrice'] = isset($sku['originPrice']) ? $sku['originPrice'] : 0;//商品原价
                    $data[$key]['marketPrice'] = $sku['marketPrice'];//商品市场价
                    $data[$key]['unitName'] = $sku['unitName'];//规格名称
                }
            }
        }
        return array_values($data);
    }

    /**
     * Doc: (des="根绝条件获取商品秒杀以及优惠活动价格")
     * User: XMing
     * Date: 2020/7/10
     * Time: 10:18 上午
     * @param array $condition
     * @return ResultWrapper
     */
    private function selectCondition(array $condition)
    {
        $nowTime = time();
        $fields = 'a.id as activityId,a.activityType,a.title,a.startTime,a.endTime,
                   g.goodsId,g.skuId,g.price,g.basicGoodsId,
                   g.shopId,g.activityNum,g.limitNum,g.haveBuyNum';
        $sql = 'select '.$fields.' from qianniao_activity_goods_'.$this->onlineEnterpriseId.' as g 
                left join qianniao_activity_'.$this->onlineEnterpriseId.' as a 
                on g.activityId = a.id 
                where a.deleteStatus = '.StatusCode::$standard.' 
                and a.enableStatus = '.StatusCode::$standard.' 
                and a.auditStatus = '.StatusCode::$auditStatus['auditPass'].' 
                and startTime<'.$nowTime.' and endTime > '.$nowTime;
        //店铺筛选
        if (isset($condition['shopId']) && !empty($condition['shopId'])){
            $sql .= ' and find_in_set('.$condition['shopId'].',a.useShop) ';
        }
        //客户筛选
        if (isset($condition['customerId']) && !empty($condition['customerId'])){
            $sql .= ' and (a.customerRange = '.StatusCode::$standard.' or find_in_set('.$condition['customerId'].',a.customerSourceId))';
        }

        //goodsId搜索
        if (isset($condition['goodsIds']) && !empty($condition['goodsIds'])){
            $goodsIdsStr = is_array($condition['goodsIds']) ? implode(',',$condition['goodsIds']) : $condition['goodsIds'];
            $sql .= ' and g.goodsId in('.$goodsIdsStr.') ';
        }

        $dbResult = $this->objDActivity->query($sql);
        if ($dbResult === false){
            return ResultWrapper::fail($this->objDActivity->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * Doc: (des="根据活动ids及客户id获取，活动剩余数量，以及用户剩余购买数量")
     * User: XMing
     * Date: 2020/7/10
     * Time: 5:10 下午
     * @param array $condition
     * @return ResultWrapper
     */
    private function selectLimitCondition(array $condition)
    {
        $fields = 'activityId,shopId,goodsId,skuId,num,customerId';
        $sql = 'select '.$fields.' from qianniao_activity_goods_user_log_'.$this->onlineEnterpriseId.' 
                where shopId = '.$condition['shopId'];

        //客户id
        if (isset($condition['customerId']) && !empty($condition['customerId'])){
            $sql .= ' and customerId = '.$condition['customerId'];
        }

        //活动ids
        if (isset($condition['activityIds']) && !empty($condition['activityIds'])){
            $activityIdsStr = is_array($condition['activityIds']) ? implode(',',$condition['activityIds']) : $condition['activityIds'];
            $sql .= ' and activityId in('.$activityIdsStr.') ';
        }

        $dbResult = $this->objDActivity->query($sql);
        if ($dbResult === false){
            return ResultWrapper::fail($this->objDActivity->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * Doc: (des="计算用户已购数量")
     * User: XMing
     * Date: 2020/7/10
     * Time: 5:07 下午
     * @param array $selectParams
     * @return ResultWrapper
     */
    private function getAllowBuyNumByParams(array $selectParams)
    {
        $returnData = [];
        $conditions = [];
        foreach ($selectParams['activity'] as $shopId => $activityId){
            $returnData[$shopId] = [];
            $conditions[$shopId] = [
                'shopId' => $shopId,
                'customerId' => isset($selectParams['customerId']) ? $selectParams['customerId'] : 0,
                'activityIds' => $activityId
            ];
        }

        if (empty($conditions)){
            return ResultWrapper::success($returnData);
        }

        //获取数据
        $activityData = [];
        foreach ($conditions as $condition){
            $result = self::selectLimitCondition($condition);
            if (!$result->isSuccess()){
                return ResultWrapper::fail($result->getData(),$result->getErrorCode());
            }
            $activityResult = $result->getData();
            $activityData = array_merge($activityData,$activityResult);
        }

        if (empty($activityData)){
            return ResultWrapper::success($returnData);
        }

        if (isset($selectParams['isCalCart']) && $selectParams['isCalCart'] === true){
            //统计购物车中已经加入的活动商品数
        }

        unset($returnData);
        $returnData = [];
        foreach ($activityData as $item){
            if (!isset($returnData[$item['shopId']][$item['goodsId']][$item['skuId']][$item['activityId']]['num'])){
                $returnData[$item['shopId']][$item['goodsId']][$item['skuId']][$item['activityId']]['num'] = 0;
            }
            $returnData[$item['shopId']][$item['goodsId']][$item['skuId']][$item['activityId']]['num'] = bcadd($returnData[$item['shopId']][$item['goodsId']][$item['skuId']][$item['activityId']]['num'],$item['num'],0);
        }
        return ResultWrapper::success($returnData);
    }

    /**
     * Doc: (des="通过goodsId,获取商品的活动价格信息")
     * User: XMing
     * Date: 2020/7/10
     * Time: 12:11 下午
     *
     * result des:
     * @activityNum int 活动限购数量
     * @limitNum int 用户限购数量
     * @haveBuyNum int 活动已购数量
     * @userBuyLogNum int 用户已购数量
     * @userAllowNum int 用户可够数量
     * @activityAllowNum int 活动剩余数量
     *
     * @param array $selectParams
     * @return ResultWrapper
     */
    public function getActivityPriceByParams(array $selectParams)
    {
        // 初始化所有活动物料价格
        $returnData = [];
        $conditions = [];
        foreach ($selectParams['material'] as $shopId => $goodsId) {
            $returnData[$shopId] = [];
            $conditions[$shopId] = [
                'shopId' => $shopId,
                'customerId' => isset($selectParams['customerId']) ? (int) $selectParams['customerId'] : 0,
            ];
            $conditions[$shopId]['goodsIds'] = $goodsId;
        }

        if (empty($conditions)){
            return ResultWrapper::success($returnData);
        }
        //获取这批商品活动价格信息,一般情况下只会有一个shopId
        $activityData = [];
        foreach ($conditions as $shopId =>  $condition){
            $result = self::selectCondition($condition);
            if (!$result->isSuccess()){
                return ResultWrapper::fail($result->getData(),$result->getErrorCode());
            }
            $activityResult = $result->getData();
            $activityData = array_merge($activityData,$activityResult);
        }
        if (empty($activityData)){
            return ResultWrapper::success($returnData);
        }

        //将数据的格式统一为，全国价格格式
        unset($returnData);
        $returnData = [];
        unset($conditions);
        foreach ($activityData as $item){
            $returnData[$item['shopId']][$item['goodsId']][$item['skuId']] = [
                'activityPrice' => $item['price'],
                'goodsId' => $item['goodsId'],
                'basicGoodsId' => $item['basicGoodsId'],
                'skuId' => $item['skuId'],
                'shopId' => $item['shopId'],
                'activityNum' => $item['activityNum'],//活动限购数量
                'limitNum' => $item['limitNum'],//用户限购数量
                'activityId' => $item['activityId'],
                'activityName' => $item['title'],
                'haveBuyNum' => $item['haveBuyNum'],//活动已购数量
            ];
            $conditions['activity'][$item['shopId']][] = $item['activityId'];
        }


        //获取用户商品的已购数量
        $conditions['customerId'] = isset($selectParams['customerId']) ? $selectParams['customerId'] : 0;
        $activityUserLogResult = self::getAllowBuyNumByParams($conditions);
        if (!$activityUserLogResult->isSuccess()){
            return ResultWrapper::fail($activityUserLogResult->getData(),$activityUserLogResult->getErrorCode());
        }
        $activityUserLogData = $activityUserLogResult->getData();
        //计算活动商品用户剩余可购买数量，活动商品剩余数量
        foreach ($returnData as $shopId => $datum){
            foreach ($datum as $goodsId => $items){
                foreach ($items as $skuId => $item){
                    //获取此活动用户已购数量
                    $buyLogNum = isset($activityUserLogData[$shopId][$goodsId][$skuId][$item['activityId']]) ? $activityUserLogData[$shopId][$goodsId][$skuId][$item['activityId']]['num'] : 0;
                    $returnData[$shopId][$goodsId][$skuId]['userBuyLogNum'] = $buyLogNum;//用户已购数量 (可购数量+已购数量=用户限购数量)
                    $returnData[$shopId][$goodsId][$skuId]['userAllowNum'] = bcsub($item['limitNum'],$buyLogNum,0);//用户可购数量
                    $returnData[$shopId][$goodsId][$skuId]['activityAllowNum'] = bcsub($item['activityNum'],$item['haveBuyNum'],0);//活动剩余数量
                }
            }
        }
        return ResultWrapper::success($returnData);
    }

    /**
     * Doc: (des="获取活动的详情")
     * User: XMing
     * Date: 2020/8/5
     * Time: 9:35 上午
     * @param int $activityId
     * @param int $skuId
     * @return ResultWrapper
     *
     */
    public function getActivityDetails(int $activityId,int $skuId)
    {
        $fields = 'a.id,a.deleteStatus,a.auditStatus,a.startTime,a.endTime,goodsId,g.skuId,g.limitNum,g.activityNum,g.haveBuyNum';
        $sql = 'SELECT '.$fields.' FROM qianniao_activity_'.$this->onlineEnterpriseId.' as a 
                LEFT JOIN qianniao_activity_goods_'.$this->onlineEnterpriseId.' as g 
                ON g.activityId = a.id WHERE 
                a.id = '.$activityId;
        if (!empty($skuId)){
            $sql .= ' AND g.skuId = '.$skuId;
        }
        $activityDetails = $this->objDActivity->query($sql);
        if ($activityDetails === false){
            return ResultWrapper::fail($this->objDActivity->error(),ErrorCode::$dberror);
        }
        $activityDetails = empty($activityDetails) ? [] : array_shift($activityDetails);
        return ResultWrapper::success($activityDetails);
    }
}
