<?php

namespace app\admin\service\order;

use app\admin\service\member\MemberService;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberAccountList;
use app\model\SysConfig;
use support\Log;

class CommissionService
{
    /*
    {
        "config": {
            "name": "名称",
            "valid": 365, //有效天
            "protocol": 229, //服务协议分类ID
            "notice":["", ""] //注意事项数组
        },
        "goods": {
            "goods_id": "", //产品ID
            "goods_sku_id": 0, //产品SKUID
            "amount": "goods_sales_price" //核算金额字段
        },
        "commission": {
            "direct": 0.2, //直属提成
            "indirect": 0.1, //间属提成
            "relate-consum": 0.1, //消费关联提成 带客
            "invite-non-identity": 0.05, //邀请人非身份会员达成提成
            "agent-senior-join": 0.05, //中介加盟合伙人提成
            "agent-senior-strategy": 0.05, //中介战略合伙人提成
            "account":"CASH" //提成写入账户
        },
        "account": {
            "account":"CASH", //达成金额进入账户 不则为空
            "added":0.12 //达成金额增值 不则为0
        },
        "control": {
            "notify": "procMemberPartnerExec", //回调函数
            "if_installment": "N", //是否支持分期
            "if_commission_out": "Y" //提成是否可提现
        }
    }
     */

    /**
     * @Desc 处理提成
     * @Author Gorden
     * @Date 2024/9/28 16:09
     *
     * @param $config
     * @param $memberId
     * @param $orderId
     * @param $amount
     * @param $accountListCategory
     * @return void
     */
    public static function commission($config, $memberId, $orderId, $amount, $accountListCategory)
    {
        Log::info("开始处理提成", ['member_id' => $memberId, 'amount' => $amount]);
        try {
            $member = Member::where('member_id', $memberId)->first();
            $configParams1 = [];
            $configParams2 = [];
            if (!empty($member->join_invite_member_id)) {
                $member1 = Member::where('member_id', $member->join_invite_member_id)->first();
                if ($member1->member_is_partner == 'Y') {
                    $config1 = SysConfig::where('config_key', 'app-identity-partner-config')->first();
                } else if ($member1->member_is_referrer == 'Y') {
                    $config1 = SysConfig::where('config_key', 'app-identity-referrer-config')->first();
                } else if ($member1->member_is_franchisee == 'Y') {
                    $config1 = SysConfig::where('config_key', 'app-identity-franchisee-config')->first();
                }
                if (!empty($config1)) {
                    $configParams1 = json_decode($config1->config_value_json, true);
                    Log::info("一级提成参数", ['config' => $configParams1]);
                }
                if (!empty($member1->join_invite_member_id)) {
                    $member2 = Member::where('member_id', $member1->join_invite_member_id)->first();
                    if ($member2->member_is_partner == 'Y') {
                        $config2 = SysConfig::where('config_key', 'app-identity-partner-config')->first();
                    } else if ($member1->member_is_referrer == 'Y') {
                        $config2 = SysConfig::where('config_key', 'app-identity-referrer-config')->first();
                    } else if ($member1->member_is_franchisee == 'Y') {
                        $config2 = SysConfig::where('config_key', 'app-identity-franchisee-config')->first();
                    }
                    if (!empty($config2)) {
                        $configParams2 = json_decode($config2->config_value_json, true);
                        Log::info("二级提成参数", ['config' => $configParams2]);
                    }
                }
            }
            if (empty($configParams1) && empty($configParams2)) {
                Log::info("提成失败，提成参数异常", ['member_id' => $memberId, 'amount' => $amount]);
            }
            // 提成记录JSON
            $accountListJson = [
                'line' => 'relate-consum',
                'amount' => $amount,
                'order_id' => $orderId,
                'master_member_id' => $memberId
            ];
            // 直属提成
            if (!empty($member1) && ($member1->member_is_partner == 'Y' || $member1->member_is_referrer == 'Y' || $member1->member_is_franchisee == 'Y') && !empty($configParams1)) {
                $accountListJson['identity'] = MemberService::getIdentity($member1->member_is_partner, $member1->member_is_referrer, $member1->member_is_franchisee);
                $accountListJson['line'] = 'direct';
                $member1CommissionAmount = $configParams1['commission']['direct'] * $amount;
                self::commissionToMember($member1->member_id, $accountListJson, $member1CommissionAmount, $accountListCategory);
                Log::info("直属提成参数", ['member_id' => $member1->member_id, 'account_list_json' => $accountListJson, 'amount' => $member1CommissionAmount, 'category' => $accountListCategory]);

            }
            // 间属提成
            if (!empty($member2) && ($member2->member_is_partner == 'Y' || $member2->member_is_referrer == 'Y' || $member1->member_is_franchisee == 'Y') && !empty($configParams2)) {
                $accountListJson['identity'] = MemberService::getIdentity($member2->member_is_partner, $member2->member_is_referrer, $member2->member_is_franchisee);
                $accountListJson['line'] = 'indirect';
                $member2CommissionAmount = $configParams2['commission']['indirect'] * $amount;
                self::commissionToMember($member2->member_id, $accountListJson, $member2CommissionAmount, $accountListCategory);
                Log::info("间属提成参数", ['member_id' => $member2->member_id, 'account_list_json' => $accountListJson, 'amount' => $member2CommissionAmount, 'category' => $accountListCategory]);

            }
        } catch (\Exception $e) {
            Log::error("提成处理失败", ['msg' => $e->getMessage()]);
            _syslog("提成处理失败", '提成处理失败');
        }
    }

    /**
     * @Desc 提成到账户
     * @Author Gorden
     * @Date 2024/9/25 15:14
     *
     * @param $memberId
     * @param $accountListJson
     * @param $money
     * @return void
     */
    private static function commissionToMember($memberId, $accountListJson, $money, $accountListCategory)
    {
        $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'CASH')->first();
        $account->member_account_income = $account->member_account_income + $money;
        $account->member_account_surplus = $account->member_account_surplus + $money;
        $account->save();

        MemberAccountList::insert([
            'join_list_member_account_nbr' => $memberId . '-CASH',
            'join_member_account_list_member_id' => $memberId,
            'member_account_list_status' => 'ACTIVED',
            'member_account_list_attr' => 'IN',
            'member_account_list_classify' => $accountListJson['identity'],
            'member_account_list_category' => $accountListCategory,
            'member_account_list_datetime' => date('Y-m-d H:i:s'),
            'member_account_list_amount' => $money,
            'member_account_list_json' => json_encode($accountListJson),
            'member_account_list_addtimes' => time()
        ]);
    }

    /**
     * @Desc 驳回提现申请，重新插一条入账记录
     * @Author Gorden
     * @Date 2024/12/9 10:26
     *
     * @param $memberId
     * @param $money
     * @param $accountListJson
     * @return void
     */
    public static function withdrawReject($memberId, $money, $accountListJson)
    {
        MemberAccountList::insert([
            'join_list_member_account_nbr' => $memberId . '-CASH',
            'join_member_account_list_member_id' => $memberId,
            'member_account_list_status' => 'ACTIVED',
            'member_account_list_attr' => 'IN',
            'member_account_list_classify' => 'REJECT_WITHDRAW',
            'member_account_list_category' => '驳回提现申请',
            'member_account_list_datetime' => date('Y-m-d H:i:s'),
            'member_account_list_amount' => $money,
            'member_account_list_json' => json_encode($accountListJson),
            'member_account_list_addtimes' => time()
        ]);
    }
}