<?php

namespace app\api\controller;

use app\admin\validate\user\UserValidate;
use app\api\logic\order\OrderLogic;
use app\api\logic\user\UserLogic;
use app\common\enum\OrderEnum;
use app\common\enum\PayEnum;
use app\common\enum\user\UserTerminalEnum;
use app\common\enum\YesNoEnum;
use app\common\logic\PayNotifyLogic;
use app\common\logic\store_order\StoreOrderLogic;
use app\common\logic\StoreFinanceFlowLogic;
use app\common\model\finance\CapitalFlow;
use app\common\model\financial_transfers\FinancialTransfers;
use app\common\model\order\Cart;
use app\common\model\store_branch_product\StoreBranchProduct;
use app\common\model\store_cash_finance_flow\StoreCashFinanceFlow;
use app\common\model\store_category\StoreCategory;
use app\common\model\store_finance_flow\StoreFinanceFlow;
use app\common\model\store_order\StoreOrder;
use app\common\model\store_order_cart_info\StoreOrderCartInfo;
use app\common\model\store_product\StoreProduct;
use app\common\model\store_product_log\StoreProductLog;
use app\common\model\system_store\SystemStore;
use app\common\model\user\User;
use app\common\model\user\UserAddress;
use app\common\model\user\UserRecharge;
use app\common\model\user_ship\UserShip;
use app\common\model\user_sign\UserSign;
use app\common\model\vip_flow\VipFlow;
use app\common\service\pay\PayService;
use app\common\service\SmsService;
use app\common\service\wechat\WeChatMnpService;
use app\MyBusinessException;
use app\store\lists\store_order\StoreOrderLists;
use app\store\logic\WorkbenchLogic;
use app\store\validate\store_order\StoreOrderValidate;
use Illuminate\Support\Facades\Log;
use Overtrue\EasySms\EasySms;
use Picqer\Barcode\BarcodeGeneratorJPG;
use Picqer\Barcode\BarcodeGeneratorPNG;
use support\Cache;

use think\db\Raw;
use think\Exception;
use think\facade\Db;

class LiuController extends BaseApiController
{
    public $notNeedLogin = ['index', 'app_update', 'test', 'show'];

    public static $total;


    public function dealCapital($startTime,$endTime,$pay_type)
    {
        $vipFrozen = VipFlow::where('create_time', '>=', $startTime)
            ->where('create_time', '<', $endTime)
            ->where('pay_type',$pay_type)->select()->toArray();
        if($pay_type == 18){
            $category_title = 'system_purchase_add';
            $title ='系统增加采购款';
            $mark ='系统增加采购款';
            $filed = 'purchase_funds';
        }else{
            $category_title = 'system_balance_add';
            $title ='系统增加余额';
            $mark ='系统反余额冻结';
            $filed = 'now_money';
        }

        $newArr = [];
        foreach ($vipFrozen as $k =>$value){
            $user_funds = User::where('id',$value['user_id'])->value($filed);
            $newArr[$k]['uid'] = $value['user_id'];
            $newArr[$k]['category'] = $category_title;
            $newArr[$k]['link_type'] = 'order';
            $newArr[$k]['link_id'] = $value['order_id'];
            $newArr[$k]['amount'] = $value['number'];
            $newArr[$k]['before_balance'] =$user_funds;
            $newArr[$k]['balance'] = bcadd($user_funds, $value['number'], 2);
            $newArr[$k]['create_time'] = date('Y-m-d H:i:s');
            $newArr[$k]['type'] = 'in';
            $newArr[$k]['title'] = $title."{$value['number']}元";
            $newArr[$k]['mark'] = $mark;
        }
        (new CapitalFlow())->saveAll($newArr);

    }


    public function test()
    {


        $page_no = (int)$this->request->get('page_no', 1);
        $page_size = (int)$this->request->get('page_size', 15);
        $params = $this->request->get();
        $params['page_no'] = $page_no > 0 ? $page_no : 1;
        $params['page_size'] = $page_size > 0 ? $page_size : 15;
        $res = UserLogic::dealDetails($params,20);
        $res['page_no'] = $params['page_no'];
        $res['page_size'] = $params['page_size'];
        return $this->success('ok', $res);






//        $res = (new StoreOrderLogic)->refund('PF1719023023405552',180,180);
//        d($res);
        /**
         * 加入确认表
         */
        /* $startTime = 1717171200; // 开始时间
         $endTime = 1719676800;   // 结束时间
         //对平台来说
         $data = StoreFinanceFlow::
         whereBetween('create_time', [$startTime, $endTime])
             ->field('
             CONCAT("第", LPAD(YEAR(FROM_UNIXTIME(create_time, "%Y-%m-%d")), 4, "0"), "-", LPAD(WEEK(FROM_UNIXTIME(create_time, "%Y-%m-%d"), 3), 2, "0"), "周(", LPAD(MONTH(FROM_UNIXTIME(create_time, "%Y-%m-%d")), 2, "0"), "月)") as remark_time,
                 SUM(CASE WHEN financial_pm = 1 THEN number ELSE 0 END) as income,
                 SUM(CASE WHEN financial_pm = 0 THEN number ELSE 0 END) as money,
                 store_id
             ')
             ->where('financial_pm', 0)
             ->group('remark_time,store_id')
             ->order('remark_time', 'desc')
             ->select()
 //            ->each(function ($item) {
 //                $item['name'] = '周账单';
 //                $item['enter']=bcdiv($item['income'],$item['expenditure'],2);
 //                return $item;
 //            })
             ->toArray();
 //        foreach ($data as &$v) {
 //            $v['admin_id'] =$this->adminId;
 //        }

         (new FinancialTransfers())->saveAll($data);


         d($data);*/


        //反钱
        //读取前3天的值 按照用户id和类型分下 加到对应的钱
        $startTime = strtotime(date('Y-m-d', strtotime('-3 days')));
        $endTime = strtotime(date('Y-m-d'));

        // 使用模型查询
        $result = VipFlow::where('create_time', '>=', $startTime)
            ->where('create_time', '<', $endTime)
            ->group('user_id, pay_type')
            ->field('user_id, pay_type, COUNT(*) as transaction_count, SUM(number) as total_amount')
            ->select()->toArray();

        // 遍历查询结果并分类 现金不进入反的逻辑
        //3余额     18采购款        7微信小程序  9微信条码  13 支付宝条码支付
        $Balance = [];
        $Procurement = [];
        $WechatMiniPay = [];
        $WechatBarcodePay = [];
        $AliBarcodePay = [];
        foreach ($result as $row) {
            $payType = $row['pay_type'];
            $userId = $row['user_id'];
            $totalAmount = $row['total_amount'];
            switch ($payType) {
                case 3:
                    $user_now_money =User::where(
                        [
                            'id'=>$userId
                        ]
                    )->withTrashed()->value('now_money');
                    $Balance[] = [
                        'id' => $userId,
                        'now_money' => bcadd($user_now_money,$totalAmount,2),
                    ];
                    break;
                case 7:
                    $WechatMiniPay[] = [
                        'id' => $userId,
                        'total_amount' => $totalAmount,
                    ];
                    break;
                case 9:
                    $WechatBarcodePay[] = [
                        'id' => $userId,
                        'total_amount' => $totalAmount,
                    ];
                    break;
                case 13:
                    $AliBarcodePay[] = [
                        'id' => $userId,
                        'total_amount' => $totalAmount,
                    ];
                    break;
                case 18:
                    $purchase_funds_money =User::where(
                        [
                            'id'=>$userId
                        ]
                    )->withTrashed()->value('purchase_funds');
                    $Procurement[] = [
                        'id' => $userId,
//                        '111' => $totalAmount,
                        'purchase_funds' => bcadd($purchase_funds_money,$totalAmount,2),
                    ];
                    break;
            }
//            // 如果分类数组中还没有这个 pay_type,初始化一个空数组
//            if (!isset($classifiedResult[$payType])) {
//                $classifiedResult[$payType] = [];
//            }
//
//            // 将用户信息添加到对应的 pay_type 分类中
//            $classifiedResult[$payType][] = [
//                'uid' => $userId,
//                'total_amount' => $totalAmount,
//            ];
        }

        //入记录表的话查询后便利入  3余额  18采购款
//        if($Balance){
            //记录
//            (new User())->saveAll($Balance);
//        $this->dealCapital($startTime,$endTime,3);
//        }
//        if($Procurement){
//            (new User())->saveAll($Procurement);
//            $this->dealCapital($startTime,$endTime,18);
//        }
        //7微信小程序  9微信条码  13 支付宝条码支付
        d($Balance,$Procurement,$WechatMiniPay,$WechatBarcodePay,$AliBarcodePay);




        $result = array_reduce($result, function ($carry, $item) {
            $user_id = $item['user_id'];
            $pay_type = $item['pay_type'];
            $total_amount = $item['total_amount'];

            if (!isset($carry[$user_id])) {
                $carry[$user_id] = [];
            }

            if (!isset($carry[$user_id][$pay_type])) {
                $carry[$user_id][$pay_type] = [
                    'uid' => $user_id,
                    'transaction_count' => 0,
                    'total_amount' => 0
                ];
            }

            $carry[$user_id][$pay_type]['transaction_count'] += $item['transaction_count'];
            $carry[$user_id][$pay_type]['total_amount'] += $item['total_amount'];

            return $carry;
        }, []);
        d($result);

        //3余额   17现金   18采购款  7微信小程序  9微信条码  13 支付宝条码支付
        foreach ($result as $value) {
            switch ($value['pay_type']) {

                case 3:
                    echo 2;
                    break;

                case 7:
                case 9:
                    echo 1;
                    break;

                case 13:
                    echo 13;
                    break;

                case 17:
                    echo 17;
                    break;

                case 18:
                    echo 18;
                    break;
            }
            d($value);
        }

        d($result);


        $params = (new \app\api\validate\UserValidate())->post()->goCheck('setPayPassword');

        //匹配验证码正确

        if ($params['repassword'] !== $params['password'])
            return $this->fail('两次密码不一致');

        $password = payPassword($params['password']);

        User::where('id', $params['id'])->update(['pay_password' => $password]);


        d($params);


        d(password_hash(123456, PASSWORD_BCRYPT));
//        $updateData = [];
//        $goods_list = StoreOrderCartInfo::where('oid',473)->select()->toArray();
//
//        foreach ($goods_list as  $v) {
//            $StoreBranchProduct =StoreBranchProduct::where(
//                [
//                    'store_id'=>$v['store_id'],
//                    'product_id'=>$v['product_id'],
//                ]
//            )->withTrashed()->find();
//            $updateData[] = [
//                'id' => $StoreBranchProduct['id'],
//                'stock' => $StoreBranchProduct['stock']-$v['cart_num'],
//                'sales' => ['inc', $v['cart_num']]
//            ];
//
//        }
//
//        (new StoreBranchProduct())->saveAll($updateData);
//
//
//        d($updateData);


        $dateRange = $this->request->get('date');
        // 拆分日期范围
        if ($dateRange) {
            list($startDate, $endDate) = explode('-', $dateRange);
            $startTime = str_replace('/', '-', $startDate);
            $endTime = str_replace('/', '-', $endDate);
        } else {
            $startTime = '';
        }

        if (empty($startTime)) {
            $startTime = strtotime(date('Y-m-d'));
            $endTime = $startTime + 86400;
        }
        $where = [
            ['create_time', 'between', [$startTime, $endTime]],
            ['store_id', '=', 23]
        ];

        $workbench = WorkbenchLogic::get_product_ranking($where);
        return $this->data($workbench);


        $order = StoreOrder::where('order_id', 'PF1718873590826700')->findOrEmpty();
//
//        $store_id = $order['store_id'];
//        $cart_id = $order['cart_id'];
//        $uid = $order['uid'];
//        if($uid && $cart_id && $store_id){
//            $cart_id =  explode(',',$cart_id);
//            $productLog = StoreProductLog::where([
//                'uid'=>$uid
//            ])->whereIn('cart_id',$cart_id)
//                ->select()->toArray();
//
//            foreach ($productLog as &$value){
//                $value['pay_uid'] = $uid;
//                $value['oid'] = $order['id'];
//                $cart_info = StoreOrderCartInfo::where([
//                    'uid'=>$uid,'old_cart_id'=>$value['cart_id'],'store_id'=>$store_id
//                ])->find();
//                $value['order_num'] = $cart_info['cart_num']??1;
//                $value['pay_num'] = $cart_info['cart_num']??1;
//                $value['pay_price'] = $cart_info['price']??0;
//                $value['cost_price'] = $cart_info['cart_info']['cost']??0;
//                $value['update_time'] = time();
//                unset($value['create_time'],$value['delete_time']);
//            }
//
//            (new StoreProductLog())->saveAll($productLog);
//        }


//        foreach ($cart_id as &$value){
//
//        }


        d($store_id, $cart_id, $uid);


        $cart = Cart::create([
            'uid' => 777,
            'type' => $params['type'] ?? '',
            'product_id' => 12,
            'store_id' => 2 ?? 0,
            'staff_id' => $params['staff_id'] ?? 0,
            'product_attr_unique' => '',
            'cart_num' => 1,
            'is_new' => 1 ?? 0,
        ]);

        d($cart, $cart['id']);


        //处理类型变更
        $order = StoreOrder::where('pay_type', 3)->field('id')->select()->toArray();
        $new = array_column($order, 'id');
//        d($new,$order);

        $dd = CapitalFlow::where('category', 'user_order_pay')
            ->whereIn('link_id', $new)
            ->select()->toArray();

        foreach ($dd as $value) {
            CapitalFlow::where('id', $value['id'])->update(['category' => 'user_order_balance_pay']);
        }


        d($dd);


        $categories = ['user_balance_recharge', 'user_order_purchase_pay'];
        $query = CapitalFlow::where('uid', 17)
            ->whereIn('category', $categories);
        $count = $query->count();
        $data = $query
            ->page(1, 15)
            ->select()->toArray();

        foreach ($data as &$value) {
            if ($value['category'] == 'user_order_purchase_pay') {
                $value['order_sn'] = StoreOrder::where('id', $value['link_id'])->value('order_id');
            } elseif ($value['category'] == 'user_balance_recharge') {
                $value['order_sn'] = UserRecharge::where('id', $value['link_id'])->value('order_id');
            }
        }


        d($data);


        //
        (new UserValidate())->post()->goCheck('fund');
        $page_no = (int)$this->request->post('page_no', 1);
        $page_size = (int)$this->request->post('page_size', 15);
        $params = $this->request->post();
        $params['page_no'] = $page_no > 0 ? $page_no : 1;
        $params['page_size'] = $page_size > 0 ? $page_size : 15;

        switch ($params['type']) {
            case 1:
                //采购款明细
                $query = CapitalFlow::where(['uid' => $params['id']]);
                $count = $query->count();
                $data = $query
                    ->page($params['page_no'], $params['page_size'])
                    ->select()->toArray();
                break;
            case 2:
                //余额明细

                $query = StoreFinanceFlow::with(['store'])
                    ->where([
                        'other_uid' => $params['id'], 'financial_type' => OrderEnum::VIP_ORDER_OBTAINS,
                        'financial_pm' => YesNoEnum::YES
                    ]);
                $count = $query->count();
                $data = $query
                    ->page($params['page_no'], $params['page_size'])
                    ->select()->toArray();

                break;
            case 3:
                //礼品券明细
                $query = UserSign::where(['uid' => $params['id']]);
                $count = $query->count();
                $data = $query
                    ->page($params['page_no'], $params['page_size'])
                    ->select()->toArray();
                break;
            case 4:
                //返还金明细 -todo back
                $query = VipFlow::with('store')->where(['user_id' => $params['id']]);
                $count = $query->count();
                $data = $query
                    ->page($params['page_no'], $params['page_size'])
                    ->select()->toArray();
                break;
            default:
                $data = [];
                $count = 0;
        }
//        d($data,$count);

        $res = [
            'list' => $data,
            'count' => $count
        ];

//        d($params);

        $res['page_no'] = $params['page_no'];
        $res['page_size'] = $params['page_size'];
        return $this->success('ok', $res);

        $field = "id,nickname,real_name,sex,avatar,account,mobile,channel,create_time,purchase_funds,user_ship,
                   label_id,integral";
        $lists = User::
        with(['user_ship', 'user_label'])
            ->field($field)
            ->page(1, 50)
            ->order('id desc')
            ->select()->each(function ($data) {
                $data['sex_text'] = $data->sex_text;
            })->toArray();
        foreach ($lists as &$item) {
            //返还金、采购款明细、余额明细、礼品券明细、返还金明细
            $item['channel'] = UserTerminalEnum::getTermInalDesc($item['channel']);
            $item['user_address'] = UserAddress::where([
                'uid' => $item['id'], 'is_default' => YesNoEnum::YES
            ])->value('detail');
            if ($item['vip_name'] == null) {
                $item['vip_name'] = '普通会员';
            }
            if ($item['label_name'] == null) {
                $item['label_name'] = '无';
            }
            $item['return_money'] = VipFlow::
            where(['user_id' => $item['id'], 'status' => 0])
                ->sum('number') ?? 0;


        }

        d($lists);


        $params = [
            'id' => 460
        ];

        $order = StoreOrder::with(['user', 'staff', 'product' => function ($query) {
            $query->field(['id', 'oid', 'product_id', 'cart_info']);
        }])->where($params)->find();
        if (empty($order)) {
            throw new \Exception('订单不存在');
        }
        $order['pay_time'] = $order['pay_time'] > 0 ? date('Y-m-d H:i:s', $order['pay_time']) : '';
        $order['status_name'] = OrderEnum::getOrderType($order['status']) ?? '';
        $order['refund_status_name'] = OrderEnum::refundStatus($order['refund_status']) ?? '';
        $order['refund_type_name'] = OrderEnum::refundType($order['refund_type']) ?? '';
        $order['pay_type_name'] = PayEnum::getPaySceneDesc($order['pay_type']) ?? '';

        $detail = StoreOrderCartInfo::where('oid', $order['id'])->find()->toArray();
        $vip = 0;
        if (isset($detail['cart_info']['vip']) && $detail['cart_info']['vip'] == 1) {
            $vip = 1;
        }
        $order['vip'] = $vip;
        $a = $order->toArray();

        d($a);


        $detail = StoreOrderCartInfo::where('oid', 460)->find()->toArray();
        $vip = 0;
        if (isset($detail['cart_info']['vip']) && $detail['cart_info']['vip'] == 1) {
            $vip = 1;
        }


        d($detail, $vip);


        PayNotifyLogic::cash_pay('PF1718775365804124');
        d(222);


        $params = [
            'verify_code' => '4-00347',
            'store_id' => 5,
            'staff_id' => 2,
        ];

        $res = OrderLogic::writeOff($params);
        d($res);


        return $this->dataLists(new StoreOrderLists());


        $order = StoreOrder::where('id', 428)->find();


        if ($order['spread_uid'] > 0) {
            $oldUser = User::where('id', $order['spread_uid'])->field('purchase_funds,user_ship')->find();
            if ($oldUser && $oldUser['user_ship'] == 1) {
                if ($oldUser['purchase_funds'] < $order['pay_price']) {
                    $order['pay_price'] = $oldUser['purchase_funds'];
                }
            }
        }
        d($order['pay_price']);


        PayNotifyLogic::afterPay($order);

        $order_id = (int)$this->request->get('order_id');
        $lat = $this->request->get('lat', '');
        $lng = $this->request->get('long', '');
        $where = [
            'id' => $order_id,
            'uid' => $this->userId,
        ];
        $url = 'https://' . $this->request->host(true);
        $parm = [
            'lat' => $lat,
            'long' => $lng
        ];
        $order = OrderLogic::detail($where, $url, $parm);
        if ($order) {
            return $this->data($order);
        } else {
            return $this->fail('订单不存在');
        }


        $order = StoreOrder::where('id', 392)->find();
        $vipFrozenAmount = 0;
        if ($order['uid'] > 0) {
            // 结算金额 要支付的钱减去冻结得钱去走后面得逻辑  发得兑换券也要去减去
            $vipFrozenAmount = self::dealFrozenPrice($order['id']);
            $order['pay_price'] = bcsub($order['pay_price'], $vipFrozenAmount, 2);
            $user_number = bcmul($order['pay_price'], '0.10', 2);
            $sing = [
                'uid' => $order['uid'],
                'order_id' => $order['order_id'],
                'title' => '购买商品获得兑换券',
                'store_id' => $order['store_id'],
                'number' => $user_number,
            ];
//            d($sing);
//            $user_sing->save($sing);
//            User::where('id', $order['uid'])->inc('integral', $user_number)->update();
        }

        d($vipFrozenAmount, $order['pay_price'], $sing);


        d($order);
        if ($order['uid'] > 0) {
            // 结算金额 要支付的钱减去冻结得钱去走后面得逻辑  发得兑换券也要去减去
            $vipFrozenAmount = self::dealFrozenPrice($order['id']);
            $order['pay_price'] = bcsub($order['pay_price'], $vipFrozenAmount, 2);
            //用户下单该用户等级为1得时候才处理冻结金额
            $user = User::where('id', $order['uid'])->find();
            if ($user['user_ship'] == 1) {
                self::dealVipAmount($order, $order['pay_type']);
            }
            $user_number = bcmul($order['pay_price'], '0.10', 2);
            $sing = [
                'uid' => $order['uid'],
                'order_id' => $order['order_id'],
                'title' => '购买商品获得兑换券',
                'store_id' => $order['store_id'],
                'number' => $user_number,
            ];
            $user_sing->save($sing);
            User::where('id', $order['uid'])->inc('integral', $user_number)->update();
        }


        // 使用聚合函数直接计算总和
//        $total_vip = StoreOrderCartInfo::where('oid', 334)
//            ->sum(DB::raw('cart_info->>"$.vip_frozen_price"'));

//        $total_vip = StoreOrderCartInfo::where('oid', 334)
//            ->sum(DB::raw('json_extract(cart_info, "$.vip_frozen_price")'));

        $total_vip = StoreOrderCartInfo::where('oid', 334)
            ->field('cart_info->vip_frozen_price as vip_frozen_price')
//            ->find()
            ->pluck('vip_frozen_price')
            ->sum();

        d($total_vip);

        d($total_vip);


        // 假设 cart_info 是一个 JSON 字段
        $detail = StoreOrderCartInfo::where('oid', $order['id'])
            ->select('cart_info->vip_frozen_price as vip_frozen_price')
            ->get()
            ->pluck('vip_frozen_price')
            ->sum();


        $redis = local_redis(1);

        $luaScript = <<<LUA
local product_key = KEYS[1]
local quantity = tonumber(ARGV[1])

local stock = tonumber(redis.call('get', product_key))

if stock and stock >= quantity then
    redis.call('decrby', product_key, quantity)
    return 1  -- 成功
else
    return 0  -- 失败
end
LUA;
        $productKey = 'kk';
        $quantity = 1;  // 假设每次抢购一个商品

        $result = $redis->eval($luaScript, [$productKey, $quantity], 1);

        if ($result == 1) {
            d("抢购成功!");
        } else {
            d("抢购失败,库存不足。");
        }


// Lua脚本,原子操作增加值
        $luaScript = <<<LUA
local val = redis.call('incr', KEYS[1])
return val
LUA;

// 需要执行Lua脚本的key
        $key = 'my_key';

// 参数:Lua脚本,键的数量,键
        $numKeys = 1;
        $args = [$key];

// 修正参数顺序
        $result = $redis->eval($luaScript, $args, $numKeys);


        d("Incremented value for '{$key}': {$result}");


        $redis->set('kk', 111);
        d(1);

        $cost_all = CapitalFlow::
        where(['category' => 'user_order_balance_pay'])
            ->sum('amount');


        //查询数据
//        $dd =Db::name('store_cash_finance_flow')

        $startTimeDefault = date('Y-m-d', time());
        $endTimeDefault = date('Y-m-d', strtotime($startTimeDefault) + 86400);

        $data = StoreCashFinanceFlow::
        where(['store_id' => 5])->order('id', 'desc')
//              ->whereBetweenTime('create_time',$startTimeDefault,$endTimeDefault)
            ->whereDay('create_time')
            ->sum('receivable');
        d($data);

//            ->select()->toArray();
//        $sum = array_sum(array_column($data, 'receivable'));
//        d($sum);
        $cash_today = StoreCashFinanceFlow::where('store_id', 5)
            ->whereDay('create_time')
            ->where('status', YesNoEnum::YES)
            ->fetchSql()
            ->sum('receipts');
        d($cash_today);


        d(StoreFinanceFlow::
        where(['other_uid' => 17, 'type' => 0, 'status' => 0])
            ->sum('number'));
        $user = User::where('id', 15)->find()->toArray();
        $data = OrderLogic::cartIdByOrderInfo([1], 0, $user, ['store_id' => 2]);
        d($data);


        $data = StoreBranchProduct::field('id,product_id,cost,purchase')->withTrashed()->select()->toArray();

        foreach ($data as $value) {
            $one = StoreProduct::where('id', $value['product_id'])->field('cost,purchase')->withTrashed()
                ->find()->toArray();

            StoreBranchProduct::where('id', $value['id'])
                ->update([
                    'cost' => $one['cost'],
                    'purchase' => $one['purchase'],
                ]);
        }


        d($data);


        $template = getenv('SMS_TEMPLATE');

        $check = (new SmsService())->client(18715753257, $template, 9527);


        d($check);


        $cartId = (array)$this->request->post('cart_id', []);
        if (empty($cartId)) {
            return $this->fail('缺失购物车数据');
        }
        $uid = Cart::where('id', $cartId[0])->value('uid');
        d($uid);


        $params = (new StoreOrderValidate())->post()->goCheck('check');
        $res = (new StoreOrderLogic())->dealSendSms($params);
        if ($res) {
            return $this->success('发送成功', [], 1, 1);
        } else {
            return $this->fail('发送失败');
        }


        $template = getenv('SMS_TEMPLATE');
        d($template);

        $params = $this->request->post();
        $remark = '5_smsPay1';
        $code = Cache::get($remark);

        if ($code && isset($params['code']) && $code !== $params['code']) {
            throw new Exception('验证码错误');
        }


        d($code);


        //发短信
        $phone = 18715753257;
        $code = generateRandomCode();

        Cache::set($remark, $code, 5 * 60);
        d($code);

        $config = [
            // HTTP 请求的超时时间(秒)
            'timeout' => 5.0,
            // 默认发送配置
            'default' => [
                // 网关调用策略,默认:顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
//                    'file' => '/tmp/easy-sms.log',
                    'file' => runtime_path() . '/logs/alipay.log',
                ],
                'aliyun' => [
                    'access_key_id' => 'LTAI5t7mhH3ij2cNWs1zhPmv',
                    'access_key_secret' => 'gqo2wMpvi8h5bDBmCpMje6BaiXvcPu',
                    'sign_name' => '里海科技',
                ],
            ],
        ];


        try {
            $easySms = new EasySms($config);
            $res = $easySms->send($phone, [
                'content' => '您的验证码为:' . $code,
                'template' => 'SMS_263810014',
                'data' => [
                    'code' => $code
                ],
            ]);

            if ($res && $res['aliyun']['status'] == 'success') {
                return true;
            }

        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            throw new \Exception(json_encode($exception->getExceptions()));
//            return  false;
        }


        d($res);


        $user = User::where('id', \request()->userId)->find();


//        $wechat = new PayService(1);
//        $order = [
//            'out_trade_no' => time().'',
//            'description' => 'subject-测试',
//            'amount' => [
//                'total' => 1,
//            ],
//        ];
//
//        $res = $wechat->wechat->scan($order);


        $startTime = 1714492800; // 开始时间
        $endTime = 1717171199;   // 结束时间
        //对平台来说
        $data = StoreFinanceFlow::
        whereBetween('create_time', [$startTime, $endTime])
            ->field('
            CONCAT("第", LPAD(YEAR(FROM_UNIXTIME(create_time, "%Y-%m-%d")), 4, "0"), "-", LPAD(WEEK(FROM_UNIXTIME(create_time, "%Y-%m-%d"), 3), 2, "0"), "周(", LPAD(MONTH(FROM_UNIXTIME(create_time, "%Y-%m-%d")), 2, "0"), "月)") as remark_time,
                SUM(CASE WHEN financial_pm = 1 THEN number ELSE 0 END) as income,
                SUM(CASE WHEN financial_pm = 0 THEN number ELSE 0 END) as money,
                store_id
            ')
            ->where('financial_pm', 0)
            ->group('remark_time,store_id')
            ->order('remark_time', 'desc')
            ->select()
//            ->each(function ($item) {
//                $item['name'] = '周账单';
//                $item['enter']=bcdiv($item['income'],$item['expenditure'],2);
//                return $item;
//            })
            ->toArray();

//        foreach ($data as &$v) {
//            $v['admin_id'] =$this->adminId;
//        }

        (new FinancialTransfers())->saveAll($data);


        d($data);


        $data = SystemStore::where('store_money', '>', 0)
            ->field('id store_id,name,store_money money')
            ->select()->toArray();


        $now = new \DateTime();
        $lastMonth = $now->modify('first day of last month');
        foreach ($data as &$v) {
            $v['remark_time'] = $lastMonth->format('Y-m');
        }

        (new FinancialTransfers())->saveAll($data);


        d($data);


        return StoreFinanceFlow::whereBetweenTime('create_time', ['1714492800', '1717171199'])
            ->field('
            CONCAT("第", LPAD(YEAR(FROM_UNIXTIME(create_time, "%Y-%m-%d")), 4, "0"), "-", LPAD(WEEK(FROM_UNIXTIME(create_time, "%Y-%m-%d"), 3), 2, "0"), "周(", LPAD(MONTH(FROM_UNIXTIME(create_time, "%Y-%m-%d")), 2, "0"), "月)") as date,
                SUM(CASE WHEN financial_pm = 1 THEN number ELSE 0 END) as income,
                SUM(CASE WHEN financial_pm = 0 THEN number ELSE 0 END) as expenditure,store_id
            ')
//            ->limit($this->limitOffset, $this->limitLength)
            ->where('financial_pm', 0)
            ->group('date,store_id')
            ->order('date', 'desc')
            ->select()->each(function ($item) {
                $item['name'] = '周账单';
//                $item['enter']=bcdiv($item['income'],$item['expenditure'],2);
                return $item;
            })
            ->toArray();


        $wechat = new PayService(1);
        $order = [
            'out_trade_no' => 'PF1717729550406928',
            'out_refund_no' => time(),
            'amount' => [
                'refund' => 1,
                'total' => 1,
                'currency' => 'CNY',
            ],
            // '_action' => 'jsapi', // jsapi 退款,默认
            // '_action' => 'app', // app 退款
            // '_action' => 'combine', // 合单退款
            // '_action' => 'h5', // h5 退款
            // '_action' => 'miniapp', // 小程序退款
            // '_action' => 'native', // native 退款

        ];

        $res = $wechat->wechat->transfer($order);


        //生成条形码
        $generator = new BarcodeGeneratorPNG();
        $barcode = $generator->getBarcode('9-11476', $generator::TYPE_CODE_128);
// 指定保存路径
//        $savePath = 'qr/barcode.png';
        $savePath = 'public/image/barcode/barcode2.png';
// 保存条形码到文件
        file_put_contents($savePath, $barcode);

//        echo '<img src="data:image/png;base64,' . base64_encode($generator->getBarcode('081231723897', $generator::TYPE_CODE_128)) . '">';
        d(111);


        $user = new StoreBranchProduct();
        $list = [
            [
                'id' => 14,
                'stock' => ['dec', 2],
                'sales' => ['inc', 2]
//                'stock' => 1017,
            ],
            [
                'id' => 15,
                'stock' => ['dec', 1],
                'sales' => ['inc', 1]
//                'stock' => 10,
            ]
        ];
//
//            $updateData[] = [
//                'id' => 14,
////                'stock' => ['dec', $v['cart_num']]
//                'stock' => 10186
//            ];


        $user->withTrashed()->saveAll($list);

        d(1);


        $code = '8-1717845671';
        $verify_code = createCode($code);

        d($verify_code);
        $orderPickupCode = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

        d($orderPickupCode);
        $order_id = getNewOrderId('PF');


        d($order_id);


        /*$order['pay_price'] = 0.01;
        $order['store_id'] = 2;
        $order['profit'] = "0.00";
        $fees = bcdiv(bcmul($order['pay_price'], '0.02', 2), 1, 2);



        $frozen = bcsub($order['profit'] , $fees, 2);


        $money_limt = SystemStore::where('id', $order['store_id'])->field('paid_deposit,security_deposit')->find();
        $deposit = bcsub($money_limt['security_deposit'], $money_limt['paid_deposit'], 2);
        d($fees,$frozen,$deposit);



        $a = 'PF1717494034927974-1';
        $check = StoreOrder::where('order_id',$a)->count();
        d($check);*/
        //付款
        $j = '{"id":"12c29662-eba0-532a-832e-12ddc30aa5ac","create_time":"2024-06-06T15:47:20+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"\u652f\u4ed8\u6210\u529f","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":{"mchid":"1654274867","appid":"wxdee751952c8c2027","out_trade_no":"PF1718073229145240","transaction_id":"4200002220202406064425693065","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"\u652f\u4ed8\u6210\u529f","bank_type":"ABC_DEBIT","attach":"wechat_common","success_time":"2024-06-06T15:47:20+08:00","payer":{"openid":"onoIP7c1qgjfIr2ce7GJAAmVGcL0"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}},"associated_data":"transaction","nonce":"blQOXyAUGK4K"}}';


        //退款
        /*  $j = '{"id":"1841a014-0829-5c12-82d0-ab211d6c06e3","create_time":"2024-06-06T09:53:59+08:00","resource_type":"encrypt-resource","event_type":"REFUND.SUCCESS","summary":"\u9000\u6b3e\u6210\u529f","resource":{"original_type":"refund","algorithm":"AEAD_AES_256_GCM","ciphertext":{"mchid":"1654274867","out_trade_no":"PF1717558027664507","transaction_id":"4200002211202406058608104458","out_refund_no":"BO1717638826","refund_id":"50303409732024060648234415101","refund_status":"SUCCESS","success_time":"2024-06-06T09:53:59+08:00","amount":{"total":1,"refund":1,"payer_total":1,"payer_refund":1},"user_received_account":"\u652f\u4ed8\u7528\u6237\u96f6\u94b1"},"associated_data":"refund","nonce":"yteRBBbAwfdE"}}';*/


        $result = json_decode($j, true);
        $ciphertext = $result['resource']['ciphertext'];

        PayNotifyLogic::handle('wechat_common', $ciphertext['out_trade_no'], $ciphertext);


        d(1);


        $order = StoreOrder::where('id', 80)->findOrEmpty();
//        d($order);

        $transaction_id = 12121212121212;
        $financeLogic = new StoreFinanceFlowLogic();
        $financeLogic->order = $order;
        $financeLogic->user = ['uid' => $order['uid']];
        if ($order->pay_type != 9 || $order->pay_type != 10) {

            $financeLogic->in($transaction_id, $order['pay_price'], OrderEnum::USER_ORDER_PAY);  //用户单入账
            //商户应该获得的钱 每个商品的price-ot_price 利润
            if ($order->profit !== "0.00") {
                //手续费
                $fees = bcdiv(bcmul($order['pay_price'], '0.02', 2), 1, 2);
                $financeLogic->in($transaction_id, $fees, OrderEnum::ORDER_COMMITION, $order['store_id']);  //手续费入账

                $financeLogic->out($transaction_id, $order['profit'], OrderEnum::MERCHANT_ORDER_OBTAINS, $order['store_id'], $order['staff_id'], 0);//商户获得的
                //冻结金额的
                $frozen = bcsub($order->profit, $fees, 2);
                //缴纳齐全了就加商户没有就加到平台
                $money_limt = SystemStore::where('id', $order['store_id'])->field('paid_deposit,security_deposit')->find();
                $deposit = bcsub($money_limt['security_deposit'], $money_limt['paid_deposit'], 2);//剩余额度
                if ($deposit > 0 && $frozen > 0) {
                    $amount = min($deposit, $frozen);
                    $financeLogic->in($transaction_id, $amount, OrderEnum::ORDER_MARGIN, $order['store_id'], $order['staff_id']);
                }

                //当前商户得冻结金额如果缴纳满足了就加到商户余额中

            }
            $financeLogic->save();
        }
        d(1);


        $result = json_decode($j, true);
        $ciphertext = $result['resource']['ciphertext'];
        PayNotifyLogic::handle('refund', $ciphertext['out_trade_no'], $ciphertext);

        d($result);


        if ($result && $result->event_type == 'REFUND.SUCCESS') {
            $ciphertext = $result->resource['ciphertext'];
            if ($ciphertext['refund_status'] === 'SUCCESS') {
                //处理订单  -1判断是退的一单还是拆分的订单
                PayNotifyLogic::handle('refund', $ciphertext['out_trade_no'], $ciphertext);
                $app->wechat->success();

            }
        }


//    d(1511);

        //退款
        $wechat = new PayService(1);
        $order = [
            'out_trade_no' => 'PF1717729550406928',
            'out_refund_no' => time(),
            'amount' => [
                'refund' => 1,
                'total' => 1,
                'currency' => 'CNY',
            ],
            // '_action' => 'jsapi', // jsapi 退款,默认
            // '_action' => 'app', // app 退款
            // '_action' => 'combine', // 合单退款
            // '_action' => 'h5', // h5 退款
            // '_action' => 'miniapp', // 小程序退款
            // '_action' => 'native', // native 退款

        ];

        $res = $wechat->wechat->refund($order);
        d($res);

        //支付

        $j = '{"id":"89b226d6-e305-5a83-9e7e-29b688cc3b10","create_time":"2024-06-05T11:27:21+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"\u652f\u4ed8\u6210\u529f","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":{"mchid":"1654274867","appid":"wxdee751952c8c2027","out_trade_no":"PF1717556761663487","transaction_id":"4200002211202406058608104458","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"\u652f\u4ed8\u6210\u529f","bank_type":"OTHERS","attach":"recharge","success_time":"2024-06-05T11:27:21+08:00","payer":{"openid":"onoIP7TFXN_106JkCMInwOTPCsD4"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}},"associated_data":"transaction","nonce":"4i7rmOABdwV3"}}';
        $result = json_decode($j, true);
        $ciphertext = $result['resource']['ciphertext'];

        PayNotifyLogic::handle('wechat_common', $ciphertext['out_trade_no'], $ciphertext);
        d(1);


        $all = UserShip::field('id,title,limit')->select()->toArray();

        $new = $this->getNextArrayByID($all, 1);
        d($new);
        d($all);


        \support\Log::info('fasfsaf');
//        Log::info('fdadsdadasd');

        d(6323);
//        d($this->getAccessToken());
        $a = (new WeChatMnpService())->getAccessToken();
//        $a = (new WeChatMnpService())->getUserPhoneNumber('a5c44554ce7caf35d3cf2196da96f7ab735deaf674d639ecb482ce618fa82ee6');

        d($a);


        throw new MyBusinessException('缺失经纬度');

        return $this->success('success', UserLogic::info(8));
        throw new Exception('缺失经纬度');
        $params = [
            'pay_type' => 1,
            'mer_id' => 1,
        ];
        self::$total = 0;
        $order = [
            'add_time' => time(),
            'create_time' => time(),
            'order_id' => getNewOrderId('PF'),
            'total_price' => self::$total,//总价
            'total_num' => 1,//总数
            'pay_type' => $params['pay_type'] ?? 0,
            'cart_id' => implode(',', [1, 2, 3]),
//                'delivery_msg'=>' 预计48小时发货 '
        ];

        $_order = $order;
        $_order['deduction_price'] = 0;
        $_order['merchant'] = $params['mer_id'];
        $_order['uid'] = request()->userId;
        $_order['money'] = 0;
        $_order['user'] = request()->userId;
        $_order['account'] = 0;
        $_order['payinfo'] = '';
        $_order['type'] = 0;
        $_order['source'] = 0;
        $_order['actual'] = $_order['total_price'];
//        d($_order);
//        if($addressId>0){
//            $address=UserAddress::where(['address_id'=>$addressId,'uid'=>Request()->userId])->find();
//            if($address){
//                $_order['real_name'] = $address['real_name'];
//                $_order['user_phone'] = $address['phone'];
//                $_order['user_address'] = $address['detail'];
//                $_order['address_id'] = $addressId;
//            }
//        }


//        if($params['pay_type']==PayEnum::WECHAT_PAY_BARCODE){
//            $_order['source']=1;
//        }
//        if($params['pay_type']==PayEnum::CASH_PAY){
//            $_order['money']=$_order['total'];
//        }

        $order = StoreOrder::create($_order);


        d($order);


    }


    public static function show()
    {
        //处理分类缺失
        $store_id = 23;
        $data = StoreBranchProduct::where('store_id', $store_id)
            ->field('cate_id,store_id')
            ->select()->toArray();
        foreach ($data as $value) {
            self::updateGoodsclass($value['cate_id'], $value['store_id']);
        }

        d($data);


    }


    public static function dealFrozenPrice($oid)
    {
        $detail = StoreOrderCartInfo::where('oid', $oid)->select()->toArray();
        $total_vip = 0;
        foreach ($detail as $value) {
            $total_vip += $value['cart_info']['vip_frozen_price'];
        }
        return $total_vip;
    }


    public function getAccessToken()
    {
        // 微信接口地址
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxdee751952c8c2027&secret=2c46d77df53cd942a7ff608247ea0ccd";

        // 发送 HTTP GET 请求
        $response = file_get_contents($url);

        // 解析 JSON 响应
        $responseData = json_decode($response, true);

        // 检查是否成功获取 access_token
        if (isset($responseData['access_token'])) {
            return $responseData['access_token'];
        } else {
            // 获取 access_token 失败,可以记录错误信息
            error_log("Failed to get access_token: " . $response);
            return null;
        }
    }


    function getNextArrayByID($arr, $id)
    {
        // 遍历数组
        foreach ($arr as $key => $value) {
            // 检查当前数组的id是否与传入的id匹配
            if ($value['id'] == $id) {
                // 如果当前数组不是最后一个,则返回下一个数组
                if ($key + 1 < count($arr)) {
                    return $arr[$key + 1];
                }
                // 如果当前数组是最后一个,则返回null或空数组
                return null;
            }
        }
        // 如果没有找到匹配的id,则返回null或空数组
        return null;
    }


    public static function updateGoodsclass($cate_id, $store_id = 0, $type = 0)
    {
        $one = StoreCategory::where('id', $cate_id)->find();
        if ($one) {
            //查二级分类
            $two = StoreCategory::where('id', $one['pid'])->find();
            if ($two) {
                if ($two['pid'] != 0) {
                    self::cate_update($cate_id, $two['id'], $store_id, 3);
                    self::cate_update($two['id'], $two['pid'], $store_id, 2);
                    self::cate_update($two['pid'], 0, $store_id, 1);
                } else {
                    if ($one['pid'] == 0) {
                        self::cate_update($one['id'], 0, $store_id, 1);
                    } else {
                        self::cate_update($one['id'], $one['pid'], $store_id, 2);
                        self::cate_update($one['pid'], 0, $store_id, 1);
                    }
                }
            }
        }
    }

    public static function cate_update($cate_id = 0, $pid = 0, $store_id = 0, $level = 1)
    {
        $find = Db::name('store_product_cate')->where(['store_id' => $store_id, 'cate_id' => $cate_id, 'level' => $level])->find();
        if ($find) {
            Db::name('store_product_cate')->where('id', $find['id'])->inc('count', 1)->update();
        } else {
            Db::name('store_product_cate')->insert(['pid' => $pid, 'store_id' => $store_id, 'cate_id' => $cate_id, 'count' => 1, 'level' => $level, 'create_time' => time(), 'update_time' => time()]);
        }
    }


}