<?php

namespace app\api\logic;

use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\logic\BaseLogic;
use app\common\logic\EffectiveLogic;
use app\common\logic\WorkAddMoneyLogic;
use app\common\logic\WorkerAccountLogLogic;
use app\common\model\master_commission\MasterWorkerCommissionConfig;
use app\common\model\master_commission\MasterWorkerCommissionRatio;
use app\common\model\master_worker\MasterWorker;
use app\common\model\orders\RechargeOrder;
use app\common\model\performance\PerformanceRules;
use app\common\model\recharge\OrderGoods;
use app\common\logic\RetentionMoneyLogic;
use think\facade\Db;
use think\facade\Log;


/**
 *  工程师业绩逻辑层
 * Class PerformanceLogic
 * @package app\api\logic
 */
class PerformanceLogic extends BaseLogic
{
    /**
     * @param $work
     * @return false|void
     */
    public static function calculatePerformance($work)
    {
        Log::info('calculatePerformance:'.json_encode($work->toArray()));
        //工单已完结，进行结算,结算完成后设置work_pay_status为2，已结算
        //获取工单对应的商品id
        $order_sns = RechargeOrder::where('work_id',$work->id)->column('sn');
        $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
        $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
        if($rule->isEmpty()){
            $work->work_pay_status = 3;
        }else{
            $work->work_pay_status = 2;
        }
        Log::info('calculatePerformance:'.json_encode($rule->toArray()));
        //工程师金额结算
        if(!$rule->isEmpty()){
            $coupon_price = RechargeOrder::where('work_id',$work->id)->sum('coupon_price');
            switch ($rule['type']){
                case 0://按照总金额结算
                    $settlement_amount = bcmul($work->work_total, $rule['rate'],2);
                    break;
                case 1://按照结算金额结算
                    $worker_price = $work->work_amount;
                    $settlement_amount = bcmul($worker_price, $rule['rate'],2);
                    break;
                case 2://按照服务总费用结算
                    //搜索所有优惠券
                    $worker_price = $work->service_fee-$coupon_price;
                    $settlement_amount = bcmul($worker_price, $rule['rate'],2);
                    break;
                default://按照固定金额结算
                    $worker_price = $work->service_fee-$coupon_price;
                    $settlement_amount = $rule['rate'];
            }
            $work->worker_price = $worker_price;

            // 缴纳质保金
            $masterWorkerInfo = MasterWorker::where('id', $work->master_worker_id)->where('retention_money_status', 1)->findOrEmpty()->toArray();
            Log::info('缴纳质保金工程师信息:'.json_encode($masterWorkerInfo));
            if(!empty($masterWorkerInfo) && $masterWorkerInfo['retention_pay_status'] == 2 && ($masterWorkerInfo['earnest_money'] > $masterWorkerInfo['earnest_money_usable'])){
                $retentionData['action'] = WorkerAccountLogEnum::INC;
                $retentionData['worker_id'] = $work->master_worker_id;
                $retentionData['work_id'] = $work->id;
                $amount = bcmul($worker_price, bcdiv($masterWorkerInfo['installment_ratio'], 100, 4),2);
                //$amount = bcmul($settlement_amount, bcdiv($masterWorkerInfo['installment_ratio'], 100, 4),2);
                $retentionData['amount'] = $amount;
                //$retentionData['remark'] = "分期缴纳质保金：该单实提成--{$settlement_amount},分期每单缴纳比例--{$masterWorkerInfo['installment_ratio']}%,缴纳金额--{$amount}";
                $retentionData['remark'] = "分期缴纳质保金：工单提成--{$worker_price},分期每单缴纳比例--{$masterWorkerInfo['installment_ratio']}%,缴纳金额--{$amount}";
                $settlement_amount -= (float)$amount;
                $surplusMoney = RetentionMoneyLogic::retentionPayment($retentionData);
                Log::info('分期缴纳质保金:'.$surplusMoney,$retentionData);
                if($surplusMoney === false){
                    Log::info('分期缴纳质保金支付失败-'.RetentionMoneyLogic::getError(),$retentionData);
                    $settlement_amount += (float)$amount;
                }else{
                    $settlement_amount += (float)$surplusMoney;

                    $work->earnest_money = $amount - $surplusMoney;//质保金金额
                }
            }

            if($settlement_amount<0){
                //修改工单为待结算，后台处理
                $work->work_pay_status = 3;
            }

            //工程师可提现金额
            $work->settlement_amount = $settlement_amount;

            //工程师加单金额判定
            //$add_work_amount = 0;测试
            $add_work_amount = WorkAddMoneyLogic::checkAddWork($work,$worker_price);
            $work->add_work_amount = $add_work_amount;

            //系统回收金额
            $work->system_amount = $worker_price-$settlement_amount-$work->earnest_money-$work->add_work_amount;

            //工程师可提现金额，汇总了加单金额
            $settlement_amount += (float)$work->add_work_amount;

            Log::info('工单'.$work->id.',总服务费：'.$worker_price.'可提现金额:'.$settlement_amount.',加单金额：'.$work->add_work_amount.',缴纳质保金：'.$work->earnest_money.'，系统回收金额：'.$work->system_amount);

            WorkerAccountLogLogic::addAccountLog($work,$settlement_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
        }
        $work->save();
        //生成保修卡
        EffectiveLogic::receiveEffective($work);
    }

    public static function calculatePerformanceCommission($work)
    {
        Log::info('calculatePerformanceCommission:'.json_encode($work->toArray()));
        //工单已完结，进行结算,结算完成后设置work_pay_status为2，已结算
        //获取工单对应的商品id
        $order_sns = RechargeOrder::where('work_id',$work->id)->column('sn');
        $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
        $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$work->master_worker_id)->where('voucher_status',2)->find()->toArray();
        $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$work->goods_category_id)->value('ratio');

        Log::info('calculatePerformanceCommission:'.json_encode([$commissionConfig,$ratio]));

        if($commissionConfig && 0 < $ratio  && $ratio < 1){
            $work->work_pay_status = 2;
            //工程师金额结算
            //$coupon_price = RechargeOrder::where('work_id',$work->id)->sum('coupon_price');
            $work->worker_price = $work->work_total;
            $settlement_amount = bcmul($work->work_total, $ratio,2);
            // 缴纳质保金
            $masterWorkerInfo = MasterWorker::where('id', $work->master_worker_id)->where('retention_money_status', 1)->findOrEmpty()->toArray();
            Log::info('缴纳质保金工程师信息:'.json_encode($masterWorkerInfo));
            if(!empty($masterWorkerInfo) && $masterWorkerInfo['retention_pay_status'] == 2 && ($masterWorkerInfo['earnest_money'] > $masterWorkerInfo['earnest_money_usable'])){
                $retentionData['action'] = WorkerAccountLogEnum::INC;
                $retentionData['worker_id'] = $work->master_worker_id;
                $retentionData['work_id'] = $work->id;
                $amount = bcmul($work->worker_price, bcdiv($masterWorkerInfo['installment_ratio'], 100, 4),2);
                $retentionData['amount'] = $amount;
                $retentionData['remark'] = "分期缴纳质保金：工单提成--{$work->worker_price},分期每单缴纳比例--{$masterWorkerInfo['installment_ratio']}%,缴纳金额--{$amount}";
                $settlement_amount -= (float)$amount;
                $surplusMoney = RetentionMoneyLogic::retentionPayment($retentionData);
                Log::info('Commission-分期缴纳质保金:'.$surplusMoney,$retentionData);
                if($surplusMoney === false){
                    Log::info('Commission-分期缴纳质保金支付失败-'.RetentionMoneyLogic::getError(),$retentionData);
                    $settlement_amount += (float)$amount;
                }else{
                    $settlement_amount += (float)$surplusMoney;

                    $work->earnest_money = $amount - $surplusMoney;//质保金金额
                }
            }

            if($settlement_amount<0){
                //修改工单为待结算，后台处理
                $work->work_pay_status = 3;
            }

            //工程师可提现金额
            $work->settlement_amount = $settlement_amount;

            //工程师加单金额判定
            //$add_work_amount = 0;测试
            $add_work_amount = WorkAddMoneyLogic::checkAddWork($work,$work->worker_price);
            $work->add_work_amount = $add_work_amount;

            //系统回收金额
            $work->system_amount = $work->worker_price-$settlement_amount-$work->earnest_money-$work->add_work_amount;

            //工程师可提现金额，汇总了加单金额
            $settlement_amount += (float)$work->add_work_amount;

            Log::info('工单'.$work->id.',总服务费：'.$work->worker_price.'可提现金额:'.$settlement_amount.',加单金额：'.$work->add_work_amount.',缴纳质保金：'.$work->earnest_money.'，系统回收金额：'.$work->system_amount);

            WorkerAccountLogLogic::addAccountLog($work,$settlement_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
        }
        $work->save();
        //生成保修卡
        EffectiveLogic::receiveEffective($work);
    }

}