<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;


class Scoreshop extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        return $base['scoreshop'];
    }
    
    public static function payResult($order_no,$paytype=0,$third_party=0,$type=0){
        $order = Db::name("bbfx_scoreshop_order")->where(['uniacid'=>UNIACID,'order_no'=>$order_no])->find();
        
        if(empty($order)){
            return false;
        }
        
        if($order['status'] == 1){
            return false;
        }
        
        $res = Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['status'=>1]);
        if(empty($res)){
            return false;
        }
        
        Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['third_party'=>$third_party,'paytype'=>$paytype,'pay_time'=>time()]);
        
        if($order['score'] > 0 && $type == 0){
            User::setUserMoney($order['user_id'],-$order['score'],2,1,"积分商品兑换",$order);
        }

        \app\common\model\bbfxshop\FenxiaoJiesuan::setJiesuanStatus($order['id'],3);
        \app\common\model\bbfxshop\FenxiaoJiesuan::setJiesuanCommission($order['id'],3);

        if($order['order_type'] == 4 || $order['order_type'] == 1){
            self::takeDelivery($order['id']);
        }

        \app\common\model\bbfxshop\Message::sendXiadanMsg($order['id'],1);

        return true;
    }
    
    public static function resetStock($uniacid,$goods_id=0){
        $where = ['uniacid'=>$uniacid,'type'=>['in',[1,2]]];
        if(!empty($goods_id)){
            $where['id'] = $goods_id;
        }
        // $goods_list = Db::name("bbfx_scoreshop_goods")->where($where)->field("id,type,is_spec")->select();
        $goods_list = Db::name("bbfx_scoreshop_goods")->where($where)->field("id,type")->select();
        if(empty($goods_list)){
            return false;
        }
        
        foreach ($goods_list as $key => $goods){
            if($goods['type'] == 1 || ($goods['type'] == 2 && $goods['is_spec'] == 1)){
                if($goods['type'] == 1){
                    $goods_stock = Db::name("bbfx_scoreshop_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id'],'status'=>0])->count();
                }
                else{
                    $goods_stock = Db::name("bbfx_scoreshop_goods_spec_sku")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->sum("stock");
                }
                $goods_stock = intval($goods_stock);
                Db::name("bbfx_scoreshop_goods")->where(['id'=>$goods['id']])->update(['stock'=>$goods_stock]);
            }
        }
    }
    
    // 确认收货
    public static function takeDelivery($order_id){
        
        $order = Db::name("bbfx_scoreshop_order")->where(['id'=>$order_id,'status'=>['>',0]])->find();
        if(empty($order)){
            return __json(0,"订单不存在");
        }
        if($order['status'] == 0){
            return __json(0,"订单未支付");
        }
        if($order['refund_status'] == 0 || $order['refund_status'] == 1){
            return __json(0,"订单已申请售后");
        }
        if(!in_array($order['order_type'],[1,2,4])){
            return __json(0,"订单类型错误");
        }
        if(($order['order_type'] == 4 || $order['order_type'] == 2) && $order['is_hexiao'] == 1){
            return __json(0,"核销订单不能确认收货");
        }
        if($order['status'] == 1 && $order['order_type'] == 2){
            return __json(0,"订单未发货");
        }
        if($order['status'] == 3 && $order['order_type'] == 2){
            return __json(0,"订单已收货");
        }

        try {
            Db::startTrans();
            $res = Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['status'=>3]);
            if($res){
                if($order['order_type'] == 1){
                    $order_goods = Db::name("bbfx_scoreshop_order_goods")->where(['order_id'=>$order['id'],'uniacid'=>UNIACID])->select();
                    foreach ($order_goods as $key => $val){
                        $goods_info = iunserializer($val['goods_info']);
                        $serial_number_list = [];
                        if(!empty($goods_info['serial_number'])){
                            $serial_number_list = $goods_info['serial_number'];
                        }
                        $total = $val['total'];
                        $o_total = Db::name("bbfx_scoreshop_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$val['goods_id'],'pid'=>$val['id']])->count();
                        $o_total = intval($o_total);
                        $total = $total - $o_total;
                        if($total > 0){
                            for($i = 0;$i < $total;$i++){
                                
                                $res = self::receiveSerialNumber($val);
                                
                                if(!empty($res)){
                                    if(is_array($res)){
                                        $serial_number_list[] = $res;
                                    }
                                }
                                else{
                                    throw new \Exception("【{$goods_info['title']}】库存不足");
                                }
                            }
                        }
                    }
                }
                $result = __json(1,"操作成功");
            }
            else{
                 throw new \Exception("操作失败");
            }
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            $result = __json(-1,$e->getMessage());
        }
        
        if($result['code'] == 1){
            \app\common\model\bbfxshop\Shipping::upload($order['id'],6);
            self::complete($order);
        }
        
        return $result;
    }
    
    // 订单完成
    public function complete($order){
        \app\common\model\bbfxshop\FenxiaoJiesuan::setJiesuanCommission($order['id'],3);
    }
    
    // 发放卡密
    public static function receiveSerialNumber($order_goods){
        
        $serial_number_data = [];
        $total = max(1,intval($order_goods['total']));
        $serial_number_ok = Db::name("bbfx_scoreshop_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$order_goods['goods_id'],'pid'=>$order_goods['id']])->count();
        $serial_number_ok = intval($serial_number_ok);
        if($serial_number_ok >= $total){
            return true;
        }
        
        while(true){
            $serial_number = Db::name("bbfx_scoreshop_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$order_goods['goods_id'],'status'=>0,'oper'=>1])->find();
            if(!empty($serial_number)){
                $res = Db::name("bbfx_scoreshop_serial_number")->where(['id'=>$serial_number['id']])->setDec("oper",1);
                if(!empty($res)){
                    Db::name("bbfx_scoreshop_serial_number")->where(['id'=>$serial_number['id']])->update(['status'=>1,'pid'=>$order_goods['id']]);
                    $serial_number_data = $serial_number;
                    break;
                }
            }
            else{
                break;
            }
        }
        
        self::resetStock($order_goods['uniacid'],$order_goods['goods_id']);
        
        return $serial_number_data;
    }
    
    // 订单退款
    public static function refund($order_id,$status,$type=0){
        
        $order = Db::name("bbfx_scoreshop_order")->where(['id'=>$order_id,'status'=>['>',0]])->find();
        $refund = Db::name("bbfx_scoreshop_order_refund")->where(['order_id'=>$order_id])->find();
        if(empty($order)){
            return __json(0,'订单不存在');
        }
        if(empty($refund)){
            return __json(0,'退款申请不存在');
        }
        if(!in_array($order['status'],[1,2,3])){
            return __json(0,'订单状态错误');
        }
        
        if($refund['status'] == 1){
            return __json(0,'订单已退款');
        }
        if($refund['status'] == 2 && $type != 1){
            return __json(0,'订单退款已拒绝');
        }
        
        if(!in_array($order['paytype'],[1,2])){
            // return __json(-1,'订单支付方式不可操作');
        }
        
        try {
            Db::startTrans();
            
            $res = Db::name("bbfx_scoreshop_order_refund")->where(['id'=>$refund['id']])->update(['status'=>$status]);
            if($res){
                Db::name("bbfx_scoreshop_order_refund")->where(['id'=>$refund['id']])->update(['refundtime'=>time()]);
                if($status == 1){
                    $price = $order['price'];
                    $refund_fee = $refund['money'];
                    if($refund_fee > $price){
                        $refund_fee = $price;
                    }

                    if($refund_fee > 0){

                        if($order['paytype'] == 1){

                            $order_trade_no = \app\common\model\bbfxshop\Order::getOrderTradeNo($order['order_no']);
                            $params = ['order_trade_no'=>$order_trade_no,'out_refund_no'=>$refund['order_no'],'total_fee'=>$order['price'],'refund_fee'=>$refund_fee,'org_req_date'=>date('Ymd',$order['pay_time']),'platform'=>$order['platform']];
                            
                            if($order['third_party'] == 1){
                                $dougong = new \app\common\model\bbfxshop\Dougong();
                                $res = $dougong->refund($params,$order['paytype']);
                            }
                            else{
                                $res = \app\common\model\bbfxshop\Wxpay::refund($params);
                            }
                            if(empty($res) || $res['code'] != 1){
                                throw new \Exception($res['message']);
                            }
                        }
                        else if($order['paytype'] == 2){
                            $res = User::setUserMoney($order['user_id'],$refund['money'],1,4,"订单退款",$order);
                            if(empty($res)){
                                throw new \Exception("退款失败");
                            }
                        }
                        else if($order['paytype'] == 5){
                            $order_trade_no = \app\common\model\bbfxshop\Order::getOrderTradeNo($order['order_no']);
                            $params = ['order_trade_no'=>$order_trade_no,'out_refund_no'=>$refund['order_no'],'refund_fee'=>$refund_fee,'refund_reason'=>$refund['content'],'org_req_date'=>date('Ymd',$order['pay_time'])];
                            if($order['third_party'] == 1){
                                $dougong = new \app\common\model\bbfxshop\Dougong();
                                $res = $dougong->refund($params,$order['paytype']);
                            }
                            else{
                                $res = \app\common\model\bbfxshop\Alipay::refund($params);
                            }
                            if(empty($res) || $res['code'] != 1){
                                throw new \Exception($res['message']);
                            }
                        }
                    }
                    
                    if($refund['score'] > 0){
                        User::setUserMoney($order['user_id'],$refund['score'],2,4,"订单退款",$order);
                    }
                    
                    Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['refund_status'=>$status]);
                    $result = __json(1,'退款成功');
                }
                else{
                    Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['refund_status'=>$status]);
                    $result = __json(1,'操作成功');
                }
            }
            else{
                throw new \Exception("操作失败");
            }
            $result = __json(1,'操作成功');
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            $msg = $e->getMessage();
            $result = __json(0,$msg);
        }

        return $result;
    }
    
    // 订单核销
    public static function hexiao($id,$user_id=0,$store=[]){
        
        $where = ['uniacid'=>UNIACID,'id'=>$id];
        if(!empty($store)){
           $where['store_id'] =  $store['id'];
        }
       
        $order = Db::name("bbfx_scoreshop_order")->where($where)->find();
        if(empty($order)){
            return __json(0,"订单不存在");
        }
        if($order['status'] == -1){
            return __json(0,"订单已取消");
        }
        if($order['status'] < 1){
            return __json(0,"订单未支付");
        }
        if($order['refund_status'] == 0 || $order['refund_status'] == 1){
            return __json(0,"订单已申请售后");
        }
        if(!(($order['order_type'] == 2 || $order['order_type'] == 4) && $order['is_hexiao'] == 1)){
            return __json(0,"不是核销订单");
        }
        if($order['status'] == 3){
            __error("订单已核销");
        }
        
        if($order['hexiao_num'] <= 0){
            $res = Db::name("bbfx_scoreshop_order")->where("id",$order['id'])->update(['status'=>3]);
            if($res){
                self::complete($order);
                
                return __json(0,"核销已完成");
            }
        }
        
        if(!empty($user_id)){
            $user = Db::name("bbfx_user")->where("id",$user_id)->field("id,nickname,avatar")->find();
        }
        if(!empty($store)){
            $store = Db::name("bbfx_store")->where("id",$store['id'])->find();
        }
        
        try {
            
            Db::startTrans();
            
            $res = Db::name("bbfx_scoreshop_order")->where("id",$order['id'])->setDec("hexiao_num",1);
            if(empty($res)){
                throw new \Exception("核销已完成");
            }
            
            $order['goods_info'] = iunserializer($order['goods_info']);
            
            $info = ['user'=>$user,'order'=>$order,'store'=>$store];
            
            $data = array(
                "uniacid"=>$order['uniacid'],
                "user_id"=>$user_id,
                "order_id"=>$order['id'],
                "store_id"=>intval($store['id']),
                "info"=>iserializer($info),
                "createtime"=>time()
            );
            
            Db::name("bbfx_scoreshop_order_hexiao_record")->insert($data);
            $odata = ['hexiao_time'=>time(),'status'=>2];
            if(!empty($user)){
                $odata['hexiao_uid'] = $user['id'];
            }
            else{
                $odata['hexiao_uid'] = 0;
            }
            if($order['hexiao_num'] == 1){
                $odata['status'] = 3;
            }
            
            $res = Db::name("bbfx_scoreshop_order")->where("id",$order['id'])->update($odata);
            
            
            $result = __json(1,"核销成功");
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            $result = __json(0,$e->getMessage());
        }

        if($result['code'] == 1 && $odata['status'] == 3){
            \app\common\model\bbfxshop\Shipping::upload($order['id'],6);
            self::complete($order);
        }
        
        return $result;
    }
    
    // 关闭订单
    public static function closeOrder($order_id){
        
        if(is_array($order_id)){
            $order = $order_id;
        }
        else{
            $order = Db::name("bbfx_scoreshop_order")->where(['uniacid'=>UNIACID,'status'=>0,'id'=>$order_id])->find();
        }
        
        if(empty($order)){
            return __json(0,"订单不存在或已关闭");
        }
        
        $res = Db::name("bbfx_order")->where("id",$order['id'])->update(['status'=>-1]);
        if($res){
            // if($order['user_coupon_id'] > 0){
            //     Db::name("bbfx_user_coupon")->where("id",$order['user_coupon_id'])->update(['status'=>0]);
            // }
            
            $goods = iunserializer($order['goods_info']);
            
            foreach ($goods as $k => $v){
                $total = $v['total'];
                if($v['stock_type'] == 1){
                    if(!empty($v['sku'])){
                        Db::name("bbfx_scoreshop_goods_spec_sku")->where(['id'=>$v['sku_id']])->setInc("stock",$total);
                    }
                    else{
                        Db::name("bbfx_scoreshop_goods")->where(['id'=>$v['id']])->setInc("stock",$total);
                    }
                }
                self::resetStock($order['uniacid'],$v['id']);
            }
            
            // $repurchase_currency = floatval($order['repurchase_currency']);
            // if($repurchase_currency > 0){
            //     User::setUserMoney($order['user_id'],$repurchase_currency,4,25,"订单关闭退回",$order);
            // }
            return __json(1,"关闭订单成功");
        }
        else{
            return __json(0,"关闭订单失败");
        }
    }
    
    public static function getOrderType($type){
        $list = ['1'=>'卡密虚拟','2'=>'实物商品','3'=>'核销商品','4'=>'虚拟商品'];
        
        if(empty($list[$type])){
            return "未知类型";
        }
        
        return $list[$type];
    }
    
    public static function getOrderStatus($order,$type=0){
        
        $status = $order['status'];
        $is_hexiao = $order['is_hexiao'];
        $refund_status = $order['refund_status'];
        
        
        $list = ['-1'=>'已关闭','0'=>'待支付','1'=>'待发货','2'=>'已发货','3'=>'已完成'];
        
        if($is_hexiao == 1){
            $list = ['-1'=>'已关闭','0'=>'待支付','1'=>'待核销','2'=>'待核销','3'=>'已完成'];
        } 
        
        if(($refund_status == 1 || $refund_status == 0) && $type == 0){
            return self::getOrderRefundStatus($refund_status);
        }
        
        if(empty($list[$status])){
            return "";
        }
        
        return $list[$status];
    }
    
    public static function getOrderRefundStatus($status){
        $list = ['-1'=>'未退款','0'=>'待审核','1'=>'已退款','2'=>'已拒绝'];
        
        if(empty($list[$status])){
            return "未知状态";
        }
        
        return $list[$status];
    }
    
    public static function getOrderPaytype($order){
        global $_W;
        $status = $order['paytype'];
        if($order['status'] < 1){
            return "";
        }
        $predeposit = $_W['base']['fenxiao']['texts']['predeposit'];
        if(empty($predeposit)){
            $predeposit = "预存款";
        }
        $repurchase_currency = $_W['base']['fenxiao']['texts']['repurchase_currency'];
        if(empty($repurchase_currency)){
            $repurchase_currency = "复购金";
        }

        $texts = $_W['base']['texts'];
         
        $list = [
            '1'=>$texts['weixin_pay'],
            '2'=>$texts['balance_pay'],
            '3'=>$predeposit."支付",
            '4'=>$repurchase_currency."支付",
            '5'=>$texts['alipay_pay'],
            '6'=>$texts['cash_pay'],
            '7'=>$texts['score_pay'],
            '8'=>'后台录单',
        ];
        
        if(empty($list[$status])){
            return "未知支付方式";
        }

        $paytype_title = $list[$status];

        if($order['balance'] > 0){
            $paytype_title .= " + " . $texts['balance']."抵扣";
        }
        else if($order['score'] > 0){
            $paytype_title .= " + " . $texts['score']."抵扣";
        }
        else if($order['repurchase_currency'] > 0){
            $paytype_title .= " + " . $repurchase_currency."抵扣";
        }
        
        return $paytype_title;
    }
}