<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/29
 */

namespace app\models\store;


use crmeb\basic\BaseModel;
use crmeb\services\UtilService;
use crmeb\traits\ModelTrait;

/**
 * TODO 商品评价Model
 * Class StoreProductReply
 * @package app\models\store
 */
class StoreProductReply extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'store_product_reply';

    use ModelTrait;

    protected $insert = ['add_time'];

    protected function setAddTimeAttr()
    {
        return time();
    }

    protected function setPicsAttr($value)
    {
        return is_array($value) ? json_encode($value) : $value;
    }

    protected function getPicsAttr($value)
    {
        return json_decode($value, true);
    }

    public static function reply($group, $type = 'product')
    {
        $group['reply_type'] = $type;
        return self::create($group);
    }

    public static function productValidWhere($alias = '')
    {
        if ($alias) {
            $model = self::alias($alias);
            $alias .= '.';
        } else {
            $model = new self;
        }
        return $model->where("{$alias}is_del", 0)->where("{$alias}reply_type", 'product');
    }

    /**
     * 设置查询商品评论条件
     * @param int $productId 商品id
     * @param int $type
     * @param string $alias
     * @return object
     */
    public static function setProductReplyWhere($productId, $type = 0, $alias = 'A')
    {
        $model = self::productValidWhere($alias)->where('A.product_id', $productId)
            ->field('A.product_score,A.service_score,A.comment,A.merchant_reply_content,A.merchant_reply_time,A.pics,A.add_time,B.nickname,B.avatar,C.cart_info,A.merchant_reply_content,A.nickname as _nickname,A.avatar as _avatar')
            ->join('user B', 'A.uid = B.uid', 'left')
            ->join('store_order_cart_info C', 'A.unique = C.unique', 'left');
        switch ($type) {
            case 1:
                $model = $model->where('A.product_score', 5);//好评
                break;
            case 2:
                $model = $model->where('A.product_score', '<', 5)->where('A.product_score', '>', 2);//中评
                break;
            case 3:
                $model = $model->where('A.product_score', '<', 2);//差评
                break;
        }
        return $model;
    }

    public static function getProductReplyList($productId, $order = 0, $page = 0, $limit = 8)
    {
        $model = self::setProductReplyWhere($productId, $order);
        if ($page) $model = $model->page((int)$page, (int)$limit);
        $list = $model->order('add_time desc')->select()->toArray() ?: [];
        foreach ($list as $k => $reply) {
            if (!$reply['nickname']) $list[$k]['nickname'] = $reply['_nickname'];
            if (!$reply['avatar']) $list[$k]['avatar'] = $reply['_avatar'];
            unset($list[$k]['_nickname'], $list[$k]['_avatar']);
            $list[$k] = self::tidyProductReply($list[$k]);
        }
        return $list;
    }

    /**
     * @param $res
     * @return mixed
     */
    public static function tidyProductReply($res)
    {
        $res['cart_info'] = json_decode($res['cart_info'], true) ?: [];
        $res['suk'] = isset($res['cart_info']['productInfo']['attrInfo']) ? $res['cart_info']['productInfo']['attrInfo']['suk'] : '';
        $res['nickname'] = anonymity($res['nickname']);
        $res['merchant_reply_time'] = date('Y-m-d H:i', $res['merchant_reply_time']);
        $res['add_time'] = date('Y-m-d H:i', $res['add_time']);
        $res['star'] = bcadd($res['product_score'], $res['service_score'], 2);
        $res['star'] = bcdiv($res['star'], 2, 0);
        $res['comment'] = $res['comment'] ?: '此用户没有填写评价';
        $res['pics'] = is_string($res['pics']) ? json_decode($res['pics'], true) : $res['pics'];
        unset($res['cart_info']);
        return $res;
    }

    public static function isReply($unique, $reply_type = 'product')
    {
        return self::be(['unique' => $unique, 'reply_type' => $reply_type]);
    }

    public static function getRecProductReply($productId)
    {
        $res = self::productValidWhere('A')->where('A.product_id', $productId)
            ->field('A.product_score,A.service_score,A.comment,A.merchant_reply_content,A.merchant_reply_time,A.pics,A.add_time,B.nickname,B.avatar,C.cart_info,A.nickname as _nickname,A.avatar as _avatar')
            ->join('user B', 'A.uid = B.uid', 'left')
            ->join('store_order_cart_info C', 'A.unique = C.unique', 'left')
            ->order('A.add_time DESC,A.product_score DESC, A.service_score DESC, A.add_time DESC')->find();
        if (!$res) return null;
        if (!$res['nickname']) $res['nickname'] = $res['_nickname'];
        if (!$res['avatar']) $res['avatar'] = $res['_avatar'];
        unset($res['_nickname'], $res['_avatar']);
        return self::tidyProductReply($res->toArray());
    }

    public static function productReplyCount($productId)
    {
        $data['sum_count'] = self::setProductReplyWhere($productId)->count();
        $data['good_count'] = self::setProductReplyWhere($productId, 1)->count();
        $data['in_count'] = self::setProductReplyWhere($productId, 2)->count();
        $data['poor_count'] = self::setProductReplyWhere($productId, 3)->count();
        if ($data['sum_count'] != 0) {
            $data['reply_chance'] = bcdiv($data['good_count'], $data['sum_count'], 2);
        } else {
            $data['reply_chance'] = 0;
        }
        $data['reply_star'] = bcmul($data['reply_chance'], 5, 0);
        $data['reply_chance'] = $data['sum_count'] == 0 ? 100 : bcmul($data['reply_chance'], 100, 2);
        return $data;
    }

    /**
     * @param $where
     * @return array
     */
    public static function sysPage($where)
    {
        $model = new self;
        $model = $model->alias('r')
            ->join('store_product p', 'p.id = r.product_id')
            ->join('wechat_user u', 'u.uid=r.uid', 'left');
        $model = $model->where('r.is_del', 0);
        if ($where['is_reply'] != '') $model = $model->where('r.is_reply', $where['is_reply']);
        if ($where['product_id']) $model = $model->where('r.product_id', $where['product_id']);
        if ($where['store_name']) $model = $model->where('p.store_name|r.product_id', 'Like', '%' . $where['store_name'] . '%');
        if ($where['account']) $model = $model->where('u.nickname', 'LIKE', '%' . $where['account'] . '%');
        if ($where['mer_id']) $model = $model->where('mer_id', $where['mer_id']);
        $model = $model->order('r.add_time desc,r.is_reply asc');
        $model = $model->field('r.*,p.store_name,p.image,u.nickname || r.nickname as account,FROM_UNIXTIME(r.add_time,"%Y-%m-%d %H:%i:%s") as add_time');
        $model = self::getModelTime($where, $model, "r.add_time");
        $count = $model->count();
        $list = $model->page((int)$where['page'], (int)$where['limit'])
            ->select()
            ->each(function ($item) {
                $item['time'] = time_tran(strtotime($item['add_time']));
                $item['create_time'] = $item['add_time'];
                $item['score'] = ($item['product_score'] + $item['service_score']) / 2;
            });
        return compact('count', 'list');
    }
}