<?php

namespace app\command;

use app\common\model\shared\SharedProsperityPartnerConsumeUpdateLog;
use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class SharedPartnerConsumeUpdate extends Command
{
    // 变更数量
    const NUMBER = 5;

    const CONFIG_ID = 2;

    protected function configure()
    {
        // 指令配置
        $this->setName('sharedPartnerConsumeUpdate')
            ->setDescription('共富区一星合伙人消费额更新');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('定时任务执行中...');

        $this->consumeUpdate();

        $output->writeln('定时任务执行完成');
    }

    private function consumeUpdate()
    {
        // 获取当前数据
        /** @var SharedProsperityRecommendConfigRepository $repository */
        $repository = app()->make(SharedProsperityRecommendConfigRepository::class);
        $data = $repository->getDetail(self::CONFIG_ID);

        $logData = [
            'partner_level' => $data->level,
            'old_consume' => $data->consume,
            'number' => self::NUMBER,
            'new_consume' => $data->consume + self::NUMBER
        ];

        Db::startTrans();
        try {
            // 更新数据
            $data->consume += self::NUMBER;
            $data->save();
            // 记录日志
            $logModel = new SharedProsperityPartnerConsumeUpdateLog();
            $logModel->save($logData);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }

    }

}