<?php


namespace App\Http\logic\admin;


use App\Facade\TableName;
use App\Http\logic\api\BaseApiLogic;
use App\Models\Platform\MonthCard;
use Illuminate\Support\Facades\DB;

class RechargeLogic extends BaseApiLogic
{
    public function config($method)
    {

        $list = DB::connection('write')->table('agent.dbo.admin_configs as ac')
            ->leftJoin('agent.dbo.admin_users as u', 'ac.admin_id', '=', 'u.id')
            ->select('ac.*', 'u.account')
            ->where('ac.type', 'pay')
            ->where('ac.new_pay_type', $method)
            ->get();

        // 支付渠道列表
        $pay_list = DB::connection('write')->table('agent.dbo.admin_configs')
            ->where('status', 1)
            ->where('type', 'pay')
            ->pluck('name', 'id');

        // 开关状态
        $first = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'FirstChargeGiftBagStatus')
            ->first();

        // 首充
        $firstCharge = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'FirstChargeGiftBag')
            ->first();

        $poll = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'PollSwitch')
            ->first();

        return compact('list', 'pay_list', 'first', 'firstCharge', 'poll');
    }

    // 控制开关
    public function switch_control($id, $type, $admin_id)
    {
        switch ($type) {
            case 'off': // 关闭

                // 不能全部关闭，至少保留一个
                $query = DB::table('agent.dbo.admin_configs')->where('type', 'pay')->where('status', 1)->count();

                if ($query <= 1) {
                    $this->error = '至少开启一个支付渠道';
                    return false;
                }
                $res = DB::table('agent.dbo.admin_configs')->where('id', $id)->update([
                    'status' => -1,
                    'updated_at' => date('Y-m-d H:i:s'),
                    'admin_id' => $admin_id
                ]);

                $list = DB::table('agent.dbo.recharge_gear')->get();
                foreach ($list as &$value) {
                    try {
                        $gear = \GuzzleHttp\json_decode($value->gear, true);
                        foreach ($gear as &$val) {
                            if ($val['id'] == $id) {
                                $val['status'] = -1;
                            }
                        }
                        $gear = \GuzzleHttp\json_encode($gear);
                        DB::table('agent.dbo.recharge_gear')->where('id', $value->id)->update(['gear' => $gear]);
                    }catch (\Exception $e) {

                    }
                }

                break;

            case 'on':  // 开启

                $res = DB::table('agent.dbo.admin_configs')->where('id', $id)->update([
                    'status' => 1,
                    'updated_at' => date('Y-m-d H:i:s'),
                    'admin_id' => $admin_id
                ]);

                $list = DB::table('agent.dbo.recharge_gear')->get();
                foreach ($list as &$value) {
                    try {
                        $gear = \GuzzleHttp\json_decode($value->gear, true);
                        foreach ($gear as &$val) {
                            if ($val['id'] == $id) {
                                $val['status'] = 1;
                            }
                        }
                        $gear = \GuzzleHttp\json_encode($gear);
                        DB::table('agent.dbo.recharge_gear')->where('id', $value->id)->update(['gear' => $gear]);
                    }catch (\Exception $e){

                    }
                }
                break;

            default:
                $this->error = '类型错误';
                return false;
        }

        if (isset($res) && $res) {
            return true;
        } else {
            $this->error = '操作失败';
            return false;
        }
    }

    // 充值档位
    public function gear_list($first_pay_status = 0)
    {
        $where = [];
        $where[] = ['first_pay', $first_pay_status];
        $list = DB::table('agent.dbo.recharge_gear')
            ->where($where)
            ->orderBy('money')
            ->get();

        $names = DB::table('agent.dbo.admin_configs')->where('type', 'pay')->pluck('name', 'id');
        $payMethodsNames = [
            'cashapp' => 'CashApp',
            'paypal' => 'PayPal',
            'applepay' => 'ApplePay',
            'googlepay' => 'GooglePay'
        ];
        
        foreach ($list as &$value) {

            $name = [];
            if (!empty($value->gear)) {
                $gear = \GuzzleHttp\json_decode($value->gear, true);
                if (is_array($gear)) {
                    foreach ($gear as $val) {
                        // 新格式：支付方式位掩码
                        if (isset($val['name']) && isset($val['status']) && $val['status'] == 1) {
                            $name[] = $payMethodsNames[$val['name']] ?? $val['name'];
                        }
                        // 旧格式：支付渠道ID（兼容）
                        elseif (isset($val['id']) && ($val['status'] ?? 0) == 1) {
                            $name[] = isset($names[$val['id']]) ? $names[$val['id']] : '';
                        }
                    }
                }
            }

            $value->gear = implode(', ', $name);
        }


        // dd($list);

        // // 首充档位配置
        // $first_pay = DB::table('agent.dbo.recharge_gear')
        //     ->where('first_pay', 1)
        //     ->first();
        // $name = [];
        // if (!empty($first_pay->gear)) {
        //     $gear = \GuzzleHttp\json_decode($first_pay->gear, true);
        //     foreach ($gear as $val) {
        //         if ($val['status'] == 1) {
        //             $name[] = isset($names[$val['id']]) ? $names[$val['id']] : '';
        //         }
        //     }
        // }

        // $first_pay->gear = implode(',', $name);

        $first_pay = [];
        $RecomendarRecharge = [];
        $monthCard = [];


        // 推荐充值档位
        // $RecomendarRecharge = DB::table(TableName::QPAccountsDB() . 'SystemStatusInfo')
        //     ->where('StatusName', 'RecomendarRecharge')
        //     ->value('StatusValue');
        // // 周卡
        // $channels = DB::table('agent.dbo.admin_configs')->where([
        //     'type' => 'pay',
        // ])->pluck('id', 'name')->toArray();
        // $monthCard = MonthCard::query()->where('CardType', 1)->get();
        // foreach ($monthCard as $k => $v) {
        //     $monthCard[$k]->FirstReward = $v->FirstReward/100;
        //     $monthCard[$k]->DayReward = $v->DayReward/100;
        //     $cardChannels = array_filter($v->gear, function ($item) {
        //         return $item['status'] == 1;
        //     });
        //     $ids = array_column($cardChannels, 'id');
        //     $v['channels'] = array_filter($channels, function ($item) use ($ids) {
        //         return in_array($item, $ids);
        //     });
        // }

        return compact('list', 'first_pay', 'RecomendarRecharge', 'monthCard');
    }

    public function channel_switch($id, $type)
    {

        $first_pay_status = DB::table('agent.dbo.recharge_gear')->where('id', $id)->value('first_pay');
        switch ($type) {
            case 'off': // 关闭
                $query = DB::table('agent.dbo.recharge_gear')->where('status', 1)->count();
                if ($query <= 1) {
                    $this->error = '至少开启一个充值档位';
                    return false;
                }

                if ($first_pay_status == 2) {   // 引导付费 共用一个开关状态
                    $res = DB::table('agent.dbo.recharge_gear')->where('first_pay', 2)->update([
                        'status' => -1,
                    ]);
                }else{
                    $res = DB::table('agent.dbo.recharge_gear')->where('id', $id)->update([
                        'status' => -1,
                    ]);
                }

                break;

            case 'on':  // 开启

                if ($first_pay_status == 2) {   // 引导付费 共用一个开关状态
                    $res = DB::table('agent.dbo.recharge_gear')->where('first_pay', 2)->update([
                        'status' => 1,
                    ]);
                }else{
                    $res = DB::table('agent.dbo.recharge_gear')->where('id', $id)->update([
                        'status' => 1,
                    ]);
                }

                break;

            default:
                $this->error = '类型错误';
                return false;
        }

        if (isset($res) && $res) {
            return true;
        } else {
            $this->error = '操作失败';
            return false;
        }
    }

    public function add($money, $status, $config_ids, $favorable_price, $give, $pay_methods = 0)
    {
        // 构建支付方式数组
        $gearData = [];
        $payMethodsMap = [
            1 => 'cashapp',
            2 => 'paypal',
            4 => 'applepay',
            8 => 'googlepay'
        ];
        
        foreach ($payMethodsMap as $value => $name) {
            if ($pay_methods & $value) {
                $gearData[] = [
                    'name' => $name,
                    'value' => $value,
                    'status' => 1
                ];
            }
        }
        
        $add_data = [
            'money' => round($money, 2),
            'status' => $status,
            'gear' => \GuzzleHttp\json_encode($gearData),  // 存储到gear字段
            'created_at' => date('Y-m-d H:i:s'),
            'favorable_price' => round($favorable_price, 2),
            'give' => round($give, 2)
        ];

        DB::table('agent.dbo.recharge_gear')->insert($add_data);
        return true;
    }

    public function update($id)
    {
        $info = DB::table('agent.dbo.recharge_gear')->where('id', $id)->first();
        $gear = \GuzzleHttp\json_decode($info->gear, true);
        $names = DB::table('agent.dbo.admin_configs')->where('type', 'pay')->pluck('name', 'id');
        $new_arr = [];
        foreach ($gear as &$value) {

            if ($value['status'] == 1) {
                $new_arr[] = $value['id'];
            }
        }

        $info->gear = $new_arr;

        return compact('info', 'names');
    }


    public function gear_switch($id, $config_id, $type)
    {

        $query = DB::table('agent.dbo.recharge_gear')->where('id', $id)->first();

        $gear = \GuzzleHttp\json_decode($query->gear, true);
        $off = 0;
        $data = [];
        $new_arr = [];
        switch ($type) {
            case 'on':
                foreach ($gear as &$value) {
                    $data[] = $value['id'];
                    if ($value['id'] == $config_id) {
                        $value['status'] = 1;
                    }
                }

                if (!in_array($config_id, $data)) {
                    $new_arr['id'] = $config_id;
                    $new_arr['status'] = 1;
                }

                break;

            case 'off':

                foreach ($gear as &$value) {
                    $data[] = $value['id'];
                    if ($value['id'] == $config_id) {
                        $value['status'] = -1;
                    }
                    if ($value['status'] == 1) {
                        $off += 1;
                    }
                }

                if (!in_array($config_id, $data)) {
                    $new_arr['id'] = $config_id;
                    $new_arr['status'] = -1;
                }

                if ($off < 1) {
                    $this->error = '至少开启一个通道';
                    return false;
                }
                break;

            default:
                $this->error = '类型错误';
                return false;
        }
        !empty($new_arr) && $gear[] = $new_arr;

        $gear = \GuzzleHttp\json_encode($gear);
        DB::table('agent.dbo.recharge_gear')->where('id', $id)->update(['gear' => $gear]);
    }


    // 首充礼包
    public function gift()
    {
        $where = [];
        $where[] = ['first_pay', '>=', 1];
        $list = DB::table('agent.dbo.recharge_gear')
            ->where($where)
            ->orderByDesc('created_at')
            ->get();

        $names = DB::table('agent.dbo.admin_configs')->where('type', 'pay')->pluck('name', 'id');
        foreach ($list as &$value) {

            $name = [];
            if (!empty($value->gear)) {
                $gear = \GuzzleHttp\json_decode($value->gear, true);
                foreach ($gear as $val) {
                    if ($val['status'] == 1) {
                        $name[] = isset($names[$val['id']]) ? $names[$val['id']] : '';
                    }
                }
            }

            $value->gear = implode(',', $name);
        }

        // 旧首充
        // 开关状态
        $oldRechargeStatus = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'FirstChargeGiftBagStatus')
            ->first();
        // 首充
        $oldRecharge = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'FirstChargeGiftBag')
            ->first();
        $oldRechargeChannel = $names[$oldRecharge->StatusValue] ?? '';

        $pay_list = $names;
        return compact('list', 'oldRecharge', 'oldRechargeStatus','oldRechargeChannel','pay_list');
    }
}

