<?php
/**
 * @author 林海涛
 * @date 2024/7/28 下午2:36
 */
namespace app\adminapi\logic\master_worker;

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;

class RetentionMoneyLogic extends BaseLogic
{
    public static function totalAmount($params)
    {
        try{
            $model = MasterWorker::findOrEmpty($params['worker_id']);
            if($model->isEmpty()){
                throw new \Exception('用户不存在');
            }
            $where = [];
            $where[] = ['worker_id','=',$params['worker_id']] ;
            $incWhere =$where;
            $incWhere[] = ['action', '=',WorkerAccountLogEnum::INC];
            $data = [];
            //$data['amount_inc_total'] = MasterWorkerRetentionMoneyLog::where($incWhere)->sum('amount');
            $data['amount_inc_total'] = $model->earnest_money;

            $outWhere = $where;
            $outWhere[] =['action', '=',WorkerAccountLogEnum::DEC];
            //$data['amount_dec_total'] = MasterWorkerRetentionMoneyLog::where($outWhere)->sum('amount');
            $data['amount_dec_total'] = $model->earnest_money_freeze;
            //$data['amount_available_total'] = $data['amount_inc_total'] - $data['amount_dec_total'];
            $data['amount_available_total'] = $model->earnest_money_usable;


            $data['retention_money_status'] = $model->retention_money_status;
            $data['retention_money_status_text'] = $model->retention_money_status_text;
            $data['retention_pay_status'] = $model->retention_pay_status;
            $data['retention_pay_status_text'] = $model->retention_pay_status_text;
            $data['worker_number'] = $model->worker_number;
            $data['real_name'] = $model->real_name;
            $data['worker_id'] = $model->id;
            $data['installment_ratio'] = $model->installment_ratio;
            return $data;
        } catch(\Exception $e){
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function add($params)
    {
        Db::startTrans();
        try {
            if(isset($params['work_id']) && !empty($params['work_id'])){
                $workModel = ServiceWork::findOrEmpty($params['work_id']);
                if($workModel->isEmpty()){
                    throw new \Exception('工单不存在');
                }
            }
            MasterWorkerRetentionMoneyLog::create([
                'sn' => generate_sn(MasterWorkerRetentionMoneyLog::class,'sn'),
                'worker_id' => $params['worker_id'],
                'action' => $params['action'],
                'amount' => $params['amount'],
                'work_id' => $params['work_id'],
                'remark' => $params['remark'],
            ]);

            // $params['worker_id']
            $masterWorkerInfo = MasterWorker::where('id', $params['worker_id'])->findOrEmpty();
            if($params['action'] == WorkerAccountLogEnum::INC){
                $earnest_money_usable = $masterWorkerInfo->earnest_money_usable + $params['amount'];
                if($earnest_money_usable > $masterWorkerInfo->earnest_money){
                    throw new \Exception('可用质保金超过配置质保金');
                }
                $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
            }
            if($params['action'] == WorkerAccountLogEnum::DEC){
                $earnest_money_usable = $masterWorkerInfo->earnest_money_usable - $params['amount'];
                if($earnest_money_usable < 0){
                    throw new \Exception('可用质保金不足');
                }
                $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
                $masterWorkerInfo->earnest_money_freeze += $params['amount'];
            }
            $masterWorkerInfo->save();

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function refundRetention($params,$to_freeze = true)
    {
        Db::startTrans();
        try {
            if(isset($params['work_id']) && !empty($params['work_id'])){
                $workModel = ServiceWork::findOrEmpty($params['work_id']);
                if($workModel->isEmpty()){
                    throw new \Exception('工单不存在');
                }
            }
            MasterWorkerRetentionMoneyLog::create([
                'sn' => generate_sn(MasterWorkerRetentionMoneyLog::class,'sn'),
                'worker_id' => $params['worker_id'],
                'action' => WorkerAccountLogEnum::DEC,
                'amount' => $params['amount'],
                'work_id' => $params['work_id'],
                'remark' => $params['remark'],
                'return_work_id' => isset($params['return_work_id'])?$params['return_work_id']:0,
            ]);

            // $params['worker_id']
            $masterWorkerInfo = MasterWorker::where('id', $params['worker_id'])->findOrEmpty();
            $earnest_money_usable = $masterWorkerInfo->earnest_money_usable - $params['amount'];
            if($earnest_money_usable < 0){
                throw new \Exception('退可用质保金不足');
            }
            $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
            // 是否要扣到 冻结 里面？
            $to_freeze && $masterWorkerInfo->earnest_money_freeze += $params['amount'];
            $masterWorkerInfo->save();

            // 记录冻结金额日志
            if($to_freeze){

            }

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