<?php
namespace app\api\controller\h5;

use app\hander\HelpHander;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;
use think\Exception;

class PhOrders extends Base
{
    //订单列表
    public function orderList(){
        $page = input('page',1);
        $size = input('size',10);
        $status = input('status/d',-1);
        $model = new \app\common\model\PhOrders();
        $res = $model->orderList($this->orgId,$status,$page,$size,$this->userId);
        HelpHander::success($res,'操作成功');

    }
    //订单详情
    public function detail(){
        $id = input('id/d','');
        $model = new \app\common\model\PhOrders();
        $ret = $model->getInfo($id);
        HelpHander::success($ret,'操作成功');
    }

    public function getWorkerAll(){
        $model = new \app\common\model\Worker();
        $ret = $model->getAllByOrg($this->orgId);
        HelpHander::success($ret,'成功');
    }

    // 存入预付款
    public function payOrder(){
        $orderId = input('orderId/d',0);
        $money = input('money/f',0);
        if($money <= 0){
            HelpHander::error('输入金额错误');
        }

        $payId = model('PhOrderPay')->addSave($this->userId,$this->orgId,$orderId,$money);
        if(!$payId){
            HelpHander::error(model('PhOrderPay')->getError());
        }
        HelpHander::success(['pay_id' => $payId],'操作成功');
    }

    // 根据支付id获取支付参数
    public function pay(){
        $payId = input('payId/d',0);
        $info = Db::name('ph_order_pay')->where('id',$payId)->where('status',0)->find();
        if(!$info){
            HelpHander::error('订单不存在');
        }
        $config = config('app.wx_config');
        $notify = request()->domain().'/api/h5/notify/phorder';
        try{
            $openid = Db::name('wxuser')->where('id',$this->userId)->where('type',1)->value('openid');
            $app = Factory::payment($config);
            $result = $app->order->unify([
                'body' => '预付款',
                'out_trade_no' => $info['sn'],
                'total_fee' => $info['money']*100,
                'notify_url' => $notify, // 支付结果通知网址,如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $openid,
            ]);

            if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS'){
                \exception(json_encode($result));
            }

            $jssdk = $app->jssdk;
            $ret = $jssdk->sdkConfig($result['prepay_id']); // 返回数组
            trace($ret);
        }catch (\Exception $e){
            trace($e->getMessage());
            HelpHander::error('获取参数失败');
        }

        HelpHander::success($ret,'成功');
    }


}