<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2016/12/13
 * Time: 下午8:31
 */

require_once(BASE_ROOT_PATH . '/helper/FileUploader.php');
require_once(BASE_ROOT_PATH . '/helper/order_helper.php');
require_once(BASE_ROOT_PATH . '/helper/account_helper.php');


class member_evaluateControl extends mbMemberControl
{
    const pic_path = '/data/upload/shop/member';

    public function __construct() {
        parent::__construct();
    }
    public function indexOp()
    {

    }

    private function order_id(&$err,&$order_info,&$store_info,&$order_goods)
    {
        $order_id = intval($_GET['order_id']);
        $order_sn = $_GET['order_sn'];

        if ($order_id <= 0 && empty($order_sn)) {
            $err = array('code' => errcode::ErrOrderNotExist,'msg' => "订单信息不存在.");
            return false;
        }
        else
        {
            if($order_id > 0) {
                $cond['order_id'] = $order_id;
            } else {
                $cond['order_sn'] = $order_sn;
            }
        }

        $model_order = Model('order');
        $model_store = Model('store');
        $order_info = $model_order->getOrderInfo($cond);

        if(empty($order_info)) {
            $err = array('code' => errcode::ErrOrder,'msg' => "无此订单.");
            return false;
        }

        $order_id = intval($order_info['order_id']);
        //判断订单身份
        if($order_info['buyer_id'] != $_SESSION['member_id']) {
            $err = array('code' => errcode::ErrOrder,'msg' => "只能评论自己的订单.");
            return false;
        }

        //订单为'已收货'状态，并且未评论
        $order_info['evaluate_able'] = $model_order->getOrderOperateState('evaluation',$order_info);
        if (empty($order_info) || !$order_info['evaluate_able']) {
            $err = array('code' => errcode::ErrOrder,'msg' => "该订单目前不能评论.");
            return false;
        }

        //查询店铺信息
        $store_info = $model_store->getStoreInfoByID($order_info['store_id']);
        if(empty($store_info)) {
            $err = array('code' => errcode::ErrOrder,'msg' => "店铺不存在.");
            return false;
        }

        //获取订单商品
        $order_goods = $model_order->getOrderGoodsList(array('order_id'=>$order_id));
        if(empty($order_goods)) {
            $err = array('code' => errcode::ErrOrder,'msg' => "找不到该订单商品.");
            return false;
        }
        return $order_id;
    }

    public function infoOp()
    {
        $order_id = $this->order_id($err,$order_info,$store_info,$order_goods);
        if($order_id == false) {
            return self::outerr($err['code'],$err['msg']);
        }

        for ($i = 0, $j = count($order_goods); $i < $j; $i++) {
            $order_goods[$i]['goods_image_url'] = cthumb($order_goods[$i]['goods_image'], 240, $store_info['store_id']);
        }

        $result = [];
        foreach ($order_goods as $key => $val) {
            $item['goods_id'] = intval($val['goods_id']);
            $item['goods_image'] = $val['goods_image_url'];
            $item['store_id'] = intval($val['store_id']);
            $item['goods_spec'] = $val['goods_spec'];
            $item['goods_name'] = $val['goods_name'];
            $result[] = $item;
        }

        return self::outsuccess(array('order_goods' => $result,'order_id' => $order_id));
    }

    private function destpath()
    {
        $path = BASE_ROOT_PATH . self::pic_path . '/' . $_SESSION['member_id'];
        if(is_dir($path)) {
            return $path;
        }
        else
        {
            if(mkdir($path)) {
                return $path;
            } else {
                return false;
            }
        }
    }

    private function upfile($img,&$err)
    {
        $member_id = $_SESSION['member_id'];

        $upload = new FileUploader();
        if($upload->init_files($img,$member_id,$err) == false) {
            return false;
        }

        $upload_dir = ATTACH_MALBUM.DS.$member_id.DS;
        $upload->set('default_dir',$upload_dir.$upload->getSysSetPath());
        $thumb_width	= '240,1024';
        $thumb_height	= '2048,1024';

        $upload->set('max_size',C('image_max_filesize'));
        $upload->set('thumb_width', $thumb_width);
        $upload->set('thumb_height',$thumb_height);
        $upload->set('fprefix',$member_id);
        $upload->set('thumb_ext', '_240,_1024');
        $result = $upload->upfile('file');
        if($result == true) {
            return $upload->file_name;
        } else {
            $err = array('code' => errcode::ErrUpfile, 'msg' => $upload->error);
            return false;
        }
    }

    private function comment(&$err)
    {
        $input_goods = trim($_POST['evaluation']);
        if(empty($input_goods)) {
            $err = array('code' => errcode::ErrParamter,'msg' => "请填写评论信息.");
            return false;
        }

        $input_goods = base64_decode($input_goods);
        $input_goods = json_decode($input_goods,true);
        if(empty($input_goods)) {
            $err = array('code' => errcode::ErrParamter,'msg' => "请填写评论信息.");
            return false;
        }

        $save_path = $this->destpath();
        if($save_path == false) {
            $err = array('code' => errcode::ErrParamter,'msg' => "请填写评论信息.");
            return false;
        }

        $result = [];
        foreach ($input_goods as $val)
        {
            $goods_id = intval($val['goods_id']);
            $score = intval($val['score']);

            $imges = [];
            foreach ($val['images'] as $img)
            {
                $file_name = $this->upfile($img);
                if($file_name != false) {
                    $imges[] = $file_name;
                }
            }

            $item['goods_id'] = $goods_id;
            $item['score'] = $score;
            $item['comment'] = $val['comment'];
            $item['images'] = implode(',',$imges);

            $result[$goods_id] = $item;
        }

        return $result;
    }

    public function addOp()
    {
        $order_id = $this->order_id($err,$order_info,$store_info,$order_goods);
        if($order_id == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        $comments = $this->comment($err);
        if($comments == false) {
            return self::outerr($err['code'],$err['msg']);
        }

        $anony = $_POST['anony'] ? 1 : 0;
        $model_order = Model('order');
        $model_evaluate_goods = Model('evaluate_goods');

        $evaluate_goods_array = array();
        $goodsid_array = array();

        $mod_goods = Model('goods');
        foreach ($order_goods as $value)
        {
            $goods_id = intval($value['goods_id']);
            $goods_commonid = commonid_helper::instance()->common_id($goods_id);
            //如果未评分，默认为5分
            $evaluate_score = $comments[$goods_id]['score'];
            if($evaluate_score <= 0 || $evaluate_score > 5) {
                $evaluate_score = 5;
            }
            //默认评语
            $evaluate_comment = $comments[$goods_id]['comment'];
            if(empty($evaluate_comment)) {
                $evaluate_comment = '不错哦';
            }
            $geval_image = $comments[$value['goods_id']]['images'];

            $evaluate_goods_info = array();
            $evaluate_goods_info['geval_orderid'] = $order_id;
            $evaluate_goods_info['geval_orderno'] = $order_info['order_sn'];
            $evaluate_goods_info['geval_ordergoodsid'] = $value['rec_id'];
            $evaluate_goods_info['geval_commonid'] = $goods_commonid;
            $evaluate_goods_info['geval_goodsid'] = $value['goods_id'];
            $evaluate_goods_info['geval_goodsname'] = $value['goods_name'];
            $evaluate_goods_info['geval_goodsprice'] = $value['goods_price'];
            $evaluate_goods_info['geval_goodsimage'] = $value['goods_image'];
            $evaluate_goods_info['geval_scores'] = $evaluate_score;
            $evaluate_goods_info['geval_content'] = $evaluate_comment;
            $evaluate_goods_info['geval_isanonymous'] = $anony;
            $evaluate_goods_info['geval_addtime'] = time();
            $evaluate_goods_info['geval_storeid'] = $store_info['store_id'];
            $evaluate_goods_info['geval_storename'] = $store_info['store_name'];
            $evaluate_goods_info['geval_frommemberid'] = $_SESSION['member_id'];
            $evaluate_goods_info['geval_frommembername'] = $_SESSION['member_name'];

            if(!empty($geval_image)) {
                $evaluate_goods_info['geval_image'] = $geval_image;
            } else {
                $evaluate_goods_info['geval_image'] = '';
            }

            $evaluate_goods_array[] = $evaluate_goods_info;
            $goodsid_array[] = $value['goods_id'];

            $mod_goods->editGoodsCommon(['comments' => array('exp', "comments+1")],['goods_commonid' => $goods_commonid]);
        }

        $model_evaluate_goods->addEvaluateGoodsArray($evaluate_goods_array, $goodsid_array);

        //更新订单信息并记录订单日志
        $state = $model_order->editOrder(array('evaluation_state'=>1), array('order_id' => $order_id));
        $model_order->editOrderCommon(array('evaluation_time'=>TIMESTAMP), array('order_id' => $order_id));
        if ($state) {
            $data = array();
            $data['order_id'] = $order_id;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = L('order_log_eval');
            $model_order->addOrderLog($data);
            QueueClient::push('onAsyncOrderEvaluate',['pay_sn' => $order_info['pay_sn']]);
        }

        //添加会员积分
        if (C('points_isuse') == 1){
            $points_model = Model('points');
            $points_model->savePointsLog('comments',array('pl_memberid'=>$_SESSION['member_id'],'pl_membername'=>$_SESSION['member_name']));
        }
        //添加会员经验值
        Model('exppoints')->saveExppointsLog('comments',array('exp_memberid'=>$_SESSION['member_id'],'exp_membername'=>$_SESSION['member_name']));

        $order = $this->get_order(array("buyer_id" => $_SESSION['member_id'],'order_id' => $order_id));
        if($order == false) {
            $order = null;
        }

        return self::outsuccess(array("act_type" => 'if_evaluation',"order_id" => $order_id, "order" => $order));
    }

    private function get_order($condition)
    {
        $model_order = Model('order');
        $order_list = $model_order->getNormalOrderList($condition, $this->page_size, '*', 'order_id desc', '', array('order_common','order_address', 'order_goods'));
        $order_helper = new order_helper($order_list);
        $orders = $order_helper->format();
        $model_order->cls();
        if(!empty($orders)) {
            return $orders[0];
        } else {
            return false;
        }
    }
}
