<?php

namespace Business\User;

use Our\ApiConst;
class SalespersonServiceModel extends \Business\AbstractModel
{


    public function init() {

    }

    /**
     * 销售列表
     * @param $param
     * @param $memberId
     * @return array
     * @throws \Exception
     * @throws \Our\Exception
     */
    public function getSalespersonInfo($param,$memberId){
        $this->validateCache($memberId);
        $limit = array($param['pageIndex']*$param['pageSize'],$param['pageSize']);
        $saleDAO = \DAO\SaleModel::getInstance();
        $acts = $saleDAO->getListByMidCache($memberId,'sale_act_id,qrcode_path',$param['pageIndex'],$param['pageSize']);
        if($acts['totalCount'] == 0){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }
        $_acts = $this->getActList($acts,$memberId);
        $_acts = array_values($_acts);
        return array('acts'=>$_acts,'totalCount'=>$acts['totalCount']);
    }
    public function getActList($acts,$memberId){
        $saleActArr = array_column($acts['list'],'sale_act_id');
        $saleGoodsDAO = \DAO\SaleGoodsModel::getInstance();
        $saleGoods = $saleGoodsDAO->getListByActArr($saleActArr);
        $saleGoods = array_column($saleGoods,'sale_act_id','goods_id');
        $acts = $this->getOrderGoods($acts,$saleGoods,$memberId);
        return $acts;
    }

    /**
     * @param $acts
     * @param $saleGoods   goods_id 或 array('goods_id'=>'sale_act_id')
     * @param $memberId
     * @return array
     * @throws \Exception
     * @throws \Our\Exception
     */
    protected function getOrderGoods($acts,$saleGoods,$memberId){
        if(is_array($acts)) {
            //多个活动
            $tempActs = array_column($acts['list'],'qrcode_path','sale_act_id');
        }else{
            //单个活动
            $saleActArr  = array($acts);
            $sale = \DAO\SaleModel::getInstance()->getOne(array('sale_act_id'=>$acts,'member_id'=>$memberId,'is_closing'=>0),'qrcode_path');
            if(!$sale) {
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::saleNotJoin);
            }
            $tempActs[$acts] = $sale['qrcode_path'];
            $saleGoods = array($saleGoods=>$acts);
        }


        $saleActArr  = array_keys($tempActs);

        $saleOrderDAO = \DAO\SaleOrderModel::getInstance();
        //取得goodsid 防止活动商品表的商品被删除 显示的商品不准确
        $saleGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db1\SaleOrderRedisModel::getInstance(),array(&$saleOrderDAO, 'getOrderGoodsList'),array("sale_act_id in(".implode(',',$saleActArr).") AND sale_id = {$memberId}",'DISTINCT goods_id,sale_act_id'),\Our\ApiConst::halfDaySecond,array($memberId));

        $saleGoodsList = $saleGoodsList ? array_column($saleGoodsList,'sale_act_id','goods_id') : [];
        $saleGoods = $saleGoods +$saleGoodsList;
        $goodsIds = $saleGoods ? array_keys($saleGoods) :[];
        if($goodsIds) {
            $goodsDAO = \DAO\GoodsModel::getInstance();
            $tempGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsCommonRedisModel::getInstance(),array(&$goodsDAO, 'getList'),array('goods_id in('.implode(',',$goodsIds).')','goods_id,goods_commonid,goods_name,goods_image'),\Our\ApiConst::oneMinute);
        }

        $goodsList = [];$acts = [];$hashData = [];

        if($tempGoodsList) {
            foreach ($tempGoodsList as $v) {
                $goodsList[$v['goods_id']] = $v;
            }
        }

        $saleActDAO = \DAO\SaleActivityModel::getInstance();
        $actList = $saleActDAO->getActByArr($saleActArr);

        $member = $this->getNameAndAvatar($memberId);
        $memberName = $member['memberName'];
        $memberAvatarUrl = $member['memberAvatarUrl'];

        $orderGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db1\SaleOrderRedisModel::getInstance(),array(&$saleOrderDAO, 'getOrderGoodsList'),array("sale_act_id in(".implode(',',$saleActArr).") AND sale_id = {$memberId} AND goods_id in(".implode(',',$goodsIds).")",'sum(goods_num) AS goodsCount,goods_name AS goodsName,goods_image AS goodsImage,goods_id AS goodsId,sale_act_id','goods_id',[],'sale_act_id'),\Our\ApiConst::halfDaySecond,array($memberId));
        $existIds = [];
        $storeModelDAO = \DAO\StoreModel::getInstance();
        //数据处理
        if($orderGoodsList && is_array($orderGoodsList)) {
            foreach ($orderGoodsList as $v){
                $existIds[] = $v['goodsId'];
                if($goodsList[$v['goodsId']]) {
                    $goods['goodsId'] = $v['goodsId'];
                    $goods['goodsCommonId'] = $goodsList[$v['goodsId']]['goods_commonid'];
                    $goods['goodsImage'] = \Our\ImageUtil::getGoodsImgUrl($goodsList[$v['goodsId']]['goods_image'],\Our\ImageConst::SaleGoodsImgSize);
                    $goods['goodsName'] = $goodsList[$v['goodsId']]['goods_name'];
                    $goods['goodsCount'] = (int)$v['goodsCount'];
                    $hashData[$v['sale_act_id']][$v['sale_act_id'].'_'.$memberId.'_'.$v['goodsId']] = serialize($goods);
                }else{
                    $goods = [];
                }
                if(key_exists($v['sale_act_id'],$acts)){
                    array_push($acts[$v['sale_act_id']]['goods'],$goods);
                }else{
                    $storeInfo = $storeModelDAO->getStoreInfoCache($actList[$v['sale_act_id']]['store_id']);
                    $storeLabel = $storeModelDAO->getStoreLabelSrc($storeInfo['store_label'],\Our\ImageConst::salestoreImg);
                    $qrCode = \Our\Common::getStaticFile($tempActs[$v['sale_act_id']],\Our\ImageConst::salesmanQr);
                    $hashData[$v['sale_act_id']][$v['sale_act_id'].'_'.$memberId] = $qrCode;
                    $acts[$v['sale_act_id']] = [
                        'storeId'=>$actList[$v['sale_act_id']]['store_id'],
                        'storeName'=>$storeInfo['store_name'],
                        'actId'=>$v['sale_act_id'],
                        'actName'=>$actList[$v['sale_act_id']]['sale_title'],
                        'qrCode'=>$qrCode,
                        'memberName'=>$storeInfo['store_name'],
                        'memberAvatarUrl'=>$storeLabel,
                        'memberAvatarUrlR20'=>$storeModelDAO->getStoreLabelSrc($storeInfo['store_label'],'','',true).'?x-oss-process=image/rounded-corners,r_20',
                        'goods'=>$goods ? array($goods) : $goods
                    ];
                }
            }
        }
        if(is_array($goodsIds) && $goodsIds) {
            foreach ($goodsIds as $id){
                //没有销售量的商品，即在sale_order表中不存在数据的商品
                if(!in_array($id,$existIds)){
                    if($goodsList[$id]) {
                        $data = [
                            'goodsImage'=>\Our\ImageUtil::getGoodsImgUrl($goodsList[$id]['goods_image'],\Our\ImageConst::SaleGoodsImgSize),
                            'goodsName'=>$goodsList[$id]['goods_name'],
                            'goodsCount'=>0,
                            'goodsId'=>$id,
                            'goodsCommonId'=>$goodsList[$id]['goods_commonid']
                        ];
                        $hashData[$saleGoods[$id]][$saleGoods[$id].'_'.$memberId.'_'.$id] = serialize($data);
                    }else{
                        $data = [];
                    }
                    if(key_exists($saleGoods[$id],$acts)){
                        array_push($acts[$saleGoods[$id]]['goods'],$data);
                    }else{
                        $storeInfo = $storeModelDAO->getStoreInfoCache($actList[$saleGoods[$id]]['store_id']);
                        $storeLabel = $storeModelDAO->getStoreLabelSrc($storeInfo['store_label'],\Our\ImageConst::salestoreImg);
                        $qrCode = \Our\Common::getStaticFile($tempActs[$saleGoods[$id]],\Our\ImageConst::salesmanQr);
                        $acts[$saleGoods[$id]] = [
                            'storeId'=>$actList[$saleGoods[$id]]['store_id'],
                            'storeName'=>$storeInfo['store_name'],
                            'actId'=>$saleGoods[$id],
                            'actName'=>$actList[$saleGoods[$id]]['sale_title'],
                            'qrCode'=>$qrCode,
                            'memberName'=>$storeInfo['store_name'],
                            'memberAvatarUrl'=>$storeLabel,
                            'memberAvatarUrlR20'=>$storeModelDAO->getStoreLabelSrc($storeInfo['store_label'],'','',true).'?x-oss-process=image/rounded-corners,r_20',
                            'goods'=>$data ? array($data) : $data
                        ];
                        $hashData[$saleGoods[$id]][$saleGoods[$id].'_'.$memberId] = $qrCode;
                    }
                }
            }
        }
        if($hashData) {
            foreach ($hashData as $k=>$v) {
                \Redis\Db1\SaleOrderRedisModel::getInstance()->tableHMSet('orderGoods_'.$k,$v,\Our\ApiConst::oneDaySecond);
            }
        }
        return $acts;
    }
    public function getNameAndAvatar($memberId) {
        $member = \DAO\MemberModel::getInstance()->getInfo($memberId);
        $memberName = $member['memberName'];
        $memberAvatarUrl = $member['memberAvatarUrl'].'?x-oss-process=image/resize,m_fill,h_192,w_192';
        return array('memberName'=>$memberName,'memberAvatarUrl'=>$memberAvatarUrl);
    }

    /**
     * 销售详情
     * @param $param
     * @param $memberId
     * @return array
     * @throws \Exception
     */
    public function getSaleInfo($param,$memberId){
        $limit = array($param['pageIndex']*$param['pageSize'],$param['pageSize']);

        $type = (int)$param['type'];
        $goodsId = (int)$param['goodsId'];
        $actId = (int)$param['actId'];
        if($goodsId === 0) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptySaleGoodsId);
        }
        $this->getSaleInfoHead($param,$memberId);

        $saleOrderDAO = \DAO\SaleOrderModel::getInstance();
        $where = "sale_act_id = {$actId} AND sale_id = {$memberId} AND goods_id = {$goodsId}";
        if($type === 0) {
//            $where .= " AND (order_state=%s AND (refund_id = %s OR (refund_id > %s AND ((seller_state = %s AND is_platform_in = %s) OR (is_platform_in = %s AND platform_state = %s)))))";
            $where .= " AND order_state=40 AND is_refund=0";
//            $where = sprintf($where,ApiConst::orderStateComplete,ApiConst::zero,ApiConst::zero,ApiConst::refundSellerRefuse,ApiConst::platNotIn,ApiConst::platIn,ApiConst::refundPlatformRefuse);
        }else{
//            $where .=" AND (order_state < %s  OR (order_state = %s AND refund_id > %s AND (seller_state != %s OR (is_platform_in = %s AND platform_state != %s ))))";
            $where .= " AND order_state < 40 OR (order_state = 40 AND is_refund = 1)";
//            $where = sprintf($where,ApiConst::orderStateComplete,ApiConst::orderStateComplete,ApiConst::zero,ApiConst::refundSellerRefuse,ApiConst::platIn,ApiConst::refundPlatformRefuse);
        }
        $goodsList = $saleOrderDAO->getOrderGoodsList($where,'member_id,member_name AS memberName,member_avatar AS memberAvatar,sum(goods_num) AS goodsNum','member_id',$limit);
        $orders = [];
        $totalCount = 0;
        if($goodsList && is_array($goodsList)){
            foreach ($goodsList as $v){
//                if(!empty($v['refund_state_name'])){
//                    $orderState = $v['refund_state_name'];
//                }else{
//                    $orderState = \DAO\Order\OrderModel::getInstance()->getStatusSaleText($v['order_state']);
//                }
                $orders[] = [
                    'memberName'=>$v['memberName'],
                    'memberAvatar'=>$v['memberAvatar'],
                    'goodsNum'=>$v['goodsNum']
                ];
            }
            $totalCount = $saleOrderDAO->getCountGroup($where,'member_id');
        }
        return array('totalCount'=>$totalCount,'orders'=>$orders);
    }
    public function getSaleInfoHead($param,$memberId) {
        $this->validateCache($memberId);
        $type = (int)$param['type'];
        $goodsId = (int)$param['goodsId'];
        $actId = (int)$param['actId'];
        if($goodsId === 0) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptySaleGoodsId);
        }

        $member = $this->getNameAndAvatar($memberId);
        $memberName = $member['memberName'];
        $memberAvatarUrl = $member['memberAvatarUrl'];

        $saleOrderRedis = \Redis\Db1\SaleOrderRedisModel::getInstance();
        $act = $saleOrderRedis->tableHGet('orderGoods_'.$actId,$actId);
        $qrcode = $saleOrderRedis->tableHGet('orderGoods_'.$actId,$actId.'_'.$memberId);
        $goods = $saleOrderRedis->tableHGet('orderGoods_'.$actId,$actId.'_'.$memberId.'_'.$goodsId);
        if(!($act && $qrcode && $goods)) {
            $this->getOrderGoods($actId, $goodsId, $memberId);
            $act = \Redis\Db1\SaleOrderRedisModel::getInstance()->tableHGet('orderGoods_'.$actId,$actId);
            $qrcode = \Redis\Db1\SaleOrderRedisModel::getInstance()->tableHGet('orderGoods_'.$actId,$actId.'_'.$memberId);
            $goods = \Redis\Db1\SaleOrderRedisModel::getInstance()->tableHGet('orderGoods_'.$actId,$actId.'_'.$memberId.'_'.$goodsId);
        }
        $storeModelDAO = \DAO\StoreModel::getInstance();
        if($act && $qrcode && $goods) {
            $act = unserialize($act);
            $goods = unserialize($goods);
            $storeInfo = $storeModelDAO->getStoreInfoCache($act['store_id']);
            $storeLabel = $storeModelDAO->getStoreLabelSrc($storeInfo['store_label'],\Our\ImageConst::salestoreImg);
            $info['storeId'] = $act['store_id'];
            $info['storeName'] = $storeInfo['store_name'];
            $info['actName'] = $act['sale_title'];
            $info['qrCode'] = $qrcode;
            $info['memberName'] = $storeInfo['store_name'];
            $info['memberAvatarUrl'] = $storeLabel;
            $info['memberAvatarUrlR20'] = $storeModelDAO->getStoreLabelSrc($storeInfo['store_label'],'','',true).'?x-oss-process=image/rounded-corners,r_20';
            $info = array_merge($info,$goods);
        }else{
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::saleActOrGoodsNotExist);
        }
        return array('info'=>$info);
    }


    public function validate($where,$memberId){
        $saleInstance = \DAO\SaleModel::getInstance();
        $sale_act = $saleInstance->getOneByMIdCache($memberId);
        if(!$sale_act){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::saleNotExist);
        }
        $where['mobile']  = \DAO\MemberModel::getInstance()->getInfo($memberId,'member_mobile');
        $this->validSaleSmsCode($where);

        $shortMessageDao = \DAO\ShortMessageModel::getInstance();
        $shortMessageDao->delCodeRedis($where['key'],$where['mobile'],\Our\ApiConst::messageTypeRegister);

        \Redis\Db1\SaleOrderRedisModel::getInstance()->tableCacheSet('saleValidate:'.$memberId,1,\Our\ApiConst::EightHoursSecond);
    }
    private function validSaleSmsCode($where){
        //验证手机号码
        if($where['code']=='666666'&&(APP_ENV=='test'||APP_ENV=='develop')){
            return true;
        }
        $validData['key'] = $where['key'];
        $validData['messageType'] = ApiConst::messageTypeSeller;
        $validData['mobile'] = $where['mobile'];
        $validData['code'] = $where['code'];
        $shortMessageDao  = \DAO\ShortMessageModel::getInstance();
        if(!$shortMessageDao->validCode($validData)){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::wrongSmsCode);
        }
        return true;
    }
    public function getMobile($where,$memberId) {
        $mobile = \DAO\MemberModel::getInstance()->getInfo($memberId,'member_mobile');
        $mobile || $mobile = '';
        return array('mobile'=>$mobile);
    }
    public function validateCache($memberId) {
        $res = \Redis\Db1\SaleOrderRedisModel::getInstance()->tableCacheGet('saleValidate:'.$memberId);
        if($res === false) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::saleValidate);
        }
        \Redis\Db1\SaleOrderRedisModel::getInstance()->tableCacheSet('saleValidate:'.$memberId,1,\Our\ApiConst::EightHoursSecond);
    }
    private static $_instance = null;

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

        return self::$_instance;
    }

}
