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

use app\hander\HelpHander;

use EasyWeChat\Factory;
use think\App;
use think\Db;
use think\Exception;
use app\api\controller\Base;

class WxOrders extends Base
{

    public function __construct(App $app = null) {
        parent::__construct($app);
//        $this->orgId = 3;


    }
    //订单结算页详情
    public function checkOrderDetail(){
        $type = input('type/d',0);
        $goodsId = input('goodsId/d',0);
        $cartId = input('cartId','');
        $num = input('num/d',0);
        $ids = [];
        if($type==0){
            if(empty($goodsId) || empty($num)){
                HelpHander::error('参数错误');
            }
            $ids[] = ['id'=>$goodsId,'num'=>$num];
        }else if($type==1){
            if(empty($cartId)){
                HelpHander::error('参数错误');
            }
            $gId = Db::name('wx_goods_cart')
                ->where('id','in',explode(',',$cartId))
                ->where('user_id',$this->userId)
                ->group('goods_id')
                ->select();

            foreach ($gId as $k=>$v){
                $ids[] = [
                    'id'=>$v['goods_id'],
                    'num'=>$v['nums'],
                ];
            }
        }
        $data = model('WxOrders')->formatOrder($ids);
        HelpHander::success($data,'操作成功');
    }

    public function create(){
        $type = input('type/d',0);
        $goodsId = input('goodsId/d',0);
        $cartId = input('cartId','');
        $addressId=input('addressId/d',0);
        $isHasBarrel=input('isHasBarrel/d',0);
        $deliveryDate=input('deliveryDate','');
        $deliveryType=input('deliveryType/d',1);
        $orderRemark=input('orderRemark','');
        $payType=input('payType/d',1);
        $num = input('num/d',0);
        if($this->orgId <= 0){
            HelpHander::error('参数错误');
        }
        $ret = model('WxOrders')->add($cartId,$addressId,$this->userId,$this->orgId,$type,$goodsId,$isHasBarrel,$deliveryDate,$deliveryType,$orderRemark,$payType,$num);
        if(!$ret){
            HelpHander::error(model('WxOrders')->getError());
        }
        HelpHander::success(['id'=>$ret],'操作成功');
    }



    //商城订单列表
    public function orderList(){
        $status=input('status/d',0);
        $page=input('page/d',1);
        $size=input('size/d',20);
        $ret = model('WxOrders')->lists($page,$size,$this->userId,$this->orgId,$status);
        HelpHander::success($ret);
    }

    //订单详情
    public function orderDetails(){
        $orderId=input('orderId/d',0);
        $ret = model('WxOrders')->details($orderId);
        HelpHander::success($ret);
    }

    //取消订单
    public function cancelOrder(){
        $id = input('id',0);
        $info = Db::name('wx_orders')
            ->where('id',$id)
            ->where('user_id',$this->userId)
            ->find();
        if(empty($info)){
            HelpHander::error('订单不存在');
        }
        if($info['status']!=0){
            HelpHander::error('订单已取消');
        }
        $data = [
            'status'=>4,
            'cancel_time'=>date('Y-m-d H:i:s')
        ];
        $ret = Db::name('wx_orders')->where('id',$id)->update($data);
        //取消订单添加库存
//        $orderGoods = Db::name('g_order_goods')
//            ->where('order_id',$id)
//            ->select();
//        foreach ($orderGoods as $k=>$v){
//            Db::name('g_goods')
//                ->where('id',$v['goods_id'])
//                ->inc('stock',$v['nums'])
//                ->update();
//        }
        if($ret){
            HelpHander::success([],'操作成功');
        }else{
            HelpHander::error('操作失败');
        }
    }
    public function confirmOrder(){
        $id = input('id',0);
        $info = Db::name('wx_orders')
            ->where('id',$id)
            ->where('user_id',$this->userId)
            ->find();
        if(empty($info)){
            HelpHander::error('订单不存在');
        }
        if($info['status']!=2){
            HelpHander::error('订单已确认');
        }
        $data = [
            'status'=>3,
            'finish_time'=>date('Y-m-d H:i:s')
        ];
        $ret = Db::name('wx_orders')->where('id',$id)->update($data);

        if($ret){
            HelpHander::success([],'操作成功');
        }else{
            HelpHander::error('操作失败');
        }
    }
    public function delOrder(){
        $id = input('id',0);
        $info = Db::name('wx_orders')
            ->where('id',$id)
            ->where('user_id',$this->userId)
            ->find();
        if(empty($info)){
            HelpHander::error('订单不存在');
        }
        if(!in_array($info['status'],[4,5,7])){
            HelpHander::error('订单状态不能删除');
        }
        $data = [
            'del'=>1,
            'del_time'=>date('Y-m-d H:i:s')
        ];
        $ret = Db::name('wx_orders')->where('id',$id)->update($data);

        if($ret){
            Db::name('wx_orders_refund')->where('order_id',$id)->update([
                'del'=>1
            ]);
            HelpHander::success([],'操作成功');
        }else{
            HelpHander::error('操作失败');
        }
    }
    //继续支付
    public function goPay(){
        $id = input('id',0);
        $order = Db::name('wx_orders')
            ->where('id',$id)
            ->where('status',0)->find();
        if(!$order){
            HelpHander::error('订单不存在');
        }
        $config = config('app.wx_mini_config');
        $notify = request()->domain().'/api/v1/notify/WxOrder';
        $openid = Db::name('wxuser')->where('id',$this->userId)->value('openid');

        $app = Factory::payment($config);

        $result = $app->order->unify([
            'body' => '订单-'.$order['order_sn'],
            'out_trade_no' => $order['order_sn'],
            'total_fee' => $order['amount']*100,
            'notify_url' => $notify, // 支付结果通知网址,如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $ret = $jssdk->bridgeConfig($result['prepay_id'],false); // 返回数组
            HelpHander::success($ret,'成功');
        }else{
            HelpHander::error($result['err_code_des']);
        }

    }

    public function refuse(){
        $id = input('id',0);
        $order = Db::name('g_orders')->where('id',$id)->find();
        if(!$order){
            HelpHander::error('订单不存在');
        }
        if($order['status']!=1 || time() > (strtotime($order['create_time'])+(30*24*3600))){
            HelpHander::error('当前订单不可退款');
        }
        $refund_money = input('refundMoney');
        $refund_remark = input('refundRemark','');
        if(empty($refund_money) ||$refund_money==0 ){
            HelpHander::error('请输入退款金额');
        }

        $data = [
            'money' =>0,
            'refund_money' =>$refund_money,
            'refund_remark' =>$refund_remark,
            'order_id' => $id,
            'user_id' => $this->userId,
            'org_id' => $this->orgId,
            'sn' => get_unique_id(),
            'from' =>1,
            'create_time' => date('Y-m-d H:i:s'),
        ];
        $r = Db::name('g_order_refund')
            ->insertGetId($data);
        Db::name('g_orders')
            ->where('id',$id)
            ->update([
                'status'=>6
            ]);
        if($r){
            HelpHander::success([],'操作成功');
        }
        HelpHander::error('操作失败');
    }

    public function buyBarrel(){
        $id = input('id/d',0);
        $num = input('num/d',1);
        $ret = model('WxOrders')->buyBarrel($this->orgId,$this->userId,$id,$num);
        HelpHander::success(['id'=>$ret]);
    }
    public function payBarrel(){
        $id = input('id/d',0);
        $info = Db::name('wx_cash_pay_log')
            ->where('id',$id)
            ->find();
        if(empty($info)){
            HelpHander::error('押金支付记录不存在');
        }
        if($info['status'] !=0){
            HelpHander::error('押金已支付');
        }

        $config = config('app.wx_mini_config');
        $notify = request()->domain().'/api/v1/notify/cashOrder';
        $openid = Db::name('wxuser')->where('id',$this->userId)->value('openid');

        $app = Factory::payment($config);

        $result = $app->order->unify([
            'body' => '订单-'.$info['sn'],
            'out_trade_no' => $info['sn'],
            'total_fee' => $info['amount']*100,
            'notify_url' => $notify, // 支付结果通知网址,如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $ret = $jssdk->bridgeConfig($result['prepay_id'],false); // 返回数组
            HelpHander::success($ret,'成功');
        }else{
            HelpHander::error($result['return_msg']);
        }
    }
    public function refundBarrel(){
        $id = input('id/d',0);
        $num = input('num/d',1);
        $ret = model('WxOrders')->refundBarrel($this->orgId,$this->userId,$id,$num);
        HelpHander::success($ret,'操作成功');
    }

    public function commentOrder(){
        $id = input('orderId',0);
        $info = Db::name('wx_orders')
            ->where('id',$id)
            ->where('user_id',$this->userId)
            ->find();
        if(empty($info)){
            HelpHander::error('订单不存在');
        }
        if($info['status']!=3){
            HelpHander::error('该订单不能评价');
        }
        $data = [
            'status'=>5,
            'finish_time'=>date('Y-m-d H:i:s')
        ];
        Db::startTrans();
        try{
            $ret = Db::name('wx_orders')->where('id',$id)->update($data);
            if(!$ret){
                \exception('操作失败');
            }
            $data=[
                'score'=>input('score',''),
                'content'=>input('content',''),
                'user_id'=>$this->userId,
                'order_id'=>$id,
                'org_id'=>$this->orgId,
                'create_time'=>date('Y-m-d H:i:s'),
                'create_yyyymm'=>date('Ym'),
                'create_yyyy'=>date('Y'),
                'create_yyyymmdd'=>date('Ymd'),
            ];
            if(!$data['score']){
                \exception('得分不能为空');
            }
            $res = Db::name('wx_comment')->insertGetId($data);
            if (!$res) {
                exception('保存失败');
            }
            Db::commit();
            HelpHander::success([],'操作成功');

        }catch (Exception $e){
            Db::rollback();
            HelpHander::error($e->getMessage());
        }
    }
    public function commentDetail(){
        $id = input('orderId',0);
        $info = Db::name('wx_comment')
            ->field('create_yyyy,create_yyyymm,create_yyyymmdd',true)
            ->where('order_id',$id)
            ->find();
        if(empty($info)){
            HelpHander::error('评价不存在');
        }
        HelpHander::success($info,'操作成功');

    }
    public function checkoutApplyRefund(){
        $type = input('type/d',0);
        $orderId = input('orderId/d',0);
        $goodsId = input('goodsId/d',0);
        $ret = model('WxOrders')->checkoutApplyRefund($this->userId,$this->orgId,$type,$orderId,$goodsId);
        $ret?HelpHander::success($ret,'操作成功'):HelpHander::error(model('WxOrders')->getError());
    }
    public function checkoutApplyRefund1(){
        $orderId = input('orderId/d',0);
        $goodsId = input('goodsId','');
        $ret = model('WxOrders')->checkoutApplyRefund1($orderId,$goodsId);
        $ret?HelpHander::success($ret,'操作成功'):HelpHander::error(model('WxOrders')->getError());
    }
    public function addApplyRefund(){
        $goodsJson = input('goodsJson','');
        $orderId = input('orderId/d',0);
        $remark = input('reason','');
        $ret = model('WxOrders')->addApplyRefund($this->userId,$this->orgId,$goodsJson,$orderId,$remark);
        $ret?HelpHander::success($ret,'操作成功'):HelpHander::error(model('WxOrders')->getError());
    }
    public function orderRefundDetail(){
        $orderId = input('orderId/d',0);
        $goodsId = input('goodsId','');
        $ret = model('WxOrders')->orderRefundDetail($this->orgId,$orderId,$goodsId);
        HelpHander::success($ret,'操作成功');

    }
    public function goodsRefundDetail(){
        $orderId = input('orderId/d',0);
        $goodsId = input('goodsId/d',0);
        $ret = model('WxOrders')->goodsRefundDetail($this->orgId,$orderId,$goodsId);
        HelpHander::success($ret,'操作成功');

    }
    public function rBuy(){
        $orderId =input('orderId/d',0);
        $goods_id = Db::name('wx_orders_goods')
            ->where('order_id', $orderId)
            ->column('goods_id');
        foreach ($goods_id as $k=>$v){
            $check = Db::name('wx_goods_cart')
                ->where('user_id',$this->userId)
                ->where('goods_id',$v)
                ->find();
            if(empty($check)){
                $data=[
                    'user_id'=>$this->userId,
                    'goods_id'=>$v,
                    'nums'=>1,
                    'create_time'=>date('Y-m-d H:i:s'),
                ];
                Db::name('wx_goods_cart')->insert($data);
            }

        }
        HelpHander::success([],'操作成功');
    }

    public function checkRefundNum(){
        $orderId = input('orderId/d',0);
        $goodsId = input('goodsId/d',0);
        $num = input('num/d',0);
        $goodsList = Db::name('wx_orders_goods')
            ->alias('og')
            ->field('og.nums as num,og.price,og.goods_id,g.title,g.img,g.label')
            ->join('wx_goods g', 'g.id=og.goods_id')
            ->where('og.order_id', $orderId)
            ->where('og.goods_id', $goodsId)
            ->find();
        if($goodsList['num'] <$num){
            HelpHander::error('退款数量不能超过购买数量',1,['num'=>$goodsList['num']]);
        }
        HelpHander::success(['num'=>$num],'可以退款');
    }


    public function checkRefundChangeNum(){
        $type = input('type/d',0);
        $orderId = input('orderId/d',0);
        $goodsId = input('goodsId/d',0);
        $nums = input('nums',0);
        if(empty($orderId)){
            HelpHander::error('参数错误');
        }
        if($type==0 && empty($goodsId)){
            HelpHander::error('参数错误');
        }
        if($type==0){
            $goodsList = Db::name('wx_orders_goods')
                ->alias('og')
                ->field('og.nums as num,og.price,og.goods_id,g.title,g.img,g.label')
                ->join('wx_goods g', 'g.id=og.goods_id')
                ->where('og.order_id', $orderId)
                ->where('og.goods_id', $goodsId)
                ->select();
            foreach ($goodsList as $k=>$v){
                if($nums > 0){
                    $goodsList[$k]['num'] = $nums;
                }
            }
        }else{
            $goodsList = Db::name('wx_orders_goods')
                ->alias('og')
                ->field('og.nums as num,og.price,og.goods_id,g.title,g.img,g.label')
                ->join('wx_goods g', 'g.id=og.goods_id')
                ->where('og.order_id', $orderId)
                ->select();
        }
        foreach ($goodsList as $k=>$v){


            //$rNum = $this->getRefundGoodsNum($v['goods_id'],$orderId);
            //$goodsList[$k]['refund_num'] = $v['num']-$rNum;
            // $goodsList[$k]['refund_num'] = $v['num'];
            $goodsList[$k]['label_name'] = $v['label']>0?Db::name('wx_goods_label')
                ->where('id',$v['label'])
                ->value('title'):"";
            $flag= Db::name('wx_orders_refund')
                ->where('del',0)
                ->where('goods_id',$v['goods_id'])
                ->where('order_id',$orderId)
                ->find();
            if($flag){
                unset($goodsList[$k]);
            }
        }
        HelpHander::success($goodsList);


    }

}