<?php
namespace app\common\model;

use think\Db;
use EasyWeChat\Factory;

class GOrders extends Base
{

    public function add($cart_Id,$addressId,$userId,$orgId,$delivery_type,$delivery_date){
        $addressInfo=Db::name('shop_address')->where('id',$addressId)->find();
        if(!$addressInfo){
            $this->error = "未选择地址";
            return false;
        }
        $newDate = strtotime(date('Y-m-d H:i:s'))-60*5;
        if($delivery_type==1){
            if(empty($delivery_date)){
                $this->error = "送货时间不能为空";
                return false;
            }
            if($delivery_date < date('Y-m-d H:i:s',$newDate)){
                $this->error = "送货时间不能小于当前时间";
                return false;
            }
        }
        $map[]=['c.user_id','=',$userId];
        $map[]=['c.id','in',$cart_Id];
        $map[]=['g.enable','=',1];
        $map[]=['g.del','=',0];

        $goodsInfo=Db::name('g_cart')
            ->alias('c')
            ->join('g_goods g','c.goods_id=g.id')
            ->field('c.nums,g.id,g.title,g.price,g.sale_price,g.type,g.stock')
            ->where($map)
            ->select();
        if(!$goodsInfo){
            $this->error = "未选择商品";
            return false;
        }
        foreach ($goodsInfo as $k=>$v){
            if($v['type'] == 1){
                $goodsInfo[$k]['price']=$v['sale_price'];
            }
            if($v['stock'] < $v['nums']){
                $this->error = "库存不足";
                return false;
            }
        }
        $totalPrice=0;
        foreach ($goodsInfo as $k=>$v){
            $sum=$v['nums'] * $v['price'];
            $totalPrice+=$sum;
        }
        Db::startTrans();
        try {
            $data=[
                'order_sn'=>get_unique_id(),
                'org_id'=>$orgId,
                'user_id'=>$userId,
                'amount'=>round($totalPrice,2),
                'status'=>0,
                'create_time'=>date('Y-m-d H:i:s'),
                'name'=>$addressInfo['name'],
                'phone'=>$addressInfo['phone'],
                'delivery_type'=>$delivery_type,
                'delivery_date'=>$delivery_date,
                'address'=>$addressInfo['content'],
                'aid' => $addressId
            ];
            if($delivery_type==0){
                unset($data['delivery_date']);
            }
            $addOrder=Db::name('g_orders')->insertGetId($data);
            if(!$addOrder){
                exception('操作失败');
            }
            foreach ($goodsInfo as $kay=>$val){
                $gdata=[
                    'order_id'=>$addOrder,
                    'goods_id'=>$val['id'],
                    'nums'=>$val['nums'],
                    'price'=>$val['price'],
                    'type'=>$val['type'],
                ];
                $addOrderGoods=Db::name('g_order_goods')->insert($gdata);
                if(!$addOrderGoods){
                    exception('操作失败');
                }
                 //减少库存
                 $dec= Db::name('g_goods')
                    ->where('id',$val['id'])
                    ->dec('stock', $val['nums'])
                    ->update();
                if(!$dec){
                    exception('操作失败');
                }
            }
            //删除用户购物车信息
            $delCart=Db::name('g_cart')->where('user_id',$userId)->whereIn('id',$cart_Id)->delete();
            if(!$delCart){
                exception('操作失败');
            }

            Db::commit();
            return $addOrder;
        } catch (\Exception $e) {
            // 回滚事务
            $this->error = $e->getMessage();
            Db::rollback();
            return false;
        }
    }
    public function addOne($goodsId,$addressId,$nums,$userId,$orgId,$delivery_type,$delivery_date){
        $addressInfo=Db::name('shop_address')->where('id',$addressId)->find();
        if(!$addressInfo){
            $this->error = "未选择地址";
            return false;
        }
        $newDate = strtotime(date('Y-m-d H:i:s'))-60*5;
        if($delivery_type==1){
            if(empty($delivery_date)){
                $this->error = "送货时间不能为空";
                return false;
            }
            if($delivery_date < date('Y-m-d H:i:s',$newDate)){
                $this->error = "送货时间不能小于当前时间";
                return false;
            }
        }
        $map[]=['id','=',$goodsId];
        $map[]=['enable','=',1];
        $map[]=['del','=',0];
        $goodsInfo=Db::name('g_goods')->where($map)->find();
        if(!$goodsInfo){
            $this->error = "未选择商品";
            return false;
        }
        if($goodsInfo['stock'] < $nums){
            $this->error = "库存不足";
            return false;
        }
        if($goodsInfo['type']==1){
            $goodsInfo['price']=$goodsInfo['sale_price'];
        }
        unset($goodsInfo['sale_price']);

        Db::startTrans();
        try {
            $data=[
                'order_sn'=>get_unique_id(),
                'org_id'=>$orgId,
                'user_id'=>$userId,
                'amount'=>round($goodsInfo['price'] * $nums,2),
                'status'=>0,
                'create_time'=>date('Y-m-d H:i:s'),
                'name'=>$addressInfo['name'],
                'phone'=>$addressInfo['phone'],
                'address'=>$addressInfo['content'],
                'aid' => $addressId,
                'delivery_type'=>$delivery_type,
                'delivery_date'=>$delivery_date,
            ];
            if($delivery_type==0){
                unset($data['delivery_date']);
            }
            $addOrder=Db::name('g_orders')->insertGetId($data);
            if(!$addOrder){
                exception('操作失败');
            }
            $gdata=[
                'order_id'=>$addOrder,
                'goods_id'=>$goodsInfo['id'],
                'nums'=>$nums,
                'price'=>$goodsInfo['price'],
                'type'=>$goodsInfo['type'],
            ];
            $addOrderGoods=Db::name('g_order_goods')->insert($gdata);
            if(!$addOrderGoods){
                exception('操作失败');
            }
            //减少库存
            $dec = Db::name('g_goods')
                ->where('id',$goodsInfo['id'])
                ->dec('stock', $nums)
                ->update();
            if(!$dec){
                exception('操作失败');
            }

            Db::commit();
            return $addOrder;
        } catch (\Exception $e) {
            // 回滚事务
            $this->error = $e->getMessage();
            Db::rollback();
            return false;
        }
    }
    public function lists($page,$size,$userId,$orgId){
        $map[]=['user_id','=',$userId];
        $map[]=['org_id','=',$orgId];
        $ret=Db::name('g_orders')
            ->field('id,status,amount')
            ->where($map)
            ->order('id','desc')
            ->page($page,$size)
            ->select();
        foreach ($ret as $k=>$v){
            $orderGoods=Db::name('g_order_goods')
                ->alias('og')
                ->field('og.nums,og.price,og.goods_id,g.title,g.img')
                ->join('g_goods g','g.id=og.goods_id')
                ->where('og.order_id',$v['id'])
                ->select();
            $nums=0;
            foreach ($orderGoods as $kk=>$vv){
                $nums+=$vv['nums'];
            }
            $ret[$k]['num']=$nums;
            $ret[$k]['order_goods']=$orderGoods;
        }
        return $ret?$ret:[];
    }
    public function details($ordersId){
        $ret = Db::name('g_orders')->where('id', $ordersId)->find();
        $ret['goods'] = Db::name('g_order_goods')
            ->alias('og')
            ->field('og.nums,og.price,og.goods_id,g.title,g.img')
            ->join('g_goods g', 'g.id=og.goods_id')
            ->where('og.order_id', $ret['id'])
            ->select();
        $nums=0;
        foreach ($ret['goods'] as $k=>$v){
            $nums+=$v['nums'];
        }
        $ret['sum']=$nums;

        return $ret;
    }
    public function accomplish($ordersId){
        $data=[
            'status'=>2,
            'finish_time'=>date('Y-m-d H:i:s'),
        ];
        $ret = Db::name('g_orders')->where('id', $ordersId)->update($data);
        return $ret;
    }

    public function refundOrder($userId){
        $data = [
            'money' => input('money/f',0),
            'order_id' => input('id/d',0),
            'user_id' => $userId,
            'remark' => input('remark','','trim'),
            'create_time' => date('Y-m-d H:i:s'),
        ];
        if($data['money'] <= 0){
            $this->error = '金额必须大于0';
            return false;
        }
        $pay = Db::name('g_orders')
            ->where('id',$data['order_id'])->find();
        if(!$pay||$pay['status'] != 1){
            $this->error = '订单不存在';
            return false;
        }
        $data['sn'] = get_unique_id('TPH');
        $data['org_id'] = $pay['org_id'];
        if($data['money'] > $pay['amount']){
            $this->error = '退款金额过大';
            return false;
        }

        Db::startTrans();
        try{

            $ret = Db::name('g_order_refund')->insert($data);
            if(!$ret){
                \exception('操作失败');
            }
            $order = Db::name('g_orders')
                ->where('id',$pay['id'])
                ->lock(true)
                ->find();
            if(!$order){
                \exception('订单不存在');
            }

            $ret = Db::name('g_orders')
                ->where('id',$pay['id'])->update([
                    'refund_money' => $data['money'],
                    'status' => 4
                ]);
            if(!$ret){
                \exception('操作失败');
            }

            $config = config('app.wx_config');
            $app = \EasyWeChat\Factory::payment($config);
            $ret = $app->refund->byOutTradeNumber($pay['order_sn'], $data['sn'], $pay['amount']*100, $data['money']*100);
            if($ret['return_code'] != 'SUCCESS' || $ret['result_code'] != 'SUCCESS'){
                \exception('退款申请提交失败');
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollback();
            trace($e->getMessage());
            $this->error = $e->getMessage();
            return false;
        }

    }
}