<?php

namespace app\model;

use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\model\relation\HasOne;

class Overview extends Base
{
    /**
     * 用户
     *
     * @return HasOne
     */
    public function account(): HasOne
    {
        return $this->hasOne(Account::class, 'id', 'account_id');
    }

    /**
     * 员工
     *
     * @return HasOne
     */
    public function staff(): HasOne
    {
        return $this->hasOne(Staff::class, 'account_id', 'account_id');
    }

    /**
     * 统计数据更新
     *
     * @param  int  $accountId
     * @param  string  $action  操作 AccountRecord表的操作
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function renew(int $accountId, string $action): bool
    {
        if (!$account = Account::findById($accountId)) {
            \think\facade\Log::error('数据统计 overview 当前用户不存在');
            return true;
        }

        // 不允许 上级的操作 即 分享、收藏和查看 不增加上级的相关记录
        $notParentAction = [AccountRecord::ACTION_SHARE, AccountRecord::ACTION_VIEW, AccountRecord::ACTION_COLLECT];
        // 只更新自己数据的操作  分享和分享内容被查看
        if (in_array($action, [AccountRecord::ACTION_SHARE, AccountRecord::ACTION_SHARE_VIEW])) {
            $field = AccountRecord::actionField()[$action] ?? null;
            if (!$field) {
                throw new Exception('操作错误');
            }
            if ($info = Overview::findOne(['account_id' => $accountId])) {
                $info->inc($field)->update();
            } else {
                Overview::create([
                    'account_id' => $accountId,
                    $field       => 1
                ]);
            }
        }

        // 更新上级
        if ($account['inviter_account_id'] > 0 && !in_array($action, $notParentAction)) {
            if ($parent = Overview::findOne(['account_id' => $account['inviter_account_id']])) {
                $field = AccountRecord::overviewField()[$action] ?? null;
                if ($field) {
                    $parent->inc($field)->update();
                }
            } else {
                Overview::create([
                    'account_id' => $account['inviter_account_id'],
                    'shares'     => 0,
                    'views'      => $action == AccountRecord::ACTION_VIEW ? 1 : 0,
                    'customer'   => $action == AccountRecord::ACTION_REGISTER ? 1 : 0,
                    'asks'       => $action == AccountRecord::ACTION_SHARE ? 1 : 0,
                ]);
            }
        }
        return true;
    }
}