<?php
namespace app\api\logic;

use app\common\logic\BaseLogic;
use app\common\model\goods\Goods;
use app\common\model\orders\RechargeOrder;
use app\common\model\recharge\OrderGoods;
use app\common\model\reviews\GoodsReviews;
use app\common\model\works\ServiceWork;
use think\Exception;
use think\facade\Db;

/**
 * 服务商品评论逻辑处理
 * Class GoodsReviewsLogic
 * @package app\api\logic
 */
class GoodsReviewsLogic extends BaseLogic
{
    /**
     * @param $params
     * @return bool
     */
    public static function add($params)
    {
        Db::startTrans();
        try {
            $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty()->toArray();
            $goods_id = OrderGoods::whereIn('sn', RechargeOrder::where('work_id',$order['work_id'])->column('sn'))->value('goods_id');
            $work = ServiceWork::findOrEmpty($order['work_id']);
            if($work['work_status']==8){
                throw new Exception('订单已评价');
            }
            if($work['work_status']!=7){
                throw new Exception('订单无法评价');
            }
            GoodsReviews::create([
                'goods_id'=>$goods_id,
                'goods_category_id'=>$work['goods_category_id'],
                'user_id'=>$params['user_id'],
                'nickname'=>$params['user_info']['nickname'],
                'avatar'=>$params['user_info']['avatar'],
                'rating'=>$params['rating'],
                'comment'=>!empty($params['comment'])?$params['comment']:'用户暂无评论',
                'review_image'=>!empty($params['review_image'])?$params['review_image']:[],
            ]);
            $work->work_status = 8;
            $work->save();

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
}