<?php

namespace app\common\logic;

use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use think\Exception;

class WorkerAccountLogLogic extends BaseLogic
{
    /**
     * @param $work //工单对象
     * @param $change_amount //变动数量
     * @param $change_type //变动类型
     * @param $action //动作 1-增加 2-减少
     * @return bool|void
     * @throws Exception
     */
    public static function addAccountLog($work,$changeAmount,$changeType,$action, string $remark = '',  array $extra = [])
    {
        $worker = MasterWorker::findOrFail($work->master_worker_id);
        if($worker->isEmpty()) {
            throw new Exception('师傅不存在');
        }

        $changeObject = WorkerAccountLogEnum::getChangeObject($changeType);
        if(!$changeObject) {
            throw new Exception('结算错误');
        }

        switch ($changeObject) {
            // 用户余额
            case WorkerAccountLogEnum::UM:
                $left_amount = $worker->user_money;
                break;
            // 其他
        }

        $data = [
            'sn' => generate_sn(MasterWorkerAccountLog::class, 'sn', 20),
            'title'=>$work->title,
            'worker_id' => $work->master_worker_id,
            'change_object' => $changeObject,
            'change_type' => $changeType,
            'action' => $action,
            'left_amount' => $left_amount,
            'change_amount' => $changeAmount,
            'work_sn' => $work->work_sn,
            'remark' => $remark,
            'extra' => $extra ? json_encode($extra, JSON_UNESCAPED_UNICODE) : '',
        ];
        MasterWorkerAccountLog::create($data);

        $worker->user_money = $left_amount + ($action==1?$changeAmount:-$changeAmount);
        $worker->save();

        return true;
    }
}