<?php



namespace ln\listens;


use app\common\repositories\system\merchant\MerchantRepository;
use app\common\repositories\user\UserBillRepository;
use ln\interfaces\ListenerInterface;
use ln\services\TimerService;
use think\facade\Db;

class AutoUnlockMerchantMoneyListen extends TimerService implements ListenerInterface
{
    public function handle($event): void
    {
        $this->tick(1000 * 60 * 20, function () {
            request()->clearCache();
            $userBill = app()->make(UserBillRepository::class);
            $timer = ((int)systemConfig('mer_lock_time'));
            $time = date('Y-m-d H:i:s', $timer ? strtotime("- $timer day") : time());
            $bills = $userBill->getTimeoutMerchantMoneyBill($time);
            $merchant = app()->make(MerchantRepository::class);
            foreach ($bills as $bill) {
                $money = bcsub($bill->number, $userBill->refundMerchantMoney($bill->link_id, $bill->type, $bill->mer_id), 2);
                Db::transaction(function () use ($bill, $merchant, $money) {
                    if ($money > 0) {
                        $merchant->addMoney($bill->mer_id, $money);
                    }
                    $bill->status = 1;
                    $bill->save();
                });
            }
        });
    }
}