<?php

namespace App\Http\Controllers\Admin;


use App\Exports\AgentEarningsExport;
use App\Exports\AgentLottoCodesExport;
use App\Exports\AgentOrdersExport;
use App\Exports\AgentShopsExport;
use App\Exports\AgentStocksExport;
use App\Exports\AgentUsersExport;
use App\Exports\AgentWithdrawsExport;
use App\Exports\OrderSharesExport;
use App\Exports\ShopExport;
use App\Exports\ShopGoodsExport;
use App\Exports\ShopOrderExport;
use App\Facades\CommonService;
use App\Facades\WechatService;
use App\Http\Resources\AgentShopCollection;
use App\Http\Response\ResponseJson;
use App\Http\Controllers\Controller;
use App\Models\ActivityOrder;
use App\Models\ActivityOrderLog;
use App\Models\AgentEarning;
use App\Models\AgentOrder;
use App\Models\AgentOrderShare;
use App\Models\AgentRefundOrder;
use App\Models\AgentShop;
use App\Models\AgentUser;
use App\Models\AgentUserLog;
use App\Models\AgentWithdraw;
use App\Models\Contract;
use App\Models\DmaShop;
use App\Models\Food;
use App\Models\LottoCode;
use App\Models\NurtureShop;
use App\Models\OperateStockLog;
use App\Models\PartnerCommission;
use App\Models\S2RealObject;
use App\Models\Shop;
use App\Models\ShopOrder;
use App\Models\ShopOrderComment;
use App\Models\ShopOrderShare;
use App\Models\ShopOrderStatus;
use App\Models\ShopRefundOrder;
use App\Models\User;
use App\Models\Wechat;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ShopController extends Controller
{
    use ResponseJson;

    protected $key = '';
    protected $url = '';

    public function __construct()
    {
//        $this->url = env('SHOP_URL','https://saas.ufutx.com/api/');
//        $this->key = env('SHOP_KEY','eyJpdiI6Ijg0elMrZkpRNC9vWXZFekJ0bUlZa0E9PSIsInZhbHVlIjoiTVpqenR0dDdHM2laMDRyZFFvZmc5Y2NFZ29hZER5UUwrWVlzOHphMGRnR0Q2dlNQSDBsekdRNEtYaWsxekd0S212NU40V0lOWjJKemNDemJIRGRVUEZlbXVnNllTRzExZkdHZ2Q1Z2ppUEZTRGVQc0JzZi9nbkJvSTBWbzRpU3prUDhlbE9xS09aTzdFak5oZ1hlWEpsaC9KNmc4NGI3K1M3a2d6RTBDU1N0RHkzUXpXcm9qNnJpdnpGYTVKblFHIiwibWFjIjoiZWZjNWMyMjlhZTVhZDBjN2Y0ZjI1ZGRjNGMzM2RiN2U5OGEwN2ZmMGI2ODk5N2Y0ODI2YTkxMjIxZjY0ZTcxYyIsInRhZyI6IiJ9');

        $this->url = config("app.shop_url");
        $this->key = config('app.shop_key');
    }

    /**
     * 获取商品列表
     * @param Request $request
     */
    public function getGoodsList(Request $request){
        $shops = Shop::nature()->keyword()->status()->orderByDesc("id")->select("id", 'icon', 'title', 'price', 'is_show','sku', 'nature',"created_at");
        $export = $request->input("export");
        if ($export) {
            $shops = $shops->get();
            return Excel::download(new ShopExport($shops), '商品列表.xlsx');
        }
        $nopage = $request->input('nopage');
        if($nopage) {
            $shops = $shops->get();
            return $this->success('ok', $shops);
        }
        $shops = $shops->paginate();
        return $this->success('ok', $shops);
    }

    public function getAllGoodsList(){
//            $headers = [
//                'Key' => $this->key, // 自定义头部参数（示例）
//            ];
//            $url = get_request_url_param($this->url.'admin/shops',[]);
//            $client = new Client();
//            $response = $client->get($url, [
//                'headers' => $headers,
//            ]);
//            $code = $response->getStatusCode();
//            if($code != 200){
//                return $this->failure('请求失败');
//            }
//            $body = $response->getBody()->getContents(); // 获取响应内容
//            $list = json_decode($body, true);
//            if($list['code'] == 1){
//                return $this->failure($list['message']);
//            }
//            $goods = $list['data'] ?? [];
            $goods = Shop::keyword()->status()->orderByDesc("id")->select("id", 'icon', 'title', 'price', 'is_show','sku',"created_at")/*->withCount('payOrders as order_count')*/->paginate();
            $food = Food::where('type','NUTRIENT')->orderByDesc('id')->get()?->toArray();
            $data = [];
            foreach ($goods as $item){
                $map['id'] = $item['id'];
                $map['name'] = $item['title'];
                array_push($data,$map);
            }
            foreach ($food as $value){
                $map['id'] = $value['id'];
                $map['name'] = $value['name'];
                array_push($data,$map);
            }
            return $this->success('ok', $data);
    }

    /**
     * 商品出库入库
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function setGoodsStock(Request $request){
        try {
            $id = $request->post('goods_id');
            if(empty($id)){
                return $this->failure('商品id不为空');
            }
            $params = $map = [];
            $params['num'] = $map['num']  = $request->post('num');
            $params['type'] = $request->post('type');
            $params['sku_id'] = $map['sku_id'] = $request->post('sku_id');
            $map['id'] = $id;
            $map['name'] = $request->post('name');
            $map['stock'] = $request->post('stock',0);
            //添加操作记录
            $admin = auth()->user();
            $operate_type = OperateStockLog::OPERATE_TYPE_IN;

            $after_num = $map['stock']+$params['num'];
            if($params['type'] == 'DECREMENT'){
                if($map['stock'] < $params['num']){
                    return $this->failure('库存不足');
                }
                $operate_type = OperateStockLog::OPERATE_TYPE_OUT;
                $after_num = $map['stock']-$params['num'];
            }

            $contract = $request->input('contract');
            $images = $request->input('images',[]);

//            $list = $this->postData($this->url."admin/shops/{$id}/stock",$params);
//            if($list['code'] == 1){
//                return $this->failure($list['message']);
//            }
            $remark = $request->post('remark');

            $goods_type = OperateStockLog::GOODS_TYPE_GOODS;
            $food = Food::where('shop_id',$id)->first();
            if(!empty($food)){
                $goods_type = OperateStockLog::GOODS_TYPE_FOOD;
                $map['id'] = $food->id;
            }

            $map['before_num'] = $map['stock'];
            $map['after_num'] = $after_num;
            $map['type'] = OperateStockLog::TYPE_ADMIN;
            $map['remark'] = !empty($remark) ? $remark : "管理员:{$admin->name}修改了商品库存,商品名:{$map['name']},数量:{$params['num']}";
            $map['operate_type'] = $operate_type;
            $map['status'] = OperateStockLog::OPERATE_STATUS_APPLY;
            $map['images'] = json_encode($images);
            $map['goods_type'] = $goods_type;
            $map['contract'] = $contract;
            OperateStockLog::addLog($admin,$map);

            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('setGoodsStock:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 获取商品详情
     * @param Request $request
     */
    public function getGoodsDetail(Request $request){
//        try {
//            $id = $request->get('id');
//            $headers = [
//                'Key' => $this->key, // 自定义头部参数（示例）
//            ];
//
//            $params = [];
//            $url = get_request_url_param($this->url.'admin/shops/'.$id,$params);
//            $client = new Client();
//            $response = $client->get($url, [
//                'headers' => $headers,
//            ]);
//            $code = $response->getStatusCode();
//            if($code != 200){
//                return $this->failure('请求失败');
//            }
//            $body = $response->getBody()->getContents(); // 获取响应内容
//            $list = json_decode($body, true);
//            if($list['code'] == 1){
//                return $this->failure($list['message']);
//            }
//            $data = $list['data'] ?? [];
//            return $this->success('ok', $data);
//        }catch (\Exception $e){
//            Log::error('getGoodsList:' . $e->getMessage());
//            return $this->failure('请求失败');
//        }
        $shop_id = $request->get('id');
        $shop = Shop::find($shop_id);
        return $this->success('ok', $shop);
    }

    /**
     * 添加商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function addGoods(Request $request){
        $title = $request->input('title');
        if(empty($title)) return $this->failure('标题不为空');
        $pay_type = $request->input('pay_type');
        $price = $request->input('price');
        if($pay_type == 'wechat' && $price == 0){
            return $this->failure('付费商品价格不为0');
        }
        $data = $request->all();
        $shop = Shop::create($data);
        return $this->success('ok', $shop);
    }

    /**
     * 删除商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function deleteGoods(Request $request)
    {

        $id = $request->get('id');
        $shop = Shop::find($id);
        //是否有属性商品存在
        $agent_shop= AgentShop::where('shop_id', $id)->exists();
        if ($agent_shop) return $this->failure("有批发商品存在");
        $nurture_shop = NurtureShop::where('shop_id', $id)->exists();
        if ($nurture_shop) return $this->failure("有小程序商品存在");
        $shop->delete();
        return $this->success('ok');

    }

    /**
     * 更新商品
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateGoods(Request $request){
//        try {
            $id = $request->get('id');
            if(empty($id)){
                return $this->failure('请选择商品');
            }
            $title = $request->input('title');
            if(empty($title)) return $this->failure('标题不为空');

//            $sub_title = $request->input('sub_title');
//
//            $icon = $request->input('icon');

            $pay_type = $request->input('pay_type');

            $price = $request->input('price');
            if($pay_type == 'wechat' && $price == 0){
                return $this->failure('付费商品价格不为0');
            }

            $sku = $request->input('sku');
            if(empty($sku) && $pay_type == 'wechat') return $this->failure('请选择规格');
            foreach ($sku as $item) {
                if (isset($item['vip_price']) && $item['vip_price'] > $item['price']) return $this->failure("规格会员价高于原价");
            }
            $data = $request->all();
            Shop::where('id', $id)->update($data);
            return $this->success('ok');
//            $banners = $request->input('banners');
//            $describe = $request->input('describe');
//            $is_show = $request->input('is_show');
//            $is_vip = $request->input('is_vip');
//            $vip_price = $request->input('vip_price');
//            if ($price < $vip_price) return $this->failure("会员价高于原价");
//
//            $headers = [
//                'Key' => $this->key, // 自定义头部参数（示例）
//            ];
//
//            $url = $this->url . 'admin/shops/'.$id;
//            $client = new Client();
//            $response = $client->put($url, [
//                'headers' => $headers,
//                'json' => [
//                    'title' => $title,
//                    'sub_title' => $sub_title,
//                    'icon' => $icon,
//                    'pay_type' => $pay_type,
//                    'price' => $price,
//                    'sku' => $sku,
//                    'describe' => $describe,
//                    'is_show' => $is_show,
//                    'banners' => $banners,
//                    'vip_price'=>$vip_price,
//                    'is_vip' => $is_vip,
//                ],
//            ]);
//            $code = $response->getStatusCode();
//            if($code != 200){
//                return $this->failure('修改失败');
//            }
//            $body = $response->getBody()->getContents(); // 获取响应内容
//            $list = json_decode($body, true);
//            if($list['code'] == 1){
//                return $this->failure($list['message']);
//            }
//
//            $data = $list['data'] ?? [];
//            return $this->success('ok', $data);
//        }catch (\Exception $e){
//            Log::error('updateGoods:' . $e->getMessage());
//            return $this->failure('修改失败');
//        }
    }

    /**
     * 获取商城某个商品订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getShopGoodsOrders(Request $request){
        try {
            $id = $request->get('id');
            if(empty($id)){
                return $this->failure('请选择商品');
            }
            $params = [];
            $params['keyword'] = $request->get('keyword');
            $params['pay_status'] = $request->get('pay_status');
            $params['ship_status'] = $request->get('ship_status');

            $url = get_request_url_param($this->url.'admin/shops/'.$id.'/orders',$params);

            $list = $this->getData($url);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('getShopGoodsOrders:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 获取所有订单
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getShopOrders(Request $request){
        try {
            $params = [];
            $params['keyword'] = $request->get('keyword');
            $params['pay_status'] = $request->get('pay_status');
            $params['ship_status'] = $request->get('ship_status');
            $params['problem_status'] = $request->get('problem_status');
            $params['start_time']  = $request->get('start_time');
            $params['end_time'] = $request->get('end_time');
            $params['nopage'] = $request->get('nopage');

            $url = get_request_url_param($this->url.'admin/shops/orders',$params);
            $list = $this->getData($url);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            $data = $list['data']??[];
            foreach ($data['data'] as $key => $value){
                $data['data'][$key]['goods_info'] = json_decode($value['goods_info'],true);
            }
            return $this->success('ok', $data);
        }catch (\Exception $e){
            Log::error('getShopOrders:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    public function getShopOrdersV2(Request $request)
    {
        $shop_id = $request->input('shop_id');
        $orders = ShopOrder::with("user:id,name,mobile,avatar", "recommendUser")->withCount("comments as comment_count")->keyword()->shop($shop_id)->status()->problem()->orderByDesc("id");
        $export = $request->input('export');
        if ($export) {
            $orders = $orders->get();
            return Excel::download(new ShopOrderExport($orders), '商品订单.xlsx');
        }
        $orders = $orders->paginate();
        return $this->success('ok', $orders);
    }


    public function storeShopOrders(Request $request)
    {
        $user_id = $request->input('user_id');
        $user = User::find($user_id);
        if (empty($user)) return $this->failure("用户不存在");
        $data = $request->all();
        $dma_shop = DmaShop::find($data['dma_shop_id']);
        if (empty($dma_shop)) return $this->failure("DMA商品信息不存在");
        $shop = Shop::find($dma_shop->shop_id);
        if (empty($shop)) return $this->failure("商品信息不存在");
        $sku_arr = $dma_shop->sku;
        if (is_array($sku_arr) && count($sku_arr)) {//含sku
            $sku = collect($sku_arr)->where('sku_id', $request->sku_id)->first();
            if (empty($sku)) throw new \Exception("获取sku信息失败");
            if (isset($sku['stock']) && $sku['stock'] < $data['num']) return $this->failure("库存不足");
            $data['price'] = $data['origin_price'] = $sku['price'] * $data['num'];
        }else {
            $data['price'] = $data['origin_price'] = $shop->price * $data['num'];
        }
        $sku = collect($dma_shop->sku)->where('sku_id', $request->sku_id)->first();

        $data['shop_id'] = $shop->id;
        $data['shop_info'] = ["id"=>$shop->id, 'title'=>$shop->title, 'pic'=>$shop->icon, "sku"=> $sku];
        $data['sku_id'] = $sku?$sku['sku_id']:0;
        $data['pay_status'] = ShopOrder::PAIDSTATUS;
        $data['express_type'] = $data['express_type']??"ONLINE";
        $data['pay_type'] = ShopOrder::FREEPAYTYPE;
        $data['trade_no'] = CommonService::getTradeNo();
        $data['name'] = $data['name']??$user->name;
        $data['mobile'] = $data['mobile']??$user->mobile;
        DB::beginTransaction();
        //生成未支付订单
        $order = ShopOrder::create($data);
        ShopOrderStatus::create(['order_id'=>$order->id, 'status'=>ShopOrder::UNPAIDSTATUS]);
        ShopOrderStatus::create(['order_id'=>$order->id, 'status'=>ShopOrder::PAIDSTATUS]);
        DB::commit();
        return $this->success('ok', $order);
    }



    /**
     * 提取get请求公共代码
     * @param $url
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getData($url){
        $headers = [
            'Key' => $this->key, // 自定义头部参数（示例）
        ];
        $client = new Client();
        $response = $client->get($url, [
            'headers' => $headers,
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }
    /**
     * 提取post请求公共代码
     * @param $url
     * @param $params
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function postData($url,$params){
        $headers = [
            'Key' => $this->key, // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->post($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    public function putData($url,$params){
        $headers = [
            'Key' => $this->key, // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->put($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    public function deleteData($url,$params){
        $headers = [
            'Key' => $this->key, // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->delete($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    /**
     * 订单退款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function shopOrderRefund(Request $request){
        try {
            $order_id = $request->input('order_id');
            $price = $request->input('price');
            $remark = $request->input('remark');
            if(empty($order_id) || empty($price)){
                return $this->failure('缺少参数');
            }
            $params = [];
            $params['price'] = $price;
            $params['remark'] = $remark;
            $list = $this->postData($this->url.'admin/refund/orders/'.$order_id,$params);

            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);

        }catch (\Exception $e){
            Log::error('orderRefund:' . $e->getMessage());
            return $this->failure('退款失败');
        }
    }

    public function shopOrderRefundV2(Request $request)
    {
        $user = auth()->user();
        $order_id = $request->input('order_id');
        $order = ShopOrder::find($order_id);
        if ($order->pay_status == ShopOrder::UNPAIDSTATUS) return $this->failure("订单未支付");
        if ($order->pay_status == ShopOrder::REFUNDSTATUS) return $this->failure("订单已退款");
        //可退金额
        $refund_fee = ShopRefundOrder::where('trade_no', $order->trade_no)->where("is_hook", 1)->sum('refund_fee');
        $amount = number_format($order->price - $refund_fee, 2, '.','');
        if($request->price > $amount) return $this->failure("退款金额大于最大可退款金额");
        $refund_trade_no = CommonService::getTradeNO();
        $total_amount = $order->price;
        $refund_amount = $request->price;
        $callback = config("app.url").'/api/admin/shop/order/'.$refund_trade_no.'/refund/callback';
        ShopRefundOrder::create([
            'order_id'=>$order_id,
            'admin_id'=>$user->id,
            'trade_no'=>$order->trade_no,
            'refund_trade_no'=>$refund_trade_no,
            'total_fee'=>$order->price,
            'refund_fee'=>$refund_amount,
            'is_hook'=>0,
            'remark'=>$request->remark,
        ]);
        //生成退款订单
        WechatService::refund($order->trade_no, $refund_trade_no, $total_amount, $refund_amount, $callback);
        return $this->success('ok');
    }

    public function shopOrderRefundCallbackV2($refund_trade_no)
    {
        $refund_order = ShopRefundOrder::where("refund_trade_no", $refund_trade_no)->first();
        if (empty($refund_order)) return $this->failure("退款订单不存在");
        if ($refund_order->is_hook) return $this->success('退款订单已回调');
        //可退金额
        $refund_fee = ShopRefundOrder::where('trade_no', $refund_order->trade_no)->where("is_hook", 1)->sum('refund_fee');
        $order = ShopOrder::where('trade_no', $refund_order->trade_no)->first();
        $amount = number_format($order->price - $refund_fee, 2, '.','');
        if($refund_order->refund_fee > $amount) {
            $refund_order->update(['is_hook'=>-1, 'err_msg'=>"退款金额大于可提现金额"]);
            return $this->failure("退款金额大于可提现金额");
        }
        $res = WechatService::orderRefunded($refund_trade_no);
        if ($res['status']) {
            $refund_order->update(['is_hook'=>1]);
            $order->status()->create(['order_id'=>$order->id, 'status'=>ShopOrder::REFUNDSTATUS]);
            if ($amount == $refund_order->refund_fee) { //全部退款
                $order->update(["pay_status"=>ShopOrder::REFUNDSTATUS]);
            }
        }else {
            $refund_order->update(['is_hook'=>-1, 'err_msg'=>$res['message']]);
        }
        return $this->success('退款订单回调成功');
    }

    public function agentOrderRefundCallback($refund_trade_no)
    {
        $refund_order = AgentRefundOrder::where("refund_trade_no", $refund_trade_no)->first();
        if (empty($refund_order)) return $this->failure("退款订单不存在");
        if ($refund_order->is_hook) return $this->success('退款订单已回调');
        //可退金额
        $refund_fee = AgentRefundOrder::where('trade_no', $refund_order->trade_no)->where("is_hook", 1)->sum('refund_fee');
        $order = AgentOrder::where('trade_no', $refund_order->trade_no)->first();
        $amount = number_format($order->price - $refund_fee, 2, '.','');
        if($refund_order->refund_fee > $amount) {
            $refund_order->update(['is_hook'=>-1, 'err_msg'=>"退款金额大于可提现金额"]);
            return $this->failure("退款金额大于可提现金额");
        }
        $res = WechatService::orderRefunded($refund_trade_no, $order->sub_mch_id);
        Log::info($res);
        if ($res['status']) {
            $refund_order->update(['is_hook'=>1]);
            $order->status()->create(['order_id'=>$order->id, 'status'=>AgentOrder::REFUNDSTATUS]);
            if ($amount == $refund_order->refund_fee) { //全部退款
                $order->update(["pay_status"=>AgentOrder::REFUNDSTATUS]);
                //删除抽奖码
                LottoCode::where('order_id', $order->id)->delete();
            }
        }else {
            $refund_order->update(['is_hook'=>-1, 'err_msg'=>$res['message']]);
        }
        return $this->success('退款订单回调成功');
    }

    /**
     * 订单退款回调
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function shopOrderRefundCallback(Request $request){
        try {
            $trade_no = $request->input('trade_no');
            if(empty($trade_no)){
                return $this->failure('订单号不为空');
            }

            $params = [];
            $list = $this->postData($this->url."admin/order/{$trade_no}/refund/callback",$params);

            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);

        }catch (\Exception $e){
            Log::error('shopOrderRefundCallback:' . $e->getMessage());
            return $this->failure('退款失败');
        }
    }

    /**
     * 订单发货
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function orderShipment(Request $request){
        try {
            $order_id = $request->input('order_id');
            if(empty($order_id)){
                return $this->failure('订单id不为空');
            }
            $express_type = $request->input('express_type');
            $remark = $request->input('remark');
            $express = $request->input('express');
            $express_trade_no = $request->input('express_trade_no');
            if($express_type == 'ONLINE'){
                if(empty($express) || empty($express_trade_no)){
                    return $this->failure('缺少快递信息');
                }
            }


            $params = [];
            $params['express_type'] = $express_type;
            $params['remark'] = $remark;
            $params['express'] = $express;
            $params['express_trade_no'] = $express_trade_no;
            $list = $this->postData($this->url."admin/send/orders/{$order_id}",$params);

            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('orderShipment:' . $e->getMessage());
            return $this->failure('发货失败');
        }
    }

    public function orderShipmentV2(Request $request)
    {
        $admin = auth()->user();
        $order_id = $request->input('order_id');
        if(empty($order_id)){
            return $this->failure('订单id不为空');
        }
        $remark = $request->input('remark');
        $express = $request->input('express');
        $express_trade_no = $request->input('express_trade_no');
        $order = ShopOrder::find($order_id);
        if ($order->pay_status == ShopOrder::UNPAIDSTATUS) return $this->failure("订单未支付");
        if ($order->pay_status == ShopOrder::REFUNDSTATUS) return $this->failure("订单已退款");
        if ($order->pay_status != ShopOrder::PAIDSTATUS) return $this->failure("订单暂不支持发货");
        if (empty($request->express_type)) return $this->failure("请选择快递方式");
        if ($order->express_type == ShopOrder::ONLINETYPE) {
            if (empty($request->express) || empty($request->express_trade_no)) return $this->failure("缺少快递信息");
        }
        $order->update(['pay_status'=>ShopOrder::SENDSTATUS , 'ship_status'=>ShopOrder::SENDSTATUS, 'express'=>$express, 'express_trade_no'=>$express_trade_no]);
        $order->status()->create(['order_id'=>$order_id, 'status'=>ShopOrder::SENDSTATUS]);
        //备注
        if ($remark) {
            $order->comments()->create(['admin_id'=>$admin->id, 'way'=>"订单自提", "content"=>$remark]);
        }
        $shop = Shop::find($order['shop_info']['id']);
        $res = $shop->stockOut($admin, $order->id, $order['shop_info']['sku']['sku_id']??'', $order->num, OperateStockLog::GOODS_TYPE_GOODS, "管理员：{$admin->name} 发货了订单减少商品：{$shop->title}库存，减少数量{$order->num}");
        if ($res['status']) {
            return $this->failure($res['msg']);
        }
        return $this->success('ok');
    }


    /**
     * 搜索快递公司
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getExpressCompany(Request $request){
        try {

            return $this->success("ok", []);
            $params = [];
            $params['keyword'] = $request->get('keyword');

            $url = get_request_url_param($this->url.'admin/logistics/companies',$params);
            $list = $this->getData($url);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('getExpressCompany:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 标记订单问题
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function markOrderProblem(Request $request){
        try {
            $order_id = $request->input('order_id');
            if(empty($order_id)){
                return  $this->failure('订单id不为空');
            }
            $params = [];
            $params['status'] = $request->input('status');

            $params['desc'] =$request->input('desc');

            $list = $this->postData($this->url."admin/problem/orders/{$order_id}",$params);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('markOrderProblem:' . $e->getMessage());
            return $this->failure('标记失败');
        }
    }

    public function markOrderProblemV2(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = ShopOrder::find($order_id);
        if ($order->pay_status == ShopOrder::UNPAIDSTATUS) return $this->failure("订单未支付");

        DB::beginTransaction();
        $problem_status = $request->problem_status;

        $order->update(["pay_status"=>ShopOrder::PROBLEMSTATUS, 'problem_status'=>$problem_status]);
        $order->status()->create(['order_id'=>$order_id, 'status'=>$problem_status]);
        DB::commit();
        return $this->success('ok');
    }


    /**
     * 获取订单备注
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getOrderComments(Request $request){
        try {
            $order_id = $request->get('order_id');
            if(empty($order_id)){
                return $this->failure('订单id不为空');
            }

            $list = $this->getData($this->url."admin/orders/{$order_id}/comments");
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('getOrderComments:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    public function getOrderCommentsV2(Request $request)
    {
        $order_id = $request->input("order_id");
        $comments = ShopOrderComment::with('admin:id,name,mobile')->where('order_id', $order_id)->orderByDesc("id")->paginate();
        return $this->success('ok', $comments);
    }

    /**
     * 增加订单备注
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addOrderComments(Request $request){
        try {
            $order_id = $request->input('order_id');
            if(empty($order_id)){
                return $this->failure('订单id不为空');
            }
            $params = [];
            $params['way'] = $request->input('way');
            $params['content'] =$request->input('content');
            if(empty($params['way'])){
                return $this->failure('请填写沟通方式');
            }
            if(empty($params['content'])){
                return $this->failure('请填写内容');
            }
            $params['photo'] =$request->input('photo');
            $params['result'] =$request->input('result');

            $list = $this->postData($this->url."admin/comment/orders/{$order_id}",$params);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('addOrderComments:' . $e->getMessage());
            return $this->failure('备注失败');
        }
    }

    public function addOrderCommentsV2(Request $request)
    {
        $data = $request->all();
        $data['admin_id'] = auth()->id();
        $comment = ShopOrderComment::create($data);
        return $this->success('ok', $comment);
    }


    /**
     * 订单签收
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function takeOrder(Request $request){
        try {
            $order_id = $request->get('order_id');
            if(empty($order_id)){
                return $this->failure('订单id不为空');
            }
            $list = $this->postData($this->url."admin/sign/orders/{$order_id}",[]);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('takeOrder:' . $e->getMessage());
            return $this->failure('签收订单');
        }
    }

    public function takeOrderV2(Request $request)
    {
        $order_id = $request->get('order_id');
        $order = ShopOrder::find($order_id);
        $order->update(['pay_status'=>ShopOrder::SIGNEDSTATUS]);
        $order->status()->create(['order_id'=>$order_id, 'status'=>ShopOrder::SIGNEDSTATUS]);
        return $this->success('ok');
    }

    public function signAgentOrder(Request $request, AgentOrder $order)
    {
        $order->update(['pay_status'=>AgentOrder::SIGNEDSTATUS]);
        $order->status()->create(['order_id'=>$order->id, 'status'=>AgentOrder::SIGNEDSTATUS]);
        return $this->success('ok');
    }

    /**
     * 导出订单excel
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function exportOrderExcel(Request $request){
        try {
            $params = [];
            $params['keyword'] = $request->get('keyword');
            $params['pay_status'] = $request->get('pay_status');
            $params['ship_status'] = $request->get('ship_status');
            $params['problem_status'] = $request->get('problem_status');
            $params['start_time']  = $request->get('start_time');
            $params['end_time'] = $request->get('end_time');
            $params['nopage'] = $request->get('nopage',1);

            $url = get_request_url_param($this->url.'admin/shops/orders',$params);
            $list = $this->getData($url);
            if(!isset($list['data'])){
                return $this->failure('暂无数据');
            }
            $data = $list['data'];
            foreach ($data as $key => $value){
                $data[$key]['goods_info'] = json_decode($value['goods_info'],true);
            }

            // 下载 Excel 文件
            return Excel::download(new ShopOrderExport($data), 'orderData.xlsx');
        }catch (\Exception $e){
            Log::error('exportOrderExcel:' . $e->getMessage());
            return $this->failure('导出失败');
        }
    }

    /**
     * 导出商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function exportGoods(Request $request){
        try {
            $keyword = $request->get('keyword');
            $is_show = $request->get('is_show');

            $headers = [
                'Key' => $this->key, // 自定义头部参数（示例）
            ];

            $params['keyword'] = $keyword;
            $params['is_show'] = $is_show;
            $url = get_request_url_param($this->url.'admin/shops',$params);
            $client = new Client();
            $response = $client->get($url, [
                'headers' => $headers,
            ]);
            $code = $response->getStatusCode();
            if($code != 200){
                return $this->failure('请求失败');
            }
            $body = $response->getBody()->getContents(); // 获取响应内容
            $list = json_decode($body, true);
            if($list['code'] == 1){
                return $this->failure($list['message']);
            }
            $data = $list['data']['data'] ?? [];
            return Excel::download(new ShopGoodsExport($data), 'shop_goods.xlsx');
        }catch (\Exception $e){
            Log::error('exportGoods:' . $e->getMessage());
            return $this->failure('导出失败');
        }
    }
    /**
     * 获取订单退款记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getRefundOrder(Request $request){
        try {
            $order_id = $request->get('order_id');
            if(empty($order_id)){
                return $this->failure('订单号不为空');
            }
            $nopage = $request->get('nopage');
            $is_hook = $request->get('is_hook');

            $params = [];
            $params['nopage'] = $nopage;
            $params['is_hook'] = $is_hook;

            $url = get_request_url_param($this->url."admin/refund/orders/{$order_id}",$params);
            $list = $this->getData($url);
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('getRefundOrder:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    public function getRefundOrderV2(Request $request)
    {
        $order_id = $request->input('order_id');
        $orders = ShopRefundOrder::with('admin:id,name,mobile')->where('order_id', $order_id)->orderByDesc("id")->paginate();
        return $this->success('ok', $orders);
    }

    /**
     * 获取退款订单详情
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getRefundOrderDetail(Request $request){
        try {
            $order_id = $request->get('order_id');
            if(empty($order_id)){
                return $this->failure('订单号不为空');
            }

            $list = $this->getData($this->url."admin/refund/orders/{$order_id}/amount");
            return $this->success('ok', $list['data']??[]);
        }catch (\Exception $e){
            Log::error('getRefundOrderDetail:' . $e->getMessage());
            return $this->failure('获取退款订单详情');
        }
    }

    public function getRefundOrderDetailV2(Request $request)
    {
        $order_id = $request->get('order_id');
        $order = ShopOrder::find($order_id);
        $refund_fee = $order->refundOrders()->whereIn('is_hook', [0, 1])->sum('refund_fee');
        $remain_fee = number_format($order->price - $refund_fee, 2, '.', '');
        $no_refund_fee = 0;
        return $this->success('ok', compact('refund_fee', 'remain_fee', 'no_refund_fee'));
    }


    /**
     * 获取订单详情
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getOrderDetail(Request $request){
        try {
            $order_id = $request->get('order_id');
            if(empty($order_id)){
                return $this->failure('订单号不为空');
            }
            $list = $this->getData($this->url."admin/shops/orders/{$order_id}");

            $data = $list['data'] ?? [];
            // 假设$data是你的JSON字符串解析后得到的数组
            if(!empty($data['recive']['tracks'])){
                usort($data['recive']['tracks'], function($a, $b) {
                    return strtotime($b['created_at']) - strtotime($a['created_at']);
                });
            }
            return $this->success('ok', $data);
        }catch (\Exception $e){
            Log::error('getRefundOrderDetail:' . $e->getMessage());
            return $this->failure('获取退款订单详情');
        }
    }

    public function getOrderDetailV2(Request $request)
    {
        $order_id = $request->get('order_id');
        $order = ShopOrder::find($order_id);
        $order->status;
        return $this->success('ok', $order);
    }

    public function storeAgentShop(Request $request, Shop $shop)
    {
//        $url = config('app.shop_url')."admin/agent/shop/$shop_id";
//        $params = $request->all();
//        $res = $this->postData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        return $this->success('ok');
        $data = $request->all();
        $res = $shop->shopAgent()->exists();
        if ($res) return $this->failure("添加失败，商品已添加");
        $shop->shopAgent()->create($data);
        return $this->success('ok');
    }

    public function updateAgentShop(Request $request, Shop $shop)
    {
//        $url = config('app.shop_url')."admin/agent/shop/$shop_id";
//        $params = $request->all();
//        $res = $this->putData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        return $this->success('ok');
        $data = $request->only('sku', 'freight','ratio', 'lotto_code', 'is_show', 'payment_id');
        $shop->shopAgent()->update($data);
        return $this->success('ok');
    }

    public function deleteAgentShop(Request $request, Shop $shop)
    {
//        $url = config('app.shop_url')."admin/agent/shop/$shop_id";
//        $params = $request->all();
//        $res = $this->deleteData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        return $this->success('ok');
        $shop->shopAgent()->delete();
        return $this->success('ok');
    }

    public function agentShops(Request $request)
    {
        $shops = Shop::with('shopAgent', 'shopAgent.payment')->keyword()->agent()->orderByDesc("id");
        if ( $request->nopage) {
            $shops = $shops->get();
        }elseif ($request->export){
            $shops = $shops->get()->toArray();
            return Excel::download(new AgentShopsExport($shops), '商品列表.xlsx');
        }else{
            $shops = $shops->paginate();
        }
//        $shops = new AgentShopCollection($shops);
        return $this->success('ok', $shops);
    }

    public function agentShop(Shop $shop)
    {
//        $url = config('app.shop_url')."admin/agent/shop/$shop_id";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);

//        $shop->sku = $shop->shopAgent->sku;
//        $shop->ratio = $shop->shopAgent->ratio;
        $shop->shopAgent;
        return $this->success('ok', $shop);
    }

    public function agentOrders(Request $request)
    {
        $shop_id = $request->input('shop_id');
        $user_id = $request->user_id;
        $orders = AgentOrder::with('user:id,name,mobile,avatar', 'recommendUser')->user($user_id)->keyword()->shop($shop_id)->status()->time()->orderByDesc("id");
        if ($request->export) {
            $orders = $orders->get();
            return Excel::download(new AgentOrdersExport($orders), '订单列表.xlsx');
        }else {
            $orders = $orders->paginate();
        }
        foreach ($orders as $order)
        {
            $order->name = $order->name?:($order->user?$order->user->name:'');
            $order->mobile = $order->mobile?:($order->user?$order->user->mobile:'');
            //查询订单剩余可退款金额
            $refund_amount = AgentRefundOrder::where('order_id',$order->id)->where('is_hook',1)->sum("refund_fee");
            $order->available_amount = $order->price - $refund_amount;
        }
        return $this->success('ok', $orders);
    }

    public function storeAgentOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $user = User::find($user_id);
        $shop_id = $request->input('shop_id');
        $sku_id = $request->input('sku_id');
        $price = $request->input('price');
        $num = $request->input('num',1);
        $from_user_id = $request->input('from_user_id');
        $created_at = $request->input('created_at');
        $is_agent = $request->input('is_agent');
        $is_earning = $request->input('is_earning');
        $shop = Shop::find($shop_id);
        if (empty($shop)) return $this->failure("未找到商品信息");
        $agent_shop = AgentShop::where('shop_id', $shop_id)->first();
        if (empty($agent_shop)) return $this->failure("未找到批发商商品信息");
        $skus = $shop->sku;
        $item = null;
        foreach ($skus as $sku) {
            if ($sku['sku_id'] == $sku_id) {
                $item = $sku;
            }
        }
        if (empty($item)) return $this->failure("未找到批发商商品规格信息");
        DB::beginTransaction();
        $order = AgentOrder::create([
            'user_id'=>$user_id,
            'name'=> $user->name,
            'mobile'=>$user->mobile,
            'trade_no'=>CommonService::getTradeNO(),
            'origin_price'=>$item['price'] * $num,
            'price'=>$price,
            'is_online'=>AgentOrder::OFFLINE,
            'pay_type'=>AgentOrder::FREEPAY,
            'pay_status'=>AgentOrder::PAIDSTATUS,
            'shop_id'=>$shop_id,
            'sku_id'=>$sku_id,
            'shop_info'=> ["id"=>$shop_id, 'title'=>$shop->title, 'pic'=>$shop->icon, 'sku'=>$item],
            'num'=>$num,
            'from_user_id'=>$from_user_id,
            'created_at'=>$created_at,
        ]);
        //增加抽奖码
        iF (in_array($shop_id, [1,3])) {
            for ($index = 0; $index < $num; $index++) {
                $code = time().CommonService::random(6,1).strtoupper(CommonService::random(1));
                //生成抽奖码
                $order->lottoCode()->create(['user_id'=>$order->user_id, 'code'=>$code]);
            }
        }

        //成为批发商
        if ($is_agent) {
//            AgentUser::updateOrCreate(['user_id'=>$user_id], ['level'=>AgentUser::AgentLevelBeing]);
            $admin = auth()->user();
            AgentUser::changeLevel($user_id, AgentUser::AgentLevelBeing, "管理员【{$admin->name}】后台生成渣酒订单");
        }
        //分成申请
        if ($is_earning) {
            $amount = $request->input("amount");
            AgentOrderShare::create([
                'user_id'=>$from_user_id,
                'order_id'=>$order->id,
                'trade_no'=>$order->trade_no,
                'amount'=>$amount,
                'status'=>"APPLY",
            ]);
        }
        DB::commit();
        return $this->success("ok");
    }

    public function agentOrder(Request $request, $order_id)
    {
//        $params = $request->all();
//        $param =  http_build_query($params);
//        $url = config('app.shop_url')."admin/agent/orders/{$order_id}?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        $contract = null;
//        if ($data['contract_id']) {
//            $contract = Contract::where('id', $data['contract_id'])->with('type')->first();
//        }
//        $data['contract'] = $contract;
//        return $this->success('ok', $data);
        $order = AgentOrder::find($order_id);
        return $this->success('ok', $order);
    }

    public function agentOrderShipment(Request $request, AgentOrder $order)
    {
        DB::beginTransaction();
        $admin = auth()->user();

        $remark = $request->input('remark');
        $express = $request->input('express');
        $express_trade_no = $request->input('express_trade_no');
        if ($order->pay_status == AgentOrder::UNPAIDSTATUS) return $this->failure("订单未支付");
        if ($order->pay_status == AgentOrder::REFUNDSTATUS) return $this->failure("订单已退款");
        if ($order->pay_status != AgentOrder::PAIDSTATUS) return $this->failure("订单暂不支持发货");
        if ($order->is_online == AgentOrder::ONLINETYPE) {
            if (empty($request->express) || empty($request->express_trade_no)) return $this->failure("缺少快递信息");
        }
        $order->update(['pay_status'=>ShopOrder::SENDSTATUS , 'ship_status'=>AgentOrder::SENDSTATUS, 'express'=>$express, 'express_trade_no'=>$express_trade_no]);
        $order->status()->create(['order_id'=>$order->id, 'status'=>AgentOrder::SENDSTATUS]);
        //备注
//        if ($remark) {
//            $order->comments()->create(['admin_id'=>$admin->id, 'way'=>"订单自提", "content"=>$remark]);
//        }
        $shop = Shop::find($order['shop_info']['id']);
        $res = $shop->stockOut($admin, $order->id, $order['shop_info']['sku']['sku_id']??'', $order->num, OperateStockLog::GOODS_TYPE_GOODS, "管理员：{$admin->name} 发货了批发商订单减少商品：{$shop->title}库存，减少数量{$order->num}");
        if ($res['status']) {
            return $this->failure($res['msg']);
        }
        DB::commit();
        return $this->success('ok');
    }

    public function agentOrderRefund(Request $request, AgentOrder $order)
    {
        $user = auth()->user();
        if ($order->pay_status == AgentOrder::UNPAIDSTATUS) return $this->failure("订单未支付");
        if ($order->pay_status == AgentOrder::REFUNDSTATUS) return $this->failure("订单已退款");
        //可退金额
        $refund_fee = AgentRefundOrder::where('trade_no', $order->trade_no)->where("is_hook", 1)->sum('refund_fee');
        $amount = number_format($order->price - $refund_fee, 2, '.','');
        if($request->price > $amount) return $this->failure("退款金额大于最大可退款金额");
        $refund_trade_no = CommonService::getTradeNO();
        $total_amount = $order->price;
        $refund_amount = $request->price;
        $callback = config("app.url").'/api/admin/agent/order/'.$refund_trade_no.'/refund/callback';
        AgentRefundOrder::create([
            'order_id'=>$order->id,
            'admin_id'=>$user->id,
            'trade_no'=>$order->trade_no,
            'refund_trade_no'=>$refund_trade_no,
            'total_fee'=>$order->price,
            'refund_fee'=>$refund_amount,
            'is_hook'=>0,
            'remark'=>$request->remark,
        ]);
        //生成退款订单
        WechatService::refund($order->trade_no, $refund_trade_no, $total_amount, $refund_amount, $callback, $order->sub_mch_id);
        return $this->success('ok');
    }

    public function refundOrders(Request $request, AgentOrder $order)
    {
        $orders = ShopRefundOrder::with('admin:id,name,mobile')->where('order_id', $order->id)->orderByDesc("id")->paginate();
        return $this->success('ok', $orders);
    }


    public function contractOrder(Request $request, $order_id)
    {
//        $param = $request->all();
//        $url = config('app.shop_url')."admin/contract/agent/orders/{$order_id}";
//        $res = $this->postData($url, $param);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $order = AgentOrder::find($order_id);
        if ($request->has("contract_id") && $request->contract_id != $order->contract_id)
        {
            $order->contract_id = $request->contract_id;
        }
        $order->save();
        return $this->success("ok");
    }

    public function agentStocks(Request $request)
    {
        $params = $request->all();
        $param =  http_build_query($params);
        $url = config('app.shop_url')."admin/agent/stocks?$param";
        $res = $this->getData($url);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        if (isset($params['export']) && $params['export']) {

            return Excel::download(new AgentStocksExport($data), '提取记录.xlsx');
        }
        return $this->success('ok', $data);
    }

    public function confirmStock(Request $request, $stock_id)
    {
        $param = $request->all();
        $url = config('app.shop_url')."admin/confirm/agent/stocks/$stock_id";
        $res = $this->postData($url, $param);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        return $this->success('ok', $data);
    }

    public function agentEarnings(Request $request)
    {
//        $params = $request->all();
//        $param =  http_build_query($params);
//        $url = config('app.shop_url')."admin/agent/earnings?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        if (isset($params['export']) && $params['export']) {
//
//            return Excel::download(new AgentEarningsExport($data), '分销记录.xlsx');
//        }
//        return $this->success('ok', $data);
        $user_id = $request->input('user_id');
        $earnings = AgentEarning::with('user:id,name,mobile,avatar', 'shop:id,title,icon')->user($user_id)->orderByDesc("id");
        if ($request->export) {
            $earnings = $earnings->get();
            return Excel::download(new AgentEarningsExport($earnings), '分销记录.xlsx');
        }else {
            $earnings = $earnings->paginate();
        }
        return $this->success('ok', $earnings);
    }

    public function agentWithdraws(Request $request)
    {
//        $params = $request->all();
//        $param =  http_build_query($params);
//        $url = config('app.shop_url')."admin/agent/withdraws?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        if (isset($params['export']) && $params['export']) {
//            return Excel::download(new AgentWithdrawsExport($data), '提现记录.xlsx');
//        }
//        return $this->success('ok', $data);

        $user_id = $request->user_id;
        $withdraws = AgentWithdraw::with('user:id,name,mobile,avatar')->user($user_id)->status($request->status)->orderByDesc('id')->orderByDesc("id");
        if ($request->export) {
            $withdraws = $withdraws->get();
            return Excel::download(new AgentWithdrawsExport($withdraws), '提现记录.xlsx');
        }else {
            $withdraws = $withdraws->paginate();
        }
        return $this->success('ok', $withdraws);
    }

    public function confirmWithdraw(Request $request, $withdraw_id)
    {
//        $param = $request->all();
//        $url = config('app.shop_url')."admin/confirm/agent/withdraws/$withdraw_id";
//        $res = $this->postData($url, $param);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $data = $request->all();
        $withdraw = AgentWithdraw::find($withdraw_id);
        $withdraw->update($data);
        return $this->success('ok');
    }

    public function agentLottoCodes(Request $request)
    {
//        $params = $request->all();
//        $param =  http_build_query($params);
//        $url = config('app.shop_url')."admin/agent/lotto/codes?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        if (isset($params['export']) && $params['export']) {
//            return Excel::download(new AgentLottoCodesExport($data), '抽奖码记录.xlsx');
//        }
//        return $this->success('ok', $data);

        $user_id = $request->user_id;
        $codes = LottoCode::with('order:id,shop_info','user:id,name,mobile,avatar')->user($user_id)->orderByDesc("id");
        if ($request->export) {
            $codes = $codes->get();
            return Excel::download(new AgentLottoCodesExport($codes), '抽奖码记录.xlsx');
        }else {
            $codes = $codes->paginate();
        }
        return $this->success('ok', $codes);
    }

    public function agentUsers(Request $request)
    {
//        $params = $request->all();
//        $param =  http_build_query($params);
//        $url = config('app.shop_url')."admin/agent/users?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $agent_users = $data = $res['data'];
//        if (!$request->export && $request->nopage) {
//            $agent_users = $data['data'];
//        }
        $users = AgentUser::whereHas("user")->whereHas("officialWechat")->with('recommendUser','user', 'officialWechat','wechat')->withCount('activityOrders as activity_count', 'introduceActivityOrders as introduce_activity_count', 'agentOrders as order_count')->withCount(["activityOrders as residue_amount"=>function($sql) {
            $sql->select(DB::raw("sum(residue_amount) as residue_amount"));
        }])->orderByDesc('id');
        $keyword = $request->keyword;
        if ($keyword) {
            $users = $users->whereHas('user', function ($sql) use($keyword) {
                $sql->where("name", 'like', "%$keyword%")
                    ->orWhere("mobile", 'like', "%$keyword%");
            });
        }
        $level = $request->input('level');
        if (is_numeric($level)) {
            $users = $users->where("level", $level);
        }
        if ($request->export || $request->nopage) {
            $users = $users->get();
        }else {
            $users = $users->paginate();
        }
        foreach ($users as $user) {
            if ($user->officialWechat && $user->wechat) {
                $user->agent_type = "mp/oa";
            }elseif ($user->officialWechat && !$user->wechat) {
                $user->agent_type = "oa";
            }elseif (!$user->officialWechat && $user->wechat) {
                $user->agent_type = "mp";
            }else {
                $user->agent_type = null;
            }
            //活動余额
            $user->residue_amount =  $user->residue_amount?:0;
            //小程序账号
            $mp_user = User::with('agentUser')->whereNotNull('mobile')->where('mobile', $user->user->mobile)->whereHas("wechat")->first();
//            dd($user);
            if($mp_user) {
                $mp_user->level = $mp_user->agentUser->level??0;
                unset($mp_user->agentUser);
            }
            $user->mp_user = $mp_user;

        }
        if ($request->export) {
            return Excel::download(new AgentUsersExport($users), '代理商列表.xlsx');
        }
        return $this->success('ok', $users);
    }

    public function agentUserDetail($id){
        $users = AgentUser::whereHas("user")
            ->with('recommendUser','user', 'officialWechat','wechat')
            ->where('id',$id)->first();
        if(isset($users->user)){
//            $users->residue_amount = ActivityOrder::where('user_id',$users->user->id)->sum('residue_amount');
            $users->residue_amount = ActivityOrderLog::where('user_id',$users->user->id)->sum('amount');
        }
        return $this->success('ok', $users);
    }

    public function storeAgentUsers(Request $request)
    {
        $data = $request->all();
        $mobile_user = User::where('mobile', $data['mobile'])->first();
        if (empty($mobile_user)) {
            $mobile_user = User::create(['mobile'=>$data['mobile'],'source'=>User::SOURCE_H5]);
            //关联特定openid(虚拟)
            Wechat::create(['user_id'=>$mobile_user->id, 'type'=>Wechat::TYPE_OFFICIAL, 'openid'=>Wechat::getVirtualOpenid()]);
        }else {
            if (!$mobile_user->officialWechat) {
                //关联特定openid(虚拟)
                Wechat::create(['user_id'=>$mobile_user->id, 'type'=>Wechat::TYPE_OFFICIAL, 'openid'=>Wechat::getVirtualOpenid()]);
            }
        }
        $mobile_user->update($data);
        $agent_user = AgentUser::where(['user_id'=>$mobile_user->id])->first();
        if(empty($agent_user)) {
            $admin = auth()->user();
            AgentUser::changeLevel($mobile_user->id, $data['level']??AgentUser::AgentLevelNot, "管理员【{$admin->name}】后台增加批发商");

        }
        return $this->success('ok', $mobile_user);
    }

    public function updateAgentUsers(Request $request, $id)
    {
        $form_user_id = $request->input('from_user_id');
        $user = User::find($id);
        if ($form_user_id) {
            $user->recommendUserLog()->updateOrCreate(['user_id'=>$id],['recommend_user_id'=>$form_user_id]);
        }
        $level = $request->level;
        if (is_numeric($level)) {
            $admin = auth()->user();
            //批发商用户
            AgentUser::changeLevel($id, $level, "管理员【{$admin->name}】后台修改等级", true);
        }
        return $this->success('ok');
    }

    public function addAgentUserSharer(Request $request, $agent_user_id)
    {
        $params = $request->all();
        $url = config('app.shop_url')."admin/change/agent/users/{$agent_user_id}/sharer";
        $res = $this->postData($url, $params);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        return $this->success('ok',$data);
    }

    public function addAgentOrderSharer(Request $request, $order_id)
    {
//        $params = $request->all();
//        $url = config('app.shop_url')."admin/agent/orders/{$order_id}/sharer";
//        $res = $this->postData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok',$data);

        $order = AgentOrder::find($order_id);
        $user_id = $request->input('user_id');
        $amount = $request->input("amount");
        AgentOrderShare::create([
            'user_id'=>$user_id,
            'order_id'=>$order_id,
            'trade_no'=>$order->trade_no,
            'amount'=>$amount,
            'status'=>"APPLY",
        ]);
        return $this->success('ok');

    }

    public function addShopOrderSharer(Request $request, ShopOrder $order)
    {
        $user_id = $request->input('user_id');
        $amount = $request->input("amount");
        ShopOrderShare::create([
            'user_id'=>$user_id,
            'order_id'=>$order->id,
            'trade_no'=>$order->trade_no,
            'amount'=>$amount,
            'status'=>"APPLY",
        ]);
        return $this->success('ok');

    }


    public function updateAgentOrderSharer(Request $request, $share_id)
    {
//        $commission = PartnerCommission::where("type", 1)->where('order_id', $share_id)->first();
//        if ($commission && in_array($commission->status, [1,2,5])) return $this->failure("当前状态不允许修改");
//        $params = $request->all();
//        $url = config('app.shop_url')."admin/agent/orders/sharers/{$share_id}";
//        $res = $this->putData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok',$data);
        $share = AgentOrderShare::find($share_id);
        $user_id = $request->input('user_id');
        $amount = $request->input("amount");
        $share->user_id = $user_id;
        $share->amount = $amount;
        $share->save();
        return $this->success('ok');
    }

    public function updateShopOrderSharer(Request $request, $share_id)
    {
        $share = ShopOrderShare::find($share_id);
        $user_id = $request->input('user_id');
        $amount = $request->input("amount");
        $share->user_id = $user_id;
        $share->amount = $amount;
        $share->save();
        return $this->success('ok');
    }

    public function agentOrderSharers(Request $request, $order_id)
    {
//        $url = config('app.shop_url')."admin/agent/orders/{$order_id}/sharers";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $sharers = $res['data'];
//        foreach ($sharers as &$sharer)
//        {
////            $sharer['commission'] = PartnerCommission::where("type", 1)->where('order_id', $sharer['id'])->first();
//            $sharer['status'] = $this->getAgentOrderShareStatus($sharer);
//        }
//        return $this->success('ok',$sharers);
        $logs = AgentOrderShare::where('order_id', $order_id)->with('user:id,name,mobile,avatar')->orderByDesc('id')->get();
        foreach ($logs as $log)
        {
            $log['status'] = $this->getAgentOrderShareStatus($log);
        }
        return $this->success('ok',$logs);
    }

    public function shopOrderSharers(Request $request, ShopOrder $order)
    {
        $logs = ShopOrderShare::where('order_id', $order->id)->with('user:id,name,mobile,avatar')->orderByDesc('id')->get();
        foreach ($logs as $log)
        {
            $log['status'] = $this->getAgentOrderShareStatus($log);
        }
        return $this->success('ok',$logs);
    }

    public function getAgentOrderShareStatus($sharer)
    {
        if ($sharer['status'] == 'APPLY' || $sharer['status'] == 'AUDIT' || $sharer['status'] == 'CONFUSE') { //未审核、已拒绝
            return $sharer['status'];
        }
        $commission = PartnerCommission::where("type", 1)->where('order_no', $sharer->trade_no)->where('order_id', $sharer['id'])->first();
        if($commission){
            if ($commission->status ==0) return 'REVIEW';
            if ($commission->status ==3) return 'CONFUSE';
        }
        return "SUCCESS";
    }

    public function deleteAgentOrderSharer(Request $request, $share_id)
    {
//        $params = $request->all();
//        $url = config('app.shop_url')."admin/agent/orders/sharer/{$share_id}";
//        $res = $this->deleteData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok',$data);
        $share = AgentOrderShare::find($share_id);
        $share->delete();
        return $this->success('ok');
    }

    public function deleteShopOrderSharer(Request $request, $share_id)
    {
        $share = ShopOrderShare::find($share_id);
        $share->delete();
        return $this->success('ok');
    }

    public function applyAgentOrderSharer(Request $request, $share_id)
    {
//        $params = $request->all();
//        $url = config('app.shop_url')."admin/apply/agent/orders/sharers/{$share_id}";
//        $res = $this->postData($url, $params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $sharers = $res['data'];
//        return $this->success('ok', $sharers);
        $share = AgentOrderShare::find($share_id);
        $share->update(['status'=>"AUDIT"]);
        return $this->success('ok',$share);

    }

    public function applyShopOrderSharer(Request $request, $share_id)
    {
        $share = ShopOrderShare::find($share_id);
        $share->update(['status'=>"AUDIT"]);
        return $this->success('ok',$share);

    }

    public function agentOrdersSharers(Request $request)
    {
//        $params = $request->all();
//        $param =  http_build_query($params);
//        $url = config('app.shop_url')."admin/agent/order/sharers?{$param}";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $sharers = $res['data'];
//        return $this->success('ok', $sharers);
        $logs = AgentOrderShare::status()->with('user:id,name,mobile,avatar')->orderByDesc('id');
        $export = $request->input('export');
        if ($export) {
            $logs = $logs->get();
            return Excel::download(new OrderSharesExport($logs), '分润.xlsx');
        }
        $logs = $logs->paginate();
        return $this->success('ok',$logs);
    }

    public function shopOrdersSharers(Request $request)
    {
        $logs = ShopOrderShare::status()->with('user:id,name,mobile,avatar')->orderByDesc('id');
        $export = $request->input('export');
        if ($export) {
            $logs = $logs->get();
            return Excel::download(new OrderSharesExport($logs), '分润.xlsx');
        }
        $logs = $logs->paginate();

        return $this->success('ok',$logs);
    }

    public function auditAgentOrderSharer(Request $request, $share_id)
    {
//        $params = $request->all();
//        $url = config('app.shop_url')."admin/audit/agent/orders/sharers/{$share_id}";
//        $res = $this->postData($url,$params);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
        $share = AgentOrderShare::find($share_id);
        $status = $request->status;
        $reason = $request->reason;
        $share->update(['status'=>$status, 'reason'=>$reason]);
        if ($status == 'AGREE'){
            PartnerCommission::create([
                'order_id'=>$share_id,
                'order_no'=>$share->trade_no,
                'order_commission_id'=>$share->order_id.$share->trade_no,
                'user_id'=>$share->user_id,
                'role'=>1,
                'amount'=>$share->amount,
                'status'=>0,
                'unfreeze_time'=>null,
                'withdrawal_id'=>null,
                'type'=>1,
            ]);
        }
        return $this->success('ok');
    }

    public function auditShopOrderSharer(Request $request, $share_id)
    {
        $share = ShopOrderShare::find($share_id);
        $status = $request->status;
        $reason = $request->reason;
        $share->update(['status'=>$status, 'reason'=>$reason]);
        if ($status == 'AGREE'){
            PartnerCommission::create([
                'order_id'=>$share_id,
                'order_no'=>$share->trade_no,
                'order_commission_id'=>$share->order_id.$share->trade_no,
                'user_id'=>$share->user_id,
                'role'=>1,
                'amount'=>$share->amount,
                'status'=>0,
                'unfreeze_time'=>null,
                'withdrawal_id'=>null,
                'type'=>1,
            ]);
        }
        return $this->success('ok');
    }

    /**
     * @param AgentUser $user 批发商
     * @param Request $request
     */
    public function logs(Request $request, AgentUser $user)
    {
        $logs = AgentUserLog::where("user_id", $user->user_id)->orderByDesc("id")->get();
        return $this->success('ok', $logs);
    }

}
