<?php
namespace Business\Goods;


class EvaluationServiceModel extends \Business\AbstractModel {

    public function init(){
    }

    public function getGoods($param,$memberId){

        $order = $this->_validate(intval($param['orderId']),$memberId);
        //获取订单商品
        $orderGoodsDAO =\DAO\Order\OrderGoodsModel::getInstance();
        $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderGoodsRedisModel::getInstance(),array(&$orderGoodsDAO, 'getOrderGoodsList'),array(array('order_id'=>$order['order_id']),'rec_id,goods_id,goods_commonid,goods_name,goods_image,goods_pay_price,goods_num,goods_spec'),\Our\ApiConst::tenMinSecond,array($order['order_id']));
        if(!$orderGoods){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::orderError);
        }
        $goods = [];
        foreach ($orderGoods as $k=>$v){
            $goods[] = array('goodsId'=>$v['goods_id'],'goodsName'=>$v['goods_name'],'goodsPrice'=>$v['goods_pay_price'],'goodsNum'=>$v['goods_num'],'goodsImage'=>\Our\ImageUtil::getGoodsImgUrl($v['goods_image']));
        }
        $serviceEvaluations = [];
        if($order['diliveryman_id']) {
            //获取配送员评价标签
            $evalLabelDAO = \DAO\DeliveryEvalLabelModel::getInstance();
            $data = \Our\RedisHelper::cachedFunction(\Redis\Db5\DeliveryEvalLabelRedisModel::getInstance(),array(&$evalLabelDAO, 'getLabelList'),array(array('store_id'=>$order['store_id'],'is_show'=>1),'label_id,label_name'),\Our\ApiConst::oneDaySecond,array($order['store_id']));
            if($data && is_array($data)){
                foreach ($data as $k=>$v){
                    $serviceEvaluations[] = array('labelId'=>$v['label_id'],'label'=>$v['label_name']);
                }
            }
        }

        return array('goods'=>$goods,'serviceEvaluations'=>$serviceEvaluations);
    }

    /**
     * 评价提交
     * @param $data
     * @param $memberId
     * @throws \Exception
     * @throws \OSS\Core\OssException
     * @throws \Our\Exception
     */
    public function submit($data,$memberId){
        list($data, $order, $orderGoods) = $this->_submitValite($data,$memberId);
        foreach ($orderGoods as $v){
            $orderGoods[$v['goods_id']] = $v;
        }
        $evaluations = [];
        $member= \DAO\MemberModel::getInstance()->getInfo($memberId);
        $memberName = $member['memberName'];
        $memberAvatar = $member['memberAvatar'];
        foreach ($data['goods'] as $k=>$v){
            if($orderGoods[$v['goodsId']]['goods_commonid'] > 0) {//=0是组合
                $evaluation = array();
                $evaluation['geval_orderid'] = $order['order_id'];
                $evaluation['geval_orderno'] = $order['order_sn'];
                $evaluation['geval_ordergoodsid'] = $orderGoods[$v['goodsId']]['rec_id'];
                $evaluation['geval_goodsid'] = $v['goodsId'];
                $evaluation['geval_goodsname'] = $orderGoods[$v['goodsId']]['goods_name'];
                $evaluation['geval_goodsprice'] = $orderGoods[$v['goodsId']]['goods_pay_price'];
                $evaluation['geval_goodsimage'] = $orderGoods[$v['goodsId']]['goods_image'];
                $evaluation['geval_scores'] = intval($v['scores']);
                $evaluation['geval_content'] = $v['content'] ? trim($v['content']) : \Our\OrderConst::beyondTimeDefaultComment;
                $evaluation['geval_isanonymous'] = intval($data['isanonymous']);
                $evaluation['geval_addtime'] = time();
                $evaluation['geval_storeid'] = $order['store_id'];
                $evaluation['geval_storename'] = $order['store_name'];
                $evaluation['geval_frommemberid'] = $memberId;
                $evaluation['geval_frommembername'] = $memberName;
                $evaluation['memberAvatar'] = $memberAvatar;
                //$images = $this->_upload($v['images']);
                $images = $v['images'];
                //兼容安卓传参
                if(!is_array($images)) $images = json_decode($images, true);
                if(is_array($images) && $images) {
                    foreach ($images as $k=>$v) {
                        if(empty($v)) {
                            unset($images[$k]);
                        }
                    }
                }else{
                    $images = null;
                }
                if(empty($images)) $images = null;
                $images ? $data['goods'][$k]['haveImg'] = 1 : $data['goods'][$k]['haveImg'] = 0;
                if($data['goods'][$k]['haveImg'] == 1) {
                    foreach ($images as &$image) {
                        if($image) {
                            $image = pathinfo($image)['basename'];
                        }
                    }
                }
                $evaluation['geval_image'] = serialize($images);
                $goodsInstance = \DAO\GoodsModel::getInstance();
                $evaluation['geval_goods_commonid'] = $orderGoods[$v['goodsId']]['goods_commonid'];
                $evaluation['goods_spec'] = $orderGoods[$v['goodsId']]['goods_spec'];
                $data['goods'][$k]['goodsCommonId'] = $evaluation['geval_goods_commonid'];
                $evaluations[] = $evaluation;
            }
        }
        $result = \DAO\EvaluateGoodsModel::getInstance()->insertAll($evaluations);
        if(!$result){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::commonError);
        }


        $evaluateInstance = \DAO\EvaluateGoodsModel::getInstance();

        $insert = array();
        foreach ($data['goods'] as $v){
            if($v['goodsCommonId']) {
                //更新商品评分
                $statisticsDb6Redis = \Redis\Db6\StatisticsRedisModel::getInstance();
                //goods_common
                $grade = \DAO\GoodsScoreStatisticsModel::getInstance()->getGrade($v['goodsCommonId']);
                $grade['evaluation_score'] = $grade['evaluation_score']+intval($v['scores']);
                $grade['evaluation_number'] = $grade['evaluation_number'] + 1;
                $v['haveImg'] ?  $grade['evaluation_img_number'] += 1 : $grade['evaluation_img_number'] = $grade['evaluation_img_number'];
                $statisticsDb6Redis->tableHSet('goodsCommon',$v['goodsCommonId'],serialize($grade));
                $grade['goods_commonid'] = $v['goodsCommonId'];
                $insert[] = $grade;
                //删除商品评论列表缓存
                \Our\RedisHelper::delCachedFunction(\Redis\Db4\EvaluateGoodsRedisModel::getInstance(),array(&$evaluateInstance, 'getList'),array(),array($v['goodsCommonId']));
            }
        }
        //批量插入或更新评论总分等
        \DAO\GoodsScoreStatisticsModel::getInstance()->insertAllOrUpdate($insert);
        if($order['diliveryman_id']){
            $delivery['deval_orderid'] = $order['order_id'];//配送评价表的内容
            $delivery['deval_orderno'] = $order['order_sn'];
            $delivery['deval_storeid'] = $order['store_id'];
            $delivery['diliveryman_id'] = $order['diliveryman_id'];
            $delivery['deval_time'] = time();
            $delivery['deval_score'] = intval($data['deliveryCredit']);
            $delivery['deval_content'] = trim($data['content']);
            $devalId = \DAO\EvaluateDeliverymanModel::getInstance()->insert($delivery);
            if($devalId){
                if(is_array($data['labelId'])&&count($data['labelId'])>0){
                    $labels = array();
                    foreach ($data['labelId'] as $key => $v){
                        if($v){
                            $labels[] = array('deval_id'=>$devalId,'label_id'=>$v);
                        }
                    }
                }
                if($labels){
                    \DAO\DeliveryLabelValueModel::getInstance()->insertAll($labels);
                }
            }
        }
        $evaluateStore = array();
        $evaluateStore['seval_orderid'] = $order['order_id'];
        $evaluateStore['seval_orderno'] = $order['order_sn'];
        $evaluateStore['seval_addtime'] = time();
        $evaluateStore['seval_storeid'] = $order['store_id'];
        $evaluateStore['seval_storename'] = $order['store_name'];
        $evaluateStore['seval_memberid'] = $memberId;
        $evaluateStore['seval_membername'] = $memberName;
        $evaluateStore['seval_desccredit'] = intval($data['descCredit']);
        $evaluateStore['seval_servicecredit'] = intval($data['serviceCredit']);
        $evaluateStore['seval_deliverycredit'] = intval($data['deliveryCredit']);
        $resultStore = \DAO\EvaluateStoreModel::getInstance()->insert($evaluateStore);
        if($resultStore){
            //更新店铺评分
            $grade = \DAO\StoreScoreStatisticsModel::getInstance()->getGrade($order['store_id']);
            $grade['evaluation_score'] = $grade['evaluation_score']+intval($data['descCredit'])+intval($data['serviceCredit'])+intval($data['deliveryCredit']);
            $grade['evaluation_number'] = $grade['evaluation_number'] + 1;
            $statisticsDb6Redis = \Redis\Db6\StatisticsRedisModel::getInstance();
            $statisticsDb6Redis->tableHSet('store',$order['store_id'],serialize($grade));
            //更新店铺评论总分
            \DAO\StoreScoreStatisticsModel::getInstance()->insertOrUpdate(array('store_id'=>$order['store_id'],'evaluation_score'=>$grade['evaluation_score'],'evaluation_number'=>$grade['evaluation_number']));
        }
        \DAO\Goods\StoreTopSaleGoodsModel::getInstance()->pushChangeSaleStore($order['store_id']);
        $orderInstance = \DAO\Order\OrderModel::getInstance();
        //修改订单状态
        $orderInstance->update(array('order_id'=>$order['order_id']),array('evaluation_state'=>1));
        //删除缓存
        \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),array(&$orderInstance, 'find'),array(),array($order['order_id']));
        //\DAO\MemberModel::getInstance()->_changeNum(\Our\NameConst::waitEvaluate,$memberId,-1);
        $orderInstance->deleteOrderCache($memberId, $order['order_id'],$order['store_id']);
    }

    /**
     * 图片上传
     * @param $images
     * @return array
     * @throws \Exception
     * @throws \OSS\Core\OssException
     */
    protected function _upload($images){
        $imgArr = [];
        if(is_array($images) && !empty($images)){
            foreach ($images as $v){
                $time = date('YmdHis_');
                $file_name = $time.\Our\Validate::getNumberString();
                $result = \Our\ImageUtil::uploadBase64Image($v,\Our\ImageConst::goodsEvaluation,$file_name);
                if($result){
                    $imgArr[] = $file_name;
                }
            }
        }
        return $imgArr;
    }
    protected function _validate($orderId,$memberId){
        if(!$memberId){
            return false;
        }
        if(!$orderId){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::orderNotExist);
        }
        //验证订单状态 是否待评价
        $orderInstance = \DAO\Order\OrderModel::getInstance();
        $orderInstance->setDb(\Our\DbNameConst::masterDBConnectName);
        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),array(&$orderInstance, 'find'),array(array('order_id'=>$orderId)),\Our\ApiConst::tenMinSecond,array($orderId));
        if($order['evaluation_state'] != 0 || $order['order_state'] != 40 || $order['buyer_id'] != $memberId){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::orderError);
        }

        return $order;
    }
    protected function _submitValite($param,$memberId){
        $order = $this->_validate(intval($param['orderId']),$memberId);
        $param['goods'] || \Error\ErrorModel::throwException(\Error\CodeConfigModel::orderError);
        $param['descCredit'] || \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyDescCredit);
        $param['deliveryCredit'] || \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyDeliveryCredit);
        $param['deliveryCredit'] || \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyServiceCredit);
        if(!is_array($param['goods'])) {
            $param['goods'] = json_decode($param['goods'],true);
        }
        foreach ($param['goods'] as $v){
            $v['goodsId'] || \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyGoodsId);
            $v['scores'] || \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyScores);
            if(!empty($v['content']) && ( mb_strlen($v['content']) < 6 ||  mb_strlen($v['content']) > 500 )) {
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::wrongEvaluation);
            }
        }
        //获取订单商品
        $orderGoodsInstance = \DAO\Order\OrderGoodsModel::getInstance(\Our\DbNameConst::masterDBConnectName);
        $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderGoodsRedisModel::getInstance(),array(&$orderGoodsInstance, 'getOrderGoodsList'),array(array('order_id'=>$order['order_id']),'rec_id,goods_id,goods_commonid,goods_name,goods_image,goods_pay_price,goods_num,goods_spec'),\Our\ApiConst::tenMinSecond,array($order['order_id']));
//        $orderGoods = \DAO\OrderGoodsModel::getInstance()->getOrderGoodsList(array('order_id'=>$order['order_id']),'rec_id,goods_id,goods_name,goods_image,goods_pay_price,goods_num');
        if(!$orderGoods){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::orderError);
        }

        $goodsIds1 = array_column($param['goods'],'goodsId');
        $goodsIds2 = array_column($orderGoods,'goods_id');

        sort($goodsIds1);
        sort($goodsIds2);
        if($goodsIds1 != $goodsIds2){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::orderError);
        }
        return array($param, $order, $orderGoods);
    }
    public function autoEvaluate() {
        $pageBegin = \Our\PageConst::taskPageBegin;
        $orderDao = \DAO\Order\OrderModel::getInstance(\Our\DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance();
        $evaluateInstance = \DAO\EvaluateGoodsModel::getInstance();
        do{
            $list = $orderDao->getList(array('finnshed_time'=>array('elt',time()-(\Our\ApiConst::sevenDaySecond)),'evaluation_state'=>\Our\ApiConst::waitEvaluation,'order_state'=>\Our\ApiConst::orderStateComplete,'delete_state'=>0,'lock_state'=>0),'order_id,buyer_id,buyer_name,store_name,store_id,order_sn,order_id,diliveryman_id',$pageBegin,\Our\PageConst::taskPageSize,'');
            foreach ($list['list'] as $order) {
                $orderGoods = $orderGoodsDao->getOrderGoodsList(array('order_id'=>$order['order_id'],'refund_id'=>0),'rec_id,goods_id,goods_commonid,goods_name,goods_image,goods_pay_price,goods_num,goods_spec');
                $evaluations = array();
                foreach ($orderGoods as $k=>$v){
                    $evaluation = array();
                    if($v['goods_commonid'] > 0) {
                        $evaluation['geval_orderid'] = $order['order_id'];
                        $evaluation['geval_orderno'] = $order['order_sn'];
                        $evaluation['geval_ordergoodsid'] = $v['rec_id'];
                        $evaluation['geval_goodsid'] = $v['goods_id'];
                        $evaluation['geval_goodsname'] = $v['goods_name'];
                        $evaluation['geval_goodsprice'] = $v['goods_pay_price'];
                        $evaluation['geval_goodsimage'] = $v['goods_image'];
                        $evaluation['geval_scores'] = 5;
                        $evaluation['geval_content'] = \Our\OrderConst::beyondTimeDefaultComment;
                        $evaluation['geval_isanonymous'] = 1;
                        $evaluation['geval_addtime'] = time();
                        $evaluation['geval_storeid'] = $order['store_id'];
                        $evaluation['geval_storename'] = $order['store_name'];
                        $evaluation['geval_frommemberid'] = $order['buyer_id'];
                        $evaluation['geval_frommembername'] = $order['buyer_name'];;
                        $images = null;
                        $evaluation['geval_image'] = serialize($images);
                        $evaluation['geval_goods_commonid'] = $v['goods_commonid'];
                        $evaluation['goods_spec'] = $v['goods_spec'];
                        $evaluations[] = $evaluation;
                    }
                }
                if($evaluations) {
                    $result = \DAO\EvaluateGoodsModel::getInstance()->insertAll($evaluations);
                }
                if(!$result){
                    return false;
                }
                $insert = array();
                foreach ($orderGoods as $v) {
                    if($v['goods_commonid'] > 0) {
                        //更新商品评分
                        $statisticsDb6Redis = \Redis\Db6\StatisticsRedisModel::getInstance();
                        //goods_common
                        $grade = \DAO\GoodsScoreStatisticsModel::getInstance()->getGrade($v['goods_commonid']);
                        $grade['evaluation_score'] = $grade['evaluation_score']+5;
                        $grade['evaluation_number'] = $grade['evaluation_number'] + 1;
                        $grade['evaluation_img_number'] = $grade['evaluation_img_number'];
                        $statisticsDb6Redis->tableHSet('goodsCommon',$v['goods_commonid'],serialize($grade));
                        $grade['goods_commonid'] = $v['goods_commonid'];
                        $insert[] = $grade;
                        //删除商品评论列表缓存
                        \Our\RedisHelper::delCachedFunction(\Redis\Db4\EvaluateGoodsRedisModel::getInstance(),array(&$evaluateInstance, 'getList'),array(),array($v['goods_commonid']));
                    }
                }
                //批量插入或更新评论总分等
                if($insert) {
                    \DAO\GoodsScoreStatisticsModel::getInstance()->insertAllOrUpdate($insert);
                }
                if($order['diliveryman_id']){
                    $delivery['deval_orderid'] = $order['order_id'];//配送评价表的内容
                    $delivery['deval_orderno'] = $order['order_sn'];
                    $delivery['deval_storeid'] = $order['store_id'];
                    $delivery['diliveryman_id'] = $order['diliveryman_id'];
                    $delivery['deval_time'] = time();
                    $delivery['deval_score'] = 5;
                    $devalId = \DAO\EvaluateDeliverymanModel::getInstance()->insert($delivery);
                }
                $evaluateStore = array();
                $evaluateStore['seval_orderid'] = $order['order_id'];
                $evaluateStore['seval_orderno'] = $order['order_sn'];
                $evaluateStore['seval_addtime'] = time();
                $evaluateStore['seval_storeid'] = $order['store_id'];
                $evaluateStore['seval_storename'] = $order['store_name'];
                $evaluateStore['seval_memberid'] = $order['buyer_id'];
                $evaluateStore['seval_membername'] = $order['buyer_name'];
                $evaluateStore['seval_desccredit'] = 5;
                $evaluateStore['seval_servicecredit'] = 5;
                $evaluateStore['seval_deliverycredit'] = 5;
                $resultStore = \DAO\EvaluateStoreModel::getInstance()->insert($evaluateStore);
                if($resultStore){
                    //更新店铺评分
                    $grade = \DAO\StoreScoreStatisticsModel::getInstance()->getGrade($order['store_id']);
                    $grade['evaluation_score'] = $grade['evaluation_score']+5+5+5;
                    $grade['evaluation_number'] = $grade['evaluation_number'] + 1;
                    $statisticsDb6Redis = \Redis\Db6\StatisticsRedisModel::getInstance();
                    $statisticsDb6Redis->tableHSet('store',$order['store_id'],serialize($grade));
                    //更新店铺评论总分
                    \DAO\StoreScoreStatisticsModel::getInstance()->insertOrUpdate(array('store_id'=>$order['store_id'],'evaluation_score'=>$grade['evaluation_score'],'evaluation_number'=>$grade['evaluation_number']));
                }
                \DAO\Goods\StoreTopSaleGoodsModel::getInstance()->pushChangeSaleStore($order['store_id']);
                //修改订单状态
                $orderDao->update(array('order_id'=>$order['order_id']),array('evaluation_state'=>2));
                //删除缓存
                \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),array(&$orderDao, 'find'),array(),array($order['order_id']));
                $orderDao->deleteOrderCache($order['buyer_id'], $order['order_id'],$order['store_id']);
            }
        }while(!empty($list['list']));


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

        return self::$_instance;
    }
}