<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付接口
 */
namespace app\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisShopOrder;
use app\ais\model\AisBank;
use app\ais\model\AisShop;
use app\ais\model\AisConfig;
use app\ais\model\AisCouponUser;
use app\ais\model\AisVipUser;
use app\common\model\SystemUser;
use app\common\facade\WechatPay;
use app\common\model\SystemUserLevel;

class Shoppay extends Base{

    /**
     * 初始化当前应用是否登录
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }


    /**
     * 读取订单并支付
     * @param integer $id 商品ID
     * @return void
     */
    public function index(){
        $param['id'] = $this->request->param('id/d',0);
        $this->apiSign($param);
        //查找商品
        $item = AisShop::field('id,store_id,coupon_id,name,title,img,points_price,sell_price,vip_price,market_price,end_time')
                ->where(['is_sale'=>1,'id' => $param['id'],'member_miniapp_id' => $this->member_miniapp_id])->find();
        if(empty($item)){
            return enjson(403,'没有内容');
        }
        return enjson(200,AisShop::userPayPrice($item,$this->user->id));
    }

    /**
     * 下单发起支付或重新在支付
     */
    public function payment(){
        if (request()->isPost()) {
            $param['id']       = $this->request->param('id/d');
            $param['telphone'] = $this->request->param('telphone/s');
            $param['message']  = $this->request->param('message','');
            $param['ucode']    = $this->request->param('ucode','');
            $this->apiSign($param);
            $item = AisShop::where(['is_sale'=>1,'id' => $param['id'],'member_miniapp_id' => $this->member_miniapp_id])->find();
            if(empty($item)){
                return enjson(403,'商品已经下架');
            }
            if($item->warehouse_num <= 0){
                return enjson(403,'商品已售完');
            }
            $is_rest_payment = true;
            //读取订单
            $shop_order = AisShopOrder::where(['member_miniapp_id' => $this->member_miniapp_id,'uid' =>$this->user->id,'shop_id' => $item->id,'is_del' => 0])->find();
            $order_no   = order_no($this->user->invite_code);
            if(empty($shop_order)){
                $validate = $this->validate($param,'Dopay.shop');
                if (true !== $validate) {
                    return enjson(403,$validate);
                }
                $sell_price  = $item->sell_price;
            }else{
                if($shop_order->paid_at == 1 && $shop_order->status == 0){
                    return enjson(403,'本商品订单未核销,请先去商家核销');
                }
                if($shop_order->sell_price < $item->sell_price){
                    $shop_order->is_del = 1; //设置删除
                    return enjson(403,'订单已失效,请重新下单');
                }else{
                    $shop_order->order_no = $order_no;
                }
                $shop_order->save();
                $sell_price  = $shop_order->amount;
                $is_rest_payment = false;
            }
            //价格计算器
            $item = AisShop::userPayPrice($item,$this->user->id);
            //唤醒微信支付参数
            $payparm = [
                'openid'     => $this->user->miniapp_uid,
                'miniapp_id' => $this->member_miniapp_id,
                'name'       => $item->name,
                'order_no'   => $order_no,
                'attach'     => 'N',
                'total_fee'  => $item->amount <= 0 ? 1 : $item->amount * 100,
                'notify_url' => api(1, 'ais/notify/shop', $this->miniapp_id),
            ];
            if($this->member_miniapp->is_psp){
                if(empty($item->store->mch_id)){
                    $setting = AisConfig::getConfig($this->miniapp_id);
                    if (empty($setting->mchid)) {
                        return enjson(403,'服务商模式下,必须配置默认商户号');
                    }
                    $payparm['mchid'] = $setting->mchid;
                }else{
                    $level = SystemUserLevel::where(['user_id' => $this->user->id,'level' => 1])->find();
                    if(!empty($level) && $level->parent_id != $item->store->manage_uid){
                        $payparm['profit_sharing'] = 'Y';
                        $payparm['attach'] = 'Y';
                    }
                    if(!empty($param['ucode'])){
                        $payparm['profit_sharing'] = 'Y';
                        $payparm['attach'] = 'Y';
                    }
                    $payparm['mchid']  = $item->store->mch_id;
                }
            }
            $ispay = WechatPay::orderPay($payparm);
            if ($ispay['code'] == 0) {
                return enjson(403,$ispay['msg']);
            }
            //判断是否创建订单
            if($is_rest_payment){
                $param['uid']               = $this->user->id;
                $param['member_miniapp_id'] = $this->member_miniapp_id;
                $param['store_id']          = $item->store_id;
                $param['sell_price']        = $item->sell_price;
                $param['amount']            = $item->amount;
                $param['points']            = $item->user_point;
                $param['thrifty']           = $item->thrifty;
                $param['share_uid']         = SystemUser::isInvite($param['ucode']);
                $param['shop_cache']        = $item->toArray();
                AisShopOrder::createOrder($param,$order_no);
            }
            return enjson(200,$ispay['data']);
        }
    }
}