<?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');
        $month = date('m');
        $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-2,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::twoMinSecond,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']);
//        k = (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 browsedate =".$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, array($memberId));
        $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'=>\Our\ImageUtil::getGoodsImgUrl($goodsCommon['goods_image'],\Our\ImageConst::footPrintGoodsImgSize),
                                'goodsPrice'=>$goodsCommon['goods_price'],
                                'viewDate'=>$dates[$v]
                            ];
                            //$footPrints[] = $temp;
                            $goodsCommons[$goodsCommon['goods_commonid']] = $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'] = \Our\ImageUtil::getGoodsImgUrl($goodsCommon['goodsImage'],\Our\ImageConst::footPrintGoodsImgSize);
                            $goodsCommon['viewDate'] = $dates[$goodsCommon['goodsCommonId']];
                            $goodsCommon['groupId'] = 0;
                            //$footPrints[] = $goodsCommon;
                            $goodsCommons[$goodsCommon['goodsCommonId']] = $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::oneMinute);
                if($groupList) {
                    $dates = array_column($browseList,'browsedate','group_id');
                    foreach ($groupList as $group) {
                        $temp = [
                            'goodsCommonId'=>0,
                            'groupId'=>$group['blId'],
                            'goodsName'=>$group['name'],
                            'goodsImage'=>\Our\ImageUtil::getGoodsImgUrl($group['image'],\Our\ImageConst::footPrintGoodsImgSize),
                            'goodsPrice'=>$group['discountPrice'],
                            'viewDate'=>$dates[$group['blId']]
                        ];
                        $groups[$group['blId']] = $temp;
                    }
                }
            }
            foreach ($browseList as $browse) {
                if($browse['goods_commonid'] && $goodsCommons[$browse['goods_commonid']]) {
                    $footPrints[] = $goodsCommons[$browse['goods_commonid']];
                }
                if($browse['group_id'] && $groups[$browse['group_id']]) {
                    $footPrints[] = $groups[$browse['group_id']];
                }
            }
        }
        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));
            \Our\RedisHelper::delCachedFunction(\Redis\Db4\GoodsBrowserRedisModel::getInstance(),array(&$browseDAO, 'getList'),array(),array($memberId));
            \Redis\Db1\MemberCenterRedisModel::getInstance()->tableHDel($memberId,\Our\NameConst::footprint);
            return true;
        }
    }
    private static $_instance = null;

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

        return self::$_instance;
    }

}
