<?php

namespace app\model;

use app\exception\RepositoryException;
use Exception;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\model\relation\HasOne;

/**
 * 拼团列表
 *
 * Class OrderGroupList
 * @package app\model
 */
class OrderGroupList extends Base
{
    /**
     * 历史记录
     *
     * @param  array  $where
     * @param  array  $field
     * @return OrderActivity[]|array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function history(array $where, array $field = [])
    {
        return self::where($where)->field($field)->select();
    }

    /**
     * 设为已付款
     *
     * @param  string  $orderCoding
     * @return bool
     */
    public static function setPaid(string $orderCoding): bool
    {
        return self::where('coding', $orderCoding)->save([
            'is_paid' => self::COMMON_ON,
            'paid_at' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * 订单相关信息取消(软删除)
     *
     * @param  string  $orderCoding
     * @return bool
     */
    public static function cancel(string $orderCoding): bool
    {
        return self::where('coding', $orderCoding)->save([
            'deleted_at' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * 活动商品信息
     *
     * @return HasOne
     */
    public function activity(): HasOne
    {
        return $this->hasOne(SpuActivity::class, 'id', 'spu_activity_id');
    }

    /**
     * 用户头像
     *
     * @return HasOne
     */
    public function accountCover(): HasOne
    {
        return $this->hasOne(Account::class, 'id', 'account_id')->bind([
            'cover' => 'headimgurl',
            'name' => 'nickname',
        ]);
    }

    /**
     * 创建拼团
     *
     * @param  array  $groupList
     * @throws Exception
     */
    public static function createGroup(array $groupList)
    {
        (new self())->saveAll($groupList);
        self::where('group_id', 0)->save(['group_id' => Db::raw('`id`')]);
    }

    /**
     * 订单信息
     *
     * @return HasOne
     */
    public function orderInfo(): HasOne
    {
        return $this->hasOne(Order::class, 'coding', 'coding');
    }

    /**
     * 用户信息
     *
     * @return HasOne
     */
    public function account(): HasOne
    {
        return $this->hasOne(Account::class, 'id', 'account_id')->withField(['id', 'nickname', 'real_name']);
    }
}