<?php

namespace app\event\statistics;

use app\model\DataInout;
use app\model\MemberAccountList;
use app\model\Order;
use app\model\OrderSheet;
use app\model\PayDetail;
use app\model\SysDept;
use support\exception\BusinessException;
use support\Log;

class InOutEvent
{
    /*
     * 	{"label": "标准订单收入", "value": "标准订单收入"},
        {"label": "餐饮订单收入", "value": "餐饮订单收入"},
        {"label": "购买康养城VIP套餐包收入", "value": "购买康养城VIP套餐包收入"},
        {"label": "购买会员合伙人收入", "value": "购买会员合伙人收入"},
        {"label": "购买康养推荐官收入", "value": "购买康养推荐官收入"},
        {"label": "购买组合包收入", "value": "购买组合包收入"},
        {"label": "会员充值订单收入", "value": "会员充值订单收入"},
        {"label": "挂账订单结算收入", "value": "挂账订单结算收入"},
        {"label": "购买储值卡订单收入", "value": "购买储值卡订单收入"},
        {"label": "佣金提现", "value": "佣金提现"},
        {"label": "退款", "value": "退款"}
     */

    /**
     * @Desc 收入
     * @Author Gorden
     * @Date 2024/10/12 15:23
     *
     * @param $params
     * @return void
     */
    public function dataIn($params)
    {
        try {
            $order = Order::where('order_id', $params['orderId'])->first();
            $sheets = OrderSheet::with([
                'goods' => function ($query) {
                    $query->select('goods_id', 'goods_name', 'goods_classify');
                }
            ])->where('join_sheet_order_id', $params['orderId'])
                ->get()
                ->toArray();
            if (!empty($params['pay_id'])) {
                $payDetails = PayDetail::where('pay_id', $params['pay_id'])
                    ->get()
                    ->toArray();
            } else {
                $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby)
                    ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
                    ->where('pay_status', 'SUCCESS')
                    ->get()
                    ->toArray();
            }
            $data = [
                'dept_id' => 0,
                'member_id' => $order->join_order_member_id,
                'inout_classify' => 'IN',
                'inout_category' => $params['inout_category'] ?? '标准订单',

            ];
            // 部门id
            if (!empty($order->order_config_json)) {
                $orderConfigJson = json_decode($order->order_config_json, true);
                if (!empty($orderConfigJson['dept'])) {
                    $data['dept_id'] = $orderConfigJson['dept'];
                } elseif (!empty($orderConfigJson['premises'])) {
                    $data['dept_id'] = SysDept::where('dept_name', $orderConfigJson['premises'])->value('dept_id');
                }
            }
            $inoutObjectJson = [];
            // 产品
            foreach ($sheets as $sheet) {
                $inoutObjectJson['goods'][] = [
                    'goods_id' => $sheet['goods']['goods_id'] ?? '',
                    'goods_name' => $sheet['goods']['goods_name'] ?? ''
                ];
                $data['inout_name'][] = $sheet['goods']['goods_name'] ?? '';
                if (!isset($inoutObjectJson['order'])) {
                    $inoutObjectJson['order'][$params['orderId']] = [
                        'ordertime' => date('Y-m-d H:i:s', strtotime($order->order_addtimes)),
                        'pay' => $order->order_amount_pay,
                        'classify' => $order->order_classify,
                        'discount' => $order->order_discount_json ?? json_decode($order->order_discount_json)
                    ];
                }
                $inoutObjectJson['order'][$params['orderId']]['goods'][] = [
                    'goods_id' => $sheet['goods']['goods_id'] ?? '',
                    'goods_name' => $sheet['goods']['goods_name'] ?? '',
                    'goods_sku_id' => $sheet['join_sheet_goods_sku_id'],
                    'order_sheet_num' => $sheet['order_sheet_num'],
                    'order_sheet_pay' => $sheet['order_sheet_pay']
                ];
                $inoutObjectJson['classify'][] = $sheet['goods']['goods_classify'] ?? '';
            }
            $inoutObjectJson['ordergroup'] = $order->order_groupby;
            $data['inout_object_json'] = json_encode($inoutObjectJson);
            $data['inout_name'] = implode(',', $data['inout_name']);
            if (strlen($data['inout_name']) > 100) {
                $data['inout_name'] = mb_substr($data['inout_name'], 0, 100) . '等';
            }
            $payJson = [
                'trade' => '',
                'if_union' => count($payDetails) > 1 ? 'Y' : 'N',
                'union_order_id' => count($payDetails) > 1 ? $params['orderId'] : ''
            ];
            foreach ($payDetails as $payDetail) {
                if (in_array($payDetail['pay_prepayid'], ['WXPAY', 'ALIPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY'])) {
                    $data['inout_attr'] = 'MONEY';
                } else {
                    $data['inout_attr'] = 'ACCOUNT';
                }
                $data['inout_amount'] = $payDetail['pay_amount'];
                $prepayId = explode('-', $payDetail['pay_prepayid']);
                if (count($prepayId) == 1) {
                    $data['pay_type'] = $payDetail['pay_prepayid'];
                } elseif (count($prepayId) > 1) {
                    $data['pay_type'] = $prepayId[1];
                }
                if (!empty($payDetail['pay_json_response'])) {
                    $payJsonResponse = json_decode($payDetail['pay_json_response'], true);
                    if (isset($payJsonResponse['transaction_id'])) {
                        $payJson['trade'] = $payJsonResponse['transaction_id'];
                    } elseif (isset($payJsonResponse['trade_no'])) {
                        $payJson['trade'] = $payJsonResponse['trade_no'];
                    }
                }
                $data['pay_json'] = json_encode($payJson);

                $this->dataSave($data);
            }

        } catch (\Exception $e) {
            _syslog("统计", '收支明细统计失败', ['msg' => $e->getMessage()]);
            Log::error("收支明细统计失败", ['msg' => $e->getMessage()]);
        }
    }

    public function dataOut($params)
    {
        try {
            if ($params['type'] == 'refund') {
                $data = $this->orderRefund($params);
            } elseif ($params['type'] == 'withdraw') {
                $data = $this->commissionWithdraw($params);
            } else {
                throw new BusinessException("不支持的支出类型");
            }

            $this->dataSave($data);
        } catch (BusinessException $e) {
            Log::error("统计支出失败:" . $e->getMessage(), $params);
        } catch (\Exception $e) {
            Log::error("统计支出失败:" . $e->getMessage(), $params);
        }
    }

    public function orderRefund($params)
    {
        try {
            $order = Order::where('order_id', $params['orderId'])->first();
            $sheets = OrderSheet::with([
                'goods' => function ($query) {
                    $query->select('goods_id', 'goods_name', 'goods_classify');
                }
            ])->where('join_sheet_order_id', $params['orderId'])
                ->get()
                ->toArray();
            $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)
                ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
                ->where('pay_category', 'REFUND')
                ->where('pay_status', 'SUCCESS')
                ->first();
            if (!$payDetail) {
                throw new BusinessException("支付数据异常");
            }
            $payDetail = $payDetail->toArray();

            $data = [
                'dept_id' => 0,
                'member_id' => $order->join_order_member_id,
                'inout_classify' => 'OUT',
                'inout_category' => !empty(self::$orderClassify[$order->order_classify]) ? self::$orderClassify[$order->order_classify] : '退款',

            ];
//            if (in_array($order->order_classify,['GOODS','SERVICE','CHNMED','CHNNCD'])){
//                $data['inout_category'] = self::$orderClassify[$order->order_classify];
//            }
            // 部门id
            if (!empty($order->order_config_json)) {
                $orderConfigJson = json_decode($order->order_config_json, true);
                if (!empty($orderConfigJson['dept'])) {
                    $data['dept_id'] = $orderConfigJson['dept'];
                } elseif (!empty($orderConfigJson['premises'])) {
                    $data['dept_id'] = SysDept::where('dept_name', $orderConfigJson['premises'])->value('dept_id');
                }
            }
            $inoutObjectJson = [];
            // 产品
            foreach ($sheets as $sheet) {
                $inoutObjectJson['goods'][] = [
                    'goods_id' => $sheet['goods']['goods_id'] ?? '',
                    'goods_name' => $sheet['goods']['goods_name'] ?? ''
                ];
                $data['inout_name'][] = $sheet['goods']['goods_name'] ?? '';
                if (!isset($inoutObjectJson['order'])) {
                    $inoutObjectJson['order'][$params['orderId']] = [
                        'pay' => $payDetail['pay_amount'],
                        'classify' => $order->order_classify,
                        'discount' => $order->order_discount_json ?? json_decode($order->order_discount_json)
                    ];
                }
                $inoutObjectJson['order'][$params['orderId']]['goods'][] = [
                    'goods_id' => $sheet['goods']['goods_id'] ?? '',
                    'goods_name' => $sheet['goods']['goods_name'] ?? '',
                    'order_sheet_num' => $sheet['order_sheet_amount'],
                    'order_sheet_pay' => $sheet['order_sheet_pay']
                ];
                $inoutObjectJson['classify'][] = $sheet['goods']['goods_classify'] ?? '';
            }
            $inoutObjectJson['ordergroup'] = $order->order_groupby;
            $data['inout_object_json'] = json_encode($inoutObjectJson);
            $data['inout_name'] = implode(',', $data['inout_name']);

            $payJson = [
                'trade' => '',
                'if_union' => 'N',
                'union_order_id' => '',
                'return' => 'Y'
            ];
            if (in_array($payDetail['pay_prepayid'], ['WXPAY', 'ALIPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY'])) {
                $data['inout_attr'] = 'MONEY';
            } else {
                $data['inout_attr'] = 'ACCOUNT';
            }
            $data['inout_amount'] = $payDetail['pay_amount'];
            $prepayId = explode('-', $payDetail['pay_prepayid']);
            if (count($prepayId) == 1) {
                $data['pay_type'] = $payDetail['pay_prepayid'];
            } elseif (count($prepayId) > 1) {
                $data['pay_type'] = $prepayId[1];
            }
            if (!empty($payDetail['pay_json_response'])) {
                $payJsonResponse = json_decode($payDetail['pay_json_response'], true);
                if (isset($payJsonResponse['transaction_id'])) {
                    $payJson['trade'] = $payJsonResponse['transaction_id'];
                } elseif (isset($payJsonResponse['trade_no'])) {
                    $payJson['trade'] = $payJsonResponse['trade_no'];
                }
            }
            $data['pay_json'] = json_encode($payJson);

            return $data;
        } catch (BusinessException $e) {
            Log::error("记录退款收支失败", ['msg' => $e->getMessage(), 'params' => $params]);
            throw new BusinessException($e->getMessage());
        } catch (\Exception $e) {
            Log::error("记录退款收支失败", ['msg' => $e->getMessage(), 'params' => $params]);
            throw new BusinessException("退款支出处理失败");
        }
    }

    public function commissionWithdraw($params)
    {
        try {
            $memberAccountList = MemberAccountList::where('member_account_list_id', $params['account_list_id'])->first();
            $data = [
                'dept_id' => 0,
                'member_id' => $memberAccountList->join_member_account_list_member_id,
                'inout_object_json' => $memberAccountList->member_account_list_json,
                'inout_attr' => 'MONEY',
                'inout_classify' => 'OUT',
                'inout_category' => '提现',
                'inout_name' => '提现',
                'inout_amount' => $memberAccountList->member_account_list_amount,
                'pay_type' => 'UNIONPAY',
                'pay_json' => json_encode([
                    'trade' => '',
                    'if_union' => 'N',
                    'union_order_id' => ''
                ]),
            ];

            return $data;
        } catch (\Exception $e) {
            throw new BusinessException("提现支出处理失败");
        }
    }

    public function dataSave($data)
    {
        DataInout::insert([
            'join_data_inout_dept_id' => $data['dept_id'],
            'join_data_inout_member_id' => $data['member_id'],
            'join_data_inout_object_json' => $data['inout_object_json'],
            'data_inout_is_valid' => 'Y',
            'data_inout_valid_date' => date('Y-m-d'),
            'data_inout_valid_time' => date('Y-m-d H:i:s'),
            'data_inout_status' => 'VALID',
            'data_inout_attr' => $data['inout_attr'],
            'data_inout_classify' => $data['inout_classify'],
            'data_inout_category' => $data['inout_category'],
            'data_inout_name' => $data['inout_name'],
            'data_inout_amount' => $data['inout_amount'],
            'data_inout_count' => 0,
            'data_inout_json' => '[]',
            'data_inout_pay_type' => $data['pay_type'] ?? '',
            'data_inout_pay_json' => $data['pay_json'],
            'data_inout_process_json' => '[]',
            'data_inout_occurtime' => date('Y-m-d H:i:s'),
            'data_inout_remark' => '',
            'data_inout_extend_json' => '[]',
            'data_inout_addtimes' => time()
        ]);
    }

    public static $orderClassify = [
        'GOODS' => '标准订单',
        'SERVICE' => '标准订单',
        'CHNMED' => '标准订单',
        'CHNNCD' => '标准订单',
        'PACKAGE' => '套包订单',
        'RECHARGE' => '充值订单',
        'DISHES' => '餐饮订单',
        'VIP' => '康养城订单',
        'PARTNER' => '会员合伙人订单',
        'REFERRER' => '康养推荐官订单',
        'COMBINE' => '新客专享订单'
    ];
}