<?php

namespace App\Services\Deed;

use App\Exceptions\AlertException;
use App\Models\Deed\DeedCommentModel;
use App\Models\Deed\DeedModel;
use App\Services\Service;

/**
 * 契约评论
 * Class CommentService
 * @package App\Services\Deed
 * @deprecated
 */
class CommentService extends Service
{
    /**
     * 评论契约
     * @param  int  $deed_id
     * @param  array  $comments
     * @return bool
     * @throws AlertException
     */
    public function comment(int $deed_id, array $comments)
    {
        $deed = DeedModel::findOrFail($deed_id);
        if (empty($deed->number)) {
            throw new AlertException('契约失效', 401);
        }

        if (DeedCommentModel::where([['number', $deed->number], ['uid', $deed->uid]])->exists()) {
            $deed->state = 5;
            $deed->save();
            throw new AlertException('契约失效', 402);
        }

        $other = DeedModel::where([['number', $deed->number], ['id', '!=', $deed_id]])->first();

        \DB::beginTransaction();
        try {
            \DB::table('kdgx_fpdx_deed_comment')->insert([
                'created_at' => time(),
                'updated_at' => time(),
                'number' => $deed->number,
                'uid' => $deed->uid,
                'comment_uid' => $other->uid,
                'speed' => $comments['speed'],
                'level' => $comments['level'],
            ]);
            \DB::table('kdgx_fpdx_deed')->where('id', $deed_id)->update(['state' => 5, 'complete_at' => time()]);
            \DB::commit();

            return true;
        } catch (\Exception $e) {
            \DB::rollBack();

            return false;
        }
    }
}
