<?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;
    }
    protected function getOrderGoods($acts,$saleGoods,$memberId){
        if(is_array($acts)) {
            $tempActs = array_column($acts['list'],'qrcode_path','sale_act_id');
            if($saleGoods) {
                $goodsIds = array_keys($saleGoods);
            }else{
                $goodsIds = [];
            }
        }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'];
            $goodsIds = array($saleGoods);
            $saleGoods = array($saleGoods=>$acts);
        }
        $saleActArr  = array_keys($tempActs);
        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;
            }
        }
        $saleOrderDAO = \DAO\SaleOrderModel::getInstance();
        $saleActDAO = \DAO\SaleActivityModel::getInstance();
        $actList = $saleActDAO->getActByArr($saleActArr);

        $member = \DAO\MemberModel::getInstance()->getInfo($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::tenMinSecond,array($memberId));
        $existIds = [];
        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']);
                    $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{
                    $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'=>$actList[$v['sale_act_id']]['store_name'],
                        'actId'=>$v['sale_act_id'],
                        'actName'=>$actList[$v['sale_act_id']]['sale_title'],
                        'qrCode'=>$qrCode,
                        'memberName'=>$memberName,
                        'memberAvatarUrl'=>$memberAvatarUrl,
                        'goods'=>$goods ? array($goods) : $goods
                    ];
                }
            }
        }
        if(is_array($goodsIds) && $goodsIds) {
            foreach ($goodsIds as $id){
                if(!in_array($id,$existIds)){
                    if($goodsList[$id]) {
                        $data = [
                            'goodsImage'=>\Our\ImageUtil::getGoodsImgUrl($goodsList[$id]['goods_image']),
                            '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{
                        $qrCode = \Our\Common::getStaticFile($tempActs[$saleGoods[$id]],\Our\ImageConst::salesmanQr);
                        $acts[$saleGoods[$id]] = [
                            'storeId'=>$actList[$saleGoods[$id]]['store_id'],
                            'storeName'=>$actList[$saleGoods[$id]]['store_name'],
                            'actId'=>$saleGoods[$id],
                            'actName'=>$actList[$saleGoods[$id]]['sale_title'],
                            'qrCode'=>$qrCode,
                            'memberName'=>$memberName,
                            'memberAvatarUrl'=>$memberAvatarUrl,
                            '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'];
        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 = 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 = 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'=>\DAO\MemberModel::getInstance()->getMemberAvatarUrl($v['member_id'],$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 = \DAO\MemberModel::getInstance()->getInfo($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);
        }
        if($act && $qrcode && $goods) {
            $act = unserialize($act);
            $goods = unserialize($goods);
            $info['storeId'] = $act['store_id'];
            $info['storeName'] = $act['store_name'];
            $info['actName'] = $act['sale_title'];
            $info['qrCode'] = $qrcode;
            $info['memberName'] = $memberName;
            $info['memberAvatarUrl'] = $memberAvatarUrl;
            $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;
    }

}
