<?php

namespace app\api\controller;



use app\common\controller\Api;
use app\common\model\hu\Goods;
use app\common\model\hu\OrderGoods;
use app\common\model\hu\UserInvite;

use app\common\model\unishop\OrderExtend;
use app\common\model\unishop\Product;
use app\common\model\unishop\Address;
use app\common\model\unishop\OrderProduct;
use app\common\model\unishop\WholesaleGoods;
use think\Db;
use think\Exception;
use think\Log;

class Order extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';
    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\unishop\Order();
    }

    /**
     * 用户下单-开发调试
     * @return void
     */
    public function pay()
    {
        try {



            $params = $this->request->param();
            $user_id = $this->auth->id;
            $order_sn =  getOrderSn();
            //商品信息
//            $params['goods_info'] = json_decode($params['goods_info'],true);
            $params['goods_info'] = [
                [
                    'goods_id'=>12,
                    'buy_number'=>1
                ],
                [
                    'goods_id'=>13,
                    'buy_number'=>2
                ],

            ];
            $pay_price = 0;
            $product_model = new Product();
            if(!empty($params['goods_info'])){
                foreach ($params['goods_info'] as $key=>$val){
                    //计算价格
                   $zj = $product_model->computePrice($val['goods_id'],$val['buy_number']);
                   $pay_price = $pay_price + $zj;

                }
            }else{
                $this->error("订单信息有误");
            }

            $address_id = isset($params['address_id'])?$params['address_id']:0;
            if($address_id == 0){
                $address_model = new Address();
                //使用默认地址
                $address_id =$address_model->where('user_id',$user_id)->where('is_default',1)->value('id');
                if(empty($address_id)){
                    $this->error("缺少收货地址信息");
                }
            }

            //插入订单表
            $data['out_trade_no'] = $order_sn;
            $data['user_id'] = $user_id;
            $data['order_price'] = $pay_price;
            $data['total_price'] = $pay_price;//实付价格
            $data['ip'] = getip();
            $data['remark'] = "用户下单";
            $data['createtime'] = time();
            $data['updatetime'] = time();
            $order_id = $this->model->insertGetID($data);
            if(!$order_id){
                $this->error('下单失败');
            }

            //插入订单商品表
            $OrderProduct_model = new OrderProduct();
            $order_goods_add = $OrderProduct_model->add($params['goods_info'],$user_id,$order_id);
            if(!$order_goods_add){
                $this->error('下单失败');
            }

            $coupon_id = isset($params['coupon_id'])?$params['coupon_id']:'0';
            $delivery_id = isset($params['delivery_id'])?$params['delivery_id']:'0';
            //插入订单扩展表
            $orderExtend_model = new OrderExtend();
            $orderExtend_model_add = $orderExtend_model->add($user_id,$order_id,$coupon_id,$delivery_id,$address_id);

            if($orderExtend_model_add){
                $this->success('下单成功');
            }else{
                $this->error('下单失败');
            }

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 模拟支付回调
     * @return void
     */
    public function notify(){

        try {

            //省略验证
            $order_sn = $this->request->param('order_sn');

            $order_info = $this->model->where('out_trade_no',$order_sn)->find();
            if(empty($order_info)){
                $this->error("订单信息有误");
            }

            if($order_info['status'] !='1'){
                $this->error("订单信息有误");
            }

            if($order_info['have_paid'] != 0){
                $this->error("订单信息有误");
            }
            //开启事务
            Db::startTrans();
            $upd = $this->model->where('out_trade_no',$order_sn)->update(['have_paid'=>1]);
            if($upd){

                //判断当前时间是否为配置中跳过的星期
                $not_time = Db::name("config")->where("name","not_time")->value("value");
                if(!empty($not_time)){
                    $not_time = explode(',',$not_time);
                    $day_week = weeks();
                    if(!in_array($day_week,$not_time)){
                        //成功 当前下单用户是否有上级  上上级
                        //上级
                        $UserInvite_model = new UserInvite();
                        $list_one = $UserInvite_model->getUsetInviteOne($order_info['user_id']);

                        //增加抽成
                        $invite_one = Db::name("config")->where('name','invite_one')->value('value');
                        $user_model = new \app\common\model\User();
                        if(!empty($list_one)){
                            foreach ($list_one as $k=>$val){
                                //计算佣金
                                $commission = $this->model->computeCommission($order_info['total_price'],$invite_one);
                                //增加佣金和流水日志

                                if(!empty($val['invite_id'])){
                                    $add_one = $user_model->userAddMoney($commission,$val['invite_id'],"直推分佣所得");
                                    if(!$add_one){
                                        //写入失败 写入记录日志
                                        Logs('订单号为:'.$order_info['out_trade_no'].'增加上级佣金失败','order_err');
                                        Db::rollback();
                                        $this->error("增加上级分佣失败");
                                    }
                                }
                            }
                        }
                        //上上级
                        $list_one_top = $UserInvite_model->getUsetInviteOneTop($order_info['user_id']);
                        $invite_two = Db::name("config")->where('name','invite_two')->value('value');
                        if(!empty($list_one_top)){
                            foreach ($list_one_top as $key=>$value){
                                //计算佣金
                                $commission = $this->model->computeCommission($order_info['total_price'],$invite_two);
                                //增加佣金和流水日志

                                if(!empty($value['top_id'])){
                                    $add_one_two = $user_model->userAddMoney($commission,$value['top_id'],"二级分佣所得");
                                    if(!$add_one_two){
                                        //写入失败 写入记录日志
                                        Logs('订单号为:'.$order_info['out_trade_no'].'增加上级佣金失败','order_err');
                                        Db::rollback();
                                        $this->error("增加上上级分佣失败");
                                    }
                                }

                            }
                        }
                        //更改订单的结算状态
                        $giveaway = $this->model->where('out_trade_no',$order_sn)->update(['is_giveaway'=>2,'updatetime'=>time()]);
                        if(!$giveaway){
                            Db::rollback();
                            $this->error("更改订单的结算状态失败");
                        }
                    }
                }

                //生成批发商品
                $wholesaleGoods_model = new WholesaleGoods();
                $wholesaleGoods_add = $wholesaleGoods_model->add($order_info['user_id'],$order_info['id']);
                if(!$wholesaleGoods_add){
                    //写入失败 写入记录日志
                    Logs('订单号为:'.$order_info['out_trade_no'].'增加批发商品失败','order_err');
                    Db::rollback();
                    $this->error("增加批发商品失败");
                }
            }else{
                Db::rollback();
                $this->error("更新支付状态失败");
            }

            Db::commit();
            $this->success("更新支付状态成功");
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

}