<?php
namespace app\api\logic;

use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\logic\BaseLogic;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
use app\common\model\works\ServiceWork;
use think\facade\Db;
use think\facade\Log;

class RetentionMoneyLogic extends BaseLogic
{

    public static function add($params)
    {
        Db::startTrans();
        try {
            $surplus_money = 0;
            if(isset($params['work_id']) && !empty($params['work_id'])){
                $workModel = ServiceWork::findOrEmpty($params['work_id']);
                if($workModel->isEmpty()){
                    throw new \Exception('工单不存在');
                }
            }
            Log::info('RetentionMoneyLogic-params:'.json_encode($params));
            // $params['worker_id']
            $masterWorkerInfo = MasterWorker::where('id', $params['worker_id'])->findOrEmpty();
            $earnest_money_usable = (float)$masterWorkerInfo->earnest_money_usable + (float)$params['amount'];
            if($earnest_money_usable > (float)$masterWorkerInfo->earnest_money){
                $surplus_money = $earnest_money_usable - (float)$masterWorkerInfo->earnest_money;
                $params['remark'] .= "\n原质保金：{$masterWorkerInfo->earnest_money}，原可用质保金：{$masterWorkerInfo->earnest_money_usable}，缴纳多余：{$surplus_money}，实际缴纳：".((float)$params['amount']-$surplus_money);
                $masterWorkerInfo->earnest_money_usable += ((float)$params['amount']-$surplus_money);
            }
            $masterWorkerInfo->save();

            MasterWorkerRetentionMoneyLog::create([
                'sn' => generate_sn(MasterWorkerRetentionMoneyLog::class,'sn'),
                'worker_id' => $params['worker_id'],
                'action' => $params['action'],
                'amount' => ((float)$params['amount']-$surplus_money),
                'work_id' => $params['work_id'],
                'remark' => $params['remark'],
                'return_work_id' => isset($params['return_work_id'])?$params['return_work_id']:0,
            ]);

            Db::commit();
            return $surplus_money;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
}