<?php

namespace app\event\order;

use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberAccountList;
use app\model\Order;
use app\model\PayDetail;
use app\model\SysConfig;
use support\Db;
use support\exception\BusinessException;
use support\Log;

class CommissionEvent
{
//{
//"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" //提成是否可提现
//	}
//}
    public function order($params)
    {
        Log::info("计算消费提成", $params);
        $accountListCategory = $params['member_account_list_category'] ?? '消费';
        Db::beginTransaction();
        try {
            $order = Order::where('order_id', $params['orderId'])->where('order_status_payment', 'SUCCESS')->first();
            $actualPaymentAmount = PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
                ->where('pay_status', 'SUCCESS')
                ->whereIn('pay_prepayid', ['WXPAY', 'ALIPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY'])
                ->sum('pay_amount');
            if ($actualPaymentAmount == 0) {
                throw new BusinessException("微信、支付宝、现金支付金额为0");
            }
            // 有传过来的
            if (!empty($params['join_invite_member_id'])) {
                $inviteMemberId = $params['join_invite_member_id'];
            } else {
                // 下单人
                $member = Member::where('member_id', $order->join_order_member_id)->first();
                if (empty($member->join_invite_member_id)) {
                    throw new BusinessException("没有直属上级");
                }
                $inviteMemberId = $member->join_invite_member_id;
            }
            // 上级
            $memberUp = Member::where('member_id', $inviteMemberId)->first();
            if ($memberUp->member_is_partner == 'Y') {
                $identity = 'PARTNER';
                // 提成设置
                $config = SysConfig::where('config_key', 'app-identity-partner-config')->first();
            } elseif ($memberUp->member_is_referrer == 'Y') {
                $identity = 'REFERRER';
                // 提成设置
                $config = SysConfig::where('config_key', 'app-identity-referrer-config')->first();
            } elseif ($memberUp->member_is_franchisee == 'Y') {
                $identity = 'FRANCHISEE';
                // 提成设置
                $config = SysConfig::where('config_key', 'app-identity-franchisee-config')->first();
            } else {
                throw new BusinessException("直属上级非会员合伙人、加盟合伙人和推荐官");
            }
            $configParams = json_decode($config->config_value_json, true);
            // 记录的JSON
            $accountListJson = [
                'line' => 'relate-consum',
                'amount' => $order->order_amount_pay,
                'identity' => $identity,
                'order_id' => $order->order_id,
                'master_member_id' => $order->join_order_member_id
            ];
            Log::info("提成参数", $accountListJson);
            // 提成
            $this->commissionToMember($inviteMemberId, $accountListJson, round($configParams['commission']['relate-consum'] * $actualPaymentAmount, 2), $accountListCategory);

            Db::commit();
            _syslog("提成", "计算提成成功");
        } catch (BusinessException $e) {
            Db::rollBack();
            Log::error("计算消费提成异常", ['msg' => $e->getMessage()]);
            _syslog("提成", "计算提成失败:" . $e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            Log::error("计算消费提成异常", ['msg' => $e->getMessage()]);
            _syslog("提成", "计算提成失败");
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/9/25 15:14
     *
     * @param $memberId
     * @param $accountListJson
     * @param $money
     * @return void
     */
    private function commissionToMember($memberId, $accountListJson, $money, $accountListCategory)
    {
        try {
            $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()
            ]);
        } catch (\Exception $e) {
            Log::error("提成入账失败", ['msg' => $e->getMessage()]);
        }
    }
}