<?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 app\common\model\master_worker\MasterWorkerFreezeAmountLog;
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 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['earnest_money_usable'] =  $model->earnest_money_usable;
            $data['earnest_money_freeze'] = $model->earnest_money_freeze;
            $data['earnest_money'] = $model->earnest_money;
            $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 addDeduct($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('工单不存在');
                }
            }

            // $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;
            }

            if($params['action'] == WorkerAccountLogEnum::FROZEN){
                $earnest_money_usable = $masterWorkerInfo->earnest_money_usable - $params['amount'];
                if($earnest_money_usable < 0){
                    throw new \Exception('可用质保金不足');
                }
                $params['action'] = WorkerAccountLogEnum::DEC;
                $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
                $masterWorkerInfo->earnest_money_freeze += $params['amount'];
            }
            if($params['action'] == WorkerAccountLogEnum::RELEASE){
                $masterWorkerInfo->earnest_money_freeze -= $params['amount'];
                if($masterWorkerInfo->earnest_money_freeze < 0){
                    throw new \Exception('冻结质保金不足');
                }
                $earnest_money_usable = $masterWorkerInfo->earnest_money_usable + $params['amount'];
                if($earnest_money_usable > $masterWorkerInfo->earnest_money){
                    // 多余的部分质保金退回给用户账号余额即可以提现
                    $surplus = $earnest_money_usable - $masterWorkerInfo->earnest_money;


                    $params['amount'] = $params['amount'] - $surplus;
                    $earnest_money_usable = $masterWorkerInfo->earnest_money;
                    throw new \Exception('可用质保金超过配置质保金');
                }
                $params['action'] = WorkerAccountLogEnum::INC;
                $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
            }

            $masterWorkerInfo->save();

            $retentionMoneyLog = MasterWorkerRetentionMoneyLog::create([
                'sn' => generate_sn(MasterWorkerRetentionMoneyLog::class,'sn'),
                'worker_id' => $params['worker_id'],
                'action' => in_array($params['action'],[WorkerAccountLogEnum::FROZEN,WorkerAccountLogEnum::DEC])?WorkerAccountLogEnum::DEC:WorkerAccountLogEnum::INC,
                'amount' => $params['amount'],
                'work_id' => $params['work_id'],
                'remark' => $params['remark'],
            ])->getData();
            // 当为冻结时，冻结金额要记录到日志中 $retentionMoneyLog


            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            Log::info('RetentionMoneyLogic-addDeduct-error:'.$e->getMessage());
            return false;
        }
    }


    // 工单结算缴纳质保金
    public static function retentionPayment($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);
            }else{
                $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
            }
            $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'],
                'source' => 2,
                '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());
            Log::info('RetentionMoneyLogic-retentionPayment-error:'.$e->getMessage());
            return false;
        }
    }

    // 扣除质保金可用额 (包括工单直接退款、冻结)
    // source remark issue_work_id work_id amount worker_id to_freeze
    public static function refundRetention($params,$to_freeze = true)
    {
        Db::startTrans();
        try {

            // $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){
                Log::info('RetentionMoneyLogic-refundRetention-error:退可用质保金不足:'.$earnest_money_usable.'，可用质保金：'.$masterWorkerInfo->earnest_money_usable);
                $earnest_money_usable = 0;
                $params['amount'] = $masterWorkerInfo->earnest_money_usable;
            }
            $masterWorkerInfo->earnest_money_usable = $earnest_money_usable;
            // 是否要扣到 冻结 里面？
            $to_freeze && $masterWorkerInfo->earnest_money_freeze += $params['amount'];
            $masterWorkerInfo->save();

            $retentionMoneyLog = 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'],
                'to_freeze' => isset($params['to_freeze'])?$params['to_freeze']:0,
            ]);
            $retention_money_log_id = $retentionMoneyLog->id;
            // 记录冻结金额日志 - 增加
            if($to_freeze){
                MasterWorkerFreezeAmountLog::create([
                    'sn' => generate_sn(MasterWorkerFreezeAmountLog::class,'sn'),
                    'master_worker_id' => $params['worker_id'],
                    'action' => WorkerAccountLogEnum::INC,
                    'amount' => $params['amount'],
                    'work_id' => $params['work_id'],
                    'issue_work_id' => isset($params['issue_work_id'])?$params['issue_work_id']:0,
                    'retention_money_log_id' => $retention_money_log_id?:0,
                    'remark' => $params['remark'],
                    'source' => $params['source']
                ]);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            Log::info('RetentionMoneyLogic-refundRetention-error:'.$e->getMessage());
            return false;
        }
    }


    // 冻结投诉冻结质保金
    public static function warrantyDepositFreeze($issueWork)
    {
        Db::startTrans();
        try {

            $work = ServiceWork::where('id',$issueWork->service_work_id)->findOrEmpty();
            if(!$work->isEmpty()){
                // 应退余额
                $change_amount = MasterWorkerAccountLog::where([
                    'change_object'=>WorkerAccountLogEnum::UM,'change_type'=>WorkerAccountLogEnum::UM_INC_ADMIN,
                    'action'=>WorkerAccountLogEnum::INC,'worker_id'=>$issueWork->master_worker_id,
                    'work_sn'=>$issueWork->work_sn])->value('change_amount');
                // 应退质保金
                $retentionAmount = MasterWorkerRetentionMoneyLog::where(['action'=>WorkerAccountLogEnum::INC,
                    'worker_id'=>$issueWork->master_worker_id,'work_id'=>$issueWork->service_work_id])
                    ->value('amount');

                // 总金额 = 退款金额 + 退质保金
                $totalAmount = ($change_amount?:0) + ($retentionAmount?:0);
                $remark = '工单号：'.$issueWork->work_sn.'，退款总金额：'.$totalAmount.
                    '，应退余额：'.($change_amount?:0).
                    '，应退质保金：'.($retentionAmount?:0).
                    '，退款原因：投诉冻结';
                $res = self::refundRetention([
                    'source'=>1,'remark'=>$remark,
                    'issue_work_id' => $issueWork->id?:0,
                    'work_id'=>$issueWork->service_work_id,'worker_id'=>$issueWork->master_worker_id,
                    'amount'=>$totalAmount,'to_freeze'=>1
                ]);
                if (false === $res) {
                    throw new \Exception(self::getError());
                }
            }


            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            Log::info('RetentionMoneyLogic-warrantyDepositFreeze-error:'.$e->getMessage());
            return false;
        }
    }


    // 解冻投诉冻结质保金
    /* to_freeze source remark work_id amount  worker_id issue_work_id */
    public static function warrantyDepositRelease($params,$is_zero = false)
    {
        Db::startTrans();
        try {
            // $params['worker_id']
            $masterWorkerInfo = MasterWorker::where('id', $params['worker_id'])->findOrEmpty();
            $masterWorkerInfo->earnest_money_freeze -= $params['amount'];
            if($is_zero){
                /*$retention_money_log_id = MasterWorkerFreezeAmountLog::where([
                    'action'=>WorkerAccountLogEnum::INC,
                    'issue_work_id'=>$params['issue_work_id'],'master_worker_id'=>$params['worker_id']])->value('retention_money_log_id');
                MasterWorkerRetentionMoneyLog::where('id',$retention_money_log_id)->update(['to_freeze'=>2]);*/
                $params['amount'] = 0;
            }else{
                $masterWorkerInfo->earnest_money_usable += $params['amount'];
            }
            $retentionMoneyLog = MasterWorkerRetentionMoneyLog::create([
                'sn' => generate_sn(MasterWorkerRetentionMoneyLog::class,'sn'),
                'worker_id' => $params['worker_id'],
                'action' => WorkerAccountLogEnum::INC,
                'amount' => $params['amount'],
                'work_id' => $params['work_id'],
                'remark' => $params['remark'],
                'source' => $params['source'],
                'to_freeze' => 2,
            ]);
            $retention_money_log_id = $retentionMoneyLog->id;
            // 记录冻结金额日志 - 扣减
            MasterWorkerFreezeAmountLog::create([
                'sn' => generate_sn(MasterWorkerFreezeAmountLog::class,'sn'),
                'master_worker_id' => $params['worker_id'],
                'action' => WorkerAccountLogEnum::DEC,
                'amount' => $params['amount'],
                'work_id' => $params['work_id'],
                'retention_money_log_id' => $retention_money_log_id?:0,
                'issue_work_id' => isset($params['issue_work_id'])?$params['issue_work_id']:0,
                'remark' => $params['remark'],
                'source' => $params['source']
            ]);

            $masterWorkerInfo->save();

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            Log::info('RetentionMoneyLogic-warrantyDepositRelease-error:'.$e->getMessage());
            return false;
        }
    }


}