<?php

namespace app\admin\controller\app;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use WpOrg\Requests\Requests;

/**
 * @ControllerAnnotation(title="app_order")
 */
class Order extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\AppOrder();
        
    }

    /**
     * @NodeAnotation(title="查看")
     */
    public function edit($id)
    {
        $row = Db::table('app_order')
            ->alias('o')
            ->join(['app_member' => 'm'], 'o.uid=m.uid', 'left')
            ->where(['id'=>$id])->find();
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 补单
     */
    public function budan($id){
        if($this->request->isPost()){
            $orderModel = Db::table('app_order');
            $orderInfo = $orderModel->where(['status'=>1])->find($id);
            if(!$orderInfo){
                $this->error('订单状态异常，无法补单');
            }
            // 通过下单的 appid 找到游戏配置
            $gamesInfo = Db::table('app_games_config')->where(['app_id'=>$orderInfo['appid']])->find();
            if(!$gamesInfo){
                $this->error('游戏配置没找到！');
            }
            // 组装post参数，并签名
            $params = [
                'order_id' => $orderInfo['order_id'],
                'good_name' => $orderInfo['subject'],
                'cp_order_id' => $orderInfo['cp_order_id'],
                'uid' => $orderInfo['uid'],
                'money' => $orderInfo['money'],
                'app_id' => $orderInfo['appid'],
                'service_id' => $orderInfo['server_id'],
                'service_name' => $orderInfo['server_name'],
                'role_id' => $orderInfo['role_id'],
                'role_name' => $orderInfo['role_name'],
                'time' => time(),
                'pay_status' => $orderInfo['status'],
                'extend' => $orderInfo['extra_info'],
            ];
            ksort($params);
            $signStr = http_build_query($params)."&paykey=".$gamesInfo['paykey'];
            $params['sign'] = md5($signStr);
            $response = Requests::post($gamesInfo['send_url'],['Accept' => 'application/json'],$params)->body;
            //$response = '{"code": 200,"message": "发货成功"}';
                // 添加补单记录
            $orderModel->where(['id'=>$id])->update(['wap_number'=>Db::raw('wap_number+1')]);
            $response_arr = json_decode($response,true);
            if($response_arr['code'] === 200){
                $orderModel->where(['id'=>$id])->update(['gstatus'=>1]);
                $this->success('补单成功！');
            }
            $orderModel->where(['id'=>$id])->update(['gstatus'=>2]);
            $this->error("补单失败！返回：{$response}");
        }
    }

    
}
