<?php

namespace Business\User;


class FootprintServiceModel extends \Business\AbstractModel
{


    public function init() {

    }

    /**
     * 获取指定年月份有足迹的日期
     * @param $param
     * @param $memberId
     */
    public function getDate($param,$memberId){
        $month = isset($param['month']) ? (int)$param['month'] : date('m');
        $year = isset($param['year']) ? (int)$param['year'] : date('Y');
        $sort = isset($param['sort']) ? (int)$param['sort'] : 1;
        $sort == 1 ? $order = ['browsedate','ASC'] : $order = ['browsedate','DESC'];
        $startTime = mktime(0,0,0,$month,1,$year);
        $endTime = mktime(0,0,-1,$month+1,1,$year);
        $browseDAO = \DAO\GoodsBrowseModel::getInstance();
        $list = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getDistinctDate'),array($memberId,$startTime,$endTime,$order),\Our\ApiConst::tenMinSecond,array($memberId));
        $date = [];
        if($list){
            $date = array_column($list,'browsedate');
        }
        return array('date'=>$date);
    }

    /**
     * 获取足迹列表
     * @param $param
     * @param $memberId
     * @return array
     * @throws \Exception
     */
    public function getFootprints($param,$memberId){
//        $pageSize = (int)($param['pageSize']);
//        $pageIndex = (int)($param['pageIndex']);
        $viewTime = (int)($param['viewTime']);
        if($viewTime === 0){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::ViewTimeNotExist);
        }
        $viewTime += \Our\ApiConst::oneDaySecond;
//        if($pageSize === 0){
//            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
//        }
        $acts = \DAO\SaleMemberModel::getInstance()->isJoinPlatform($memberId);
        $browseDAO = \DAO\GoodsBrowseModel::getInstance();
        $commonDAO = \DAO\GoodsCommonModel::getInstance();
        $where1 = "member_id = {$memberId} AND browsetime <".$viewTime;

        $field = 'goods_commonid,browsedate,group_id';
        //$limit = array($pageIndex*$pageSize,$pageSize);
        $order = array('browsetime','DESC');

        $browseList = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getList'),array($where1,$field,$order),\Our\ApiConst::oneMinute);
        $footPrints = [];
        if($browseList && is_array($browseList)){
            $goodsCommonIds = array_column($browseList,'goods_commonid');
            $goodsCommonIds = array_unique($goodsCommonIds);
            $goodsCommonIds = array_filter ($goodsCommonIds, function ($v){return $v;});
            $groupIds = array_column($browseList,'group_id');
            $groupIds = array_unique($groupIds);
            $groupIds = array_filter ($groupIds, function ($v){return $v;});
            if($goodsCommonIds) {
                $where = array("han_goods_common.goods_commonid in(".implode(',',$goodsCommonIds).")");
                $dates = array_column($browseList,'browsedate','goods_commonid');
                if(!$acts){
                    foreach ($goodsCommonIds as $v) {
                        if($goodsCommon = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsCommonRedisModel::getInstance(),array(&$commonDAO, 'getOneById'),array($v),0,array($v))){
                            $temp = [
                                'goodsCommonId'=>$goodsCommon['goods_commonid'],
                                'groupId'=>0,
                                'goodsName'=>$goodsCommon['goods_name'],
                                'goodsImage'=>\DAO\GoodsCommonModel::getInstance()->getGoodsImgSrc($goodsCommon['goods_image'],360),
                                'goodsPrice'=>$goodsCommon['goods_price'],
                                'viewDate'=>$dates[$v]
                            ];
                            $footPrints[] = $temp;
                        }
                    }
                }else{
                    $acts = array_keys($acts);
                    $field = 'han_goods_common.goods_commonid AS goodsCommonId,goods_name AS goodsName,goods_image AS goodsImage,goods_price AS goodsPrice';
                    $list = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsCommonRedisModel::getInstance(),array(&$commonDAO, 'getListWithSale'),array($where,$field,$acts,[],[],'',false),\Our\ApiConst::oneMinute);
                    if($list){
                        foreach ($list as $goodsCommon) {
                            $goodsCommon['goodsImage'] = \DAO\GoodsCommonModel::getInstance()->getGoodsImgSrc($goodsCommon['goodsImage'],360);
                            $goodsCommon['viewDate'] = $dates[$goodsCommon['goodsCommonId']];
                            $goodsCommon['groupId'] = 0;
                            $footPrints[] = $goodsCommon;
                        }
                    }
                }
            }
            if($groupIds) {
                $field = 'bl_id AS blId,bl_name AS name,bl_title,store_id,store_name,bl_state,bl_quota_starttime,bl_image,bl_storage,bl_discount_price AS discountPrice,bl_sum_price AS sumPrice,bl_quota_endtime AS endTime,image,is_transport,transport_id';
                $pbundlingInstance = \DAO\PBundlingModel::getInstance();
                $where2 = ' bl_id in ('.implode(',',$groupIds).')';
                $groupList = \Our\RedisHelper::cachedFunction(\Redis\Db4\PBundlingRedisModel::getInstance(), array(&$pbundlingInstance, 'getList'), array($field,$where2), \Our\ApiConst::oneDaySecond);
                if($groupList) {
                    $dates = array_column($browseList,'browsedate','group_id');
                    foreach ($groupList as $group) {
                        $temp = [
                            'goodsCommonId'=>0,
                            'groupId'=>$group['blId'],
                            'goodsName'=>$group['name'],
                            'goodsImage'=>\DAO\GoodsCommonModel::getInstance()->getGoodsImgSrc($group['image'],360),
                            'goodsPrice'=>$group['discountPrice'],
                            'viewDate'=>$dates[$group['blId']]
                        ];
                        $footPrints[] = $temp;
                    }
                }
            }
        }
        return array('footprints'=>$footPrints);
    }


    /**
     * 删除足迹
     * @param $param
     * @param $memberId
     * @return bool
     * @throws \Our\Exception
     */
    public function delFootPrint($param,$memberId){
        $ids = $param['ids'];
        if(!$ids){
            return false;
        }
        $browseDAO = \DAO\GoodsBrowseModel::getInstance();
        if(is_array($ids)){
            $ids = array_map(function($v){
                return intval($v);
            },$ids);
            $return = $browseDAO->delete("goods_commonid in (".implode(',',$ids).") AND member_id={$memberId}");
        }else{
            if(strpos($ids,']') !== false ) {
                $ids = json_decode($ids, true);
                $return = $browseDAO->delete("goods_commonid in (".implode(',',$ids).") AND member_id={$memberId}");
            }else{
                $ids = intval($ids);
                $return = $browseDAO->delete(array('goods_commonid'=>$ids,'member_id'=>$memberId));
            }
        }

        if($return === false) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }

        if(($return = (int)$return) > 0){
            //删除缓存
            \Our\RedisHelper::delCachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getDistinctDate'),array(),array($memberId));
            \Our\RedisHelper::delCachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getGoodsListWithSale'),array(),array($memberId));
            \Our\RedisHelper::delCachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getGoodsList'),array(),array($memberId));
            \Our\RedisHelper::delCachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getCount'),array(),array($memberId));
            return true;
        }
    }
    private static $_instance = null;

    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

}
