<?php
namespace wstmart\common\model;
use think\Db;
/**
 * ============================================================================
 * 结算类
 */
class Settlements extends Base
{
    /**
     * 即时计算
     */
    public function speedySettlement($orderId)
    {
        $order = model('common/orders')->get($orderId);
        $shops = model('common/shops')->get($order->shopId);
        if (empty($shops)) return WSTReturn('结算失败,商家不存在');
        //获取优惠款 价格*优惠率
        $m = Model('common/Table');
        $m->setTable('order_goods');
        $orderGoodsList = $m->getList(['orderId'=>$orderId],'goodsPrice,goodsNum,freight,discountRate');
        $discountMoney = 0;//优惠款
        foreach ($orderGoodsList as &$v) {
            //$discountMoney += ($v['goodsPrice']*$v['goodsNum'] + $v['freight']) * ($v['discountRate']*0.01);//优惠款
            $discountMoney += ($v['goodsPrice']*$v['goodsNum']) * ($v['discountRate']*0.01);//优惠款
        }
        $discountMoney = round($discountMoney,5);
        //加入快代付值
        Model('SysSummary')->addToPayFast($orderId,$discountMoney,'订单【'.($order['orderNo']?:'--').'】优惠款加入');
        //获取产品额
        $totalMoney = $order->realTotalMoney;//产品额
        if(2 != $order->goodsType){//助微吧商品不给购户券值
            //  购户的所得分配
            // 1,购户获得预获产品券为产品额的100% buyerPreProductInProductScale
            // 2,购户获得预获优惠券为优惠款的50% buyerPreCoupousInSaleScale
            // 3,获得预获产品券为被扣手续费的100% buyerPreProductInHandlingFeeScale
            // 4,获得预获产品券为被扣税费的100% buyerPreProductInTaxFeeScale
            // 5,获得预获产品券为被扣手续费的100% buyerPreProductInProductHandlingFeeScale
            // 6,获得预获产品券为被扣税费的100% buyerPreProductInProductTaxFeeScale

            // 购户获得预获产品券最高占产品额比例?%
//            $buyerPreProductNum = round(($totalMoney + $order->deliverMoney),5);//1
            $buyerPreProductNum = round(($discountMoney * (dataConf('couponPercentCanUsetGet')*0.01)),5);//1
            $buyerMaxCouponsNum = round(($totalMoney + $order->deliverMoney)* (dataConf('buyerPreProductInProductScale')*0.01),5);//1
            $buyerPreCoupousNum = round($discountMoney * (dataConf('buyerPreCoupousInSaleScale')*0.01),5);//2
//            $buyerPreProductNum +=  round($order->productHandlingFee * (dataConf('buyerPreProductInHandlingFeeScale')*0.01),2);//3
//            $buyerPreProductNum +=  round($order->productTaxFee * (dataConf('buyerPreProductInTaxFeeScale')*0.01),2);//4
//            $buyerPreProductNum +=  round($order->couponsHandlingFee * (dataConf('buyerPreProductInProductHandlingFeeScale')*0.01),2);//5
//            $buyerPreProductNum +=  round($order->couponsTaxFee * (dataConf('buyerPreProductInProductTaxFeeScale')*0.01),2);//6
            $buyerPreCoupousNum = $buyerPreCoupousNum > $buyerMaxCouponsNum ? $buyerMaxCouponsNum : $buyerPreCoupousNum;
            $buyerPreProductNum = $buyerPreProductNum > $totalMoney ? $totalMoney : $buyerPreProductNum;
            if($buyerPreProductNum > 0 || $buyerPreCoupousNum > 0){
                if(3 == $order->goodsType){
                    Model('common/UserVouchers')->insertVouchersNotice($order->userId,$orderId,$buyerPreProductNum,$buyerPreCoupousNum*((float)dataConf('helpSaleCouponsCalBase')/100),'交易订单【'.$order->orderNo.'】购户购物所得');
                }else{
                    Model('common/UserVouchers')->insertVouchersNotice($order->userId,$orderId,$buyerPreProductNum,$buyerPreCoupousNum,'交易订单【'.$order->orderNo.'】购户购物所得');
                }
            }
        }
        
        
        //  商户的所得分配
        // 1,商户获得预获产品券占优惠款比例 100% sellerPreProductInProductScale
        // 2,商户获得预获优惠券占优惠款比例 100% sellerPreCoupousInSaleScale
        // 3,优惠款-产品-优惠券-旺旺券,大于0是商户需付公司的钱,小于0是公司需付给商户的钱,即旺旺券
        // $discountMoney-$order->productNum-$order->couponsNum-$order->wangNum-$order->moneyNum
        $sellerPreProductNum = round($discountMoney * (dataConf('sellerPreProductInProductScale')*0.01),5);//1
        $sellerPreCoupousNum = round($discountMoney * (dataConf('sellerPreCoupousInSaleScale')*0.01),5);//2
        $calBaseNum = Db::table("__ORDERS__ o")->join("__ORDER_GOODS__ g", "g.orderId=o.orderId", 'inner')
            ->where(['o.orderId'=>$orderId])->sum('g.goodsPrice*g.goodsNum*g.discountRate*0.01');
        if($sellerPreProductNum >= 0.01 || $sellerPreCoupousNum>=0.01){
            if(3 != $order->goodsType){
                // step 3 平台送商户:10000×0.4=4000“预获产品券”
                //                   10000×0.4=4000“预获优惠券”
                Model('common/UserVouchers')->insertVouchersNotice($shops['userId'], $orderId, $calBaseNum, $calBaseNum,
                    '交易订单【'.$order->orderNo.'】商户售物所得',1);
            }else{
                Model('common/UserVouchers')->insertVouchersNotice($shops['userId'],$orderId,$sellerPreProductNum,$sellerPreCoupousNum,'交易订单【'.$order->orderNo.'】商户售物所得');
            }
        }

        if(3 != $order->goodsType){
            $toCalBaseNum = $calBaseNum;
        }else{
            $toCalBaseNum = $calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100);
        }
        // step 4 平台送商户的推荐人:当消费超过限制值时10000×0.4×0.5×0.5=1000“预获产品券”。
        //                           当消费低于限制值时10000×0.4×0.5×0.2=400“预获产品券”。
        $uUserId = UserTrees::getUpperId($shops["userId"]);
        if($uUserId == null || $uUserId == 0){$uUserId = 1;}
        $data = Db::query('SELECT sum(`goodsMoney`) as `total` FROM `hyh_orders` WHERE DATE_FORMAT(`createTime`,"%Y%m%d")=DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 day),"%Y%m%d") and `userId`="'.$uUserId.'"');
        // 因为count一定会有数据所以不判断了
        if((float)$data[0]["total"]<=(float)dataConf("refPreProductYdGTMoney")){
            Model('common/UserVouchers')->insertVouchersNotice($uUserId, $orderId,$toCalBaseNum*((float)dataConf("refPreProductNoInSaleScale")/100),
                0,'交易订单【'.$order['orderNo'].'】推荐商户所得',1);
        }else{
            Model('common/UserVouchers')->insertVouchersNotice($uUserId, $orderId,$toCalBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100)*((float)dataConf("refPreProductYesInSaleScale")/100),
                0,'交易订单【'.$order['orderNo'].'】推荐商户所得',1);
        }
        // step 6 平台送自己的推荐人:当消费超过限制值时10000×0.4×0.5×0.5=1000“预获产品券”;
        //                           当消费低于限制值时10000×0.4×0.5×0.2=400“预获产品券”。
        $uUserId = UserTrees::getUpperId($order['userId']);
        if($uUserId == null || $uUserId == 0){$uUserId = 1;}
        $data = Db::query('SELECT sum(`goodsMoney`) as `total` FROM `hyh_orders` WHERE DATE_FORMAT(`createTime`,"%Y%m%d")=DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 day),"%Y%m%d") and `userId`="'.$uUserId.'"');
        // 因为count一定会有数据所以不判断了
        if($data[0]["total"]<=dataConf("refPreProductYdGTMoney")){
            Model('common/UserVouchers')->insertVouchersNotice($uUserId, $orderId,$toCalBaseNum*((float)dataConf("refPreProductNoInSaleScale")/100),
                0,'交易订单【'.$order['orderNo'].'】推荐购户所得',1);
        }else{
            Model('common/UserVouchers')->insertVouchersNotice($uUserId, $orderId,$toCalBaseNum*((float)dataConf("refPreProductYesInSaleScale")/100),
                0,'交易订单【'.$order['orderNo'].'】推荐购户所得',1);
        }
        // step 7 平台送自己的被推荐人:10000×0.4×0.5×0.5÷5=200“预获产品券”。
        $childes = DB::table("hyh_user_trees")->where(["pid"=>$order['userId']])->field("uid")->select();
        foreach ($childes as $child){
            Model('common/UserVouchers')->insertVouchersNotice($child['uid'], $orderId,
                $toCalBaseNum*((float)dataConf("helpSaleChildrenGet")/100)/sizeof($childes), 0,
                '交易订单【'.$order['orderNo'].'】被推荐所得',1);
        }



        //旺旺券结算
        $payVouchersNum = ($order->productNum - $order->productHandlingFee - $order->productTaxFee) + ($order->couponsNum - $order->couponsHandlingFee - $order->couponsTaxFee) + $order->wangNum;////3个券的付款总额+$order->moneyNum;
        $giveWangNum = round($payVouchersNum - $discountMoney,5);
        $m->setTable('orders');
        if($giveWangNum > 0){
            $m->updateInfo(['orderId'=>$orderId],['certificateStatus'=>1,'payable'=>$giveWangNum]);
            Model('common/LogMoneys')->addMoneyLog(1,$order->shopId,$order->orderId,1,'交易订单【'.$order->orderNo.'】结算收入¥'.$giveWangNum,1,$giveWangNum,'qlgpay',3);       
        }else{
            $m->updateInfo(['orderId'=>$orderId],['certificateStatus'=>0,'payable'=>$giveWangNum]);
        }
        //商超,商厦,商都所得
        // 1,获得预获优惠券时限上日有消费≥100元为产品额的5%。
        // shopPreCoupousYdGTMoney    shopPreCoupousYesInProductScale
        // 2,获得预获优惠券时限上日有消费<100元为产品额的2.5% shopPreCoupousNoInProductScale
        $m->setTable('shops');
        $positionInfo = $m->getInfo(['shopId'=>$order->shopId,'dataFlag'=>1],'villageId,townId,countyId');
        if($positionInfo){            
            $m->setTable('user_update');
            //村代理
            $agentAreaId = 'villageId';
            $agentUserId = $m->getField(['applyLevel'=>2,$agentAreaId=>$positionInfo[$agentAreaId],'status'=>1],'userId');
            if($agentUserId && $vInfo = getUserInfo(['userId'=>$agentUserId,'dataFlag'=>1,'userStatus'=>1],'userId')){
                $yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($agentUserId,'realTotalMoney');
                $agentProductMoney = 0;
                if($yesterdayBuyMoney >= dataConf('shopPreCoupousYdGTMoney')){//大于设定值
                    $agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousYesInProductScale')*0.01),5);//1
                }else{
                    $agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousNoInProductScale')*0.01),5);//2
                }
                if($agentProductMoney >= 0.01){
                    Model('common/UserVouchers')->insertVouchersNotice($agentUserId,$orderId,0,$agentProductMoney,'交易订单【'.$order->orderNo.'】商超所得');
                }
            }            
            //乡镇代理
            
            $m->setTable('user_update');
            $agentAreaId = 'townId';
            $agentUserId = $m->getField(['applyLevel'=>3,$agentAreaId=>$positionInfo[$agentAreaId],'status'=>1],'userId');
            if($agentUserId && $vInfo = getUserInfo(['userId'=>$agentUserId,'dataFlag'=>1,'userStatus'=>1],'userId')){
                $yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($agentUserId,'realTotalMoney');
                $agentProductMoney = 0;
                if($yesterdayBuyMoney >= dataConf('shopPreCoupousYdGTMoney')){//大于设定值
                    $agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousYesInProductScale')*0.01),5);//1
                }else{
                    $agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousNoInProductScale')*0.01),5);//2
                }
                if($agentProductMoney >= 0.01){
                    Model('common/UserVouchers')->insertVouchersNotice($agentUserId,$orderId,0,$agentProductMoney,'交易订单【'.$order->orderNo.'】商厦所得');
                }
            }
            //区县代理            
            $m->setTable('user_update');
            $agentAreaId = 'countyId';
            $agentUserId = $m->getField(['applyLevel'=>4,$agentAreaId=>$positionInfo[$agentAreaId],'status'=>1],'userId');
            if($agentUserId && $vInfo = getUserInfo(['userId'=>$agentUserId,'dataFlag'=>1,'userStatus'=>1],'userId')){
                $yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($agentUserId,'realTotalMoney');
                $agentProductMoney = 0;
                if($yesterdayBuyMoney >= dataConf('shopPreCoupousYdGTMoney')){//大于设定值
                    $agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousYesInProductScale')*0.01),5);//1
                }else{
                    $agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousNoInProductScale')*0.01),5);//2
                }
                if($agentProductMoney >= 0.01){
                    Model('common/UserVouchers')->insertVouchersNotice($agentUserId,$orderId,0,$agentProductMoney,'交易订单【'.$order->orderNo.'】商都所得');
                }
            }
        }
        
        //推荐人所得
        // 1,推荐人获得预获产品券时限上日有消费≥10元为优惠款的50%。
        // refPreProductYdGTMoney     refPreProductYesInSaleScale
        // 2,推荐人获得预获产品券时限上日有消费<10元为优惠款的25% refPreProductNoInSaleScale
        // 20200114 -- 说用不上,注释
//        $m->setTable('user_trees');
//        $pid = $m->getField(['uid'=>$shops['userId']],'pid');
//        if($pid && $pInfo = getUserInfo(['userId'=>$pid,'dataFlag'=>1,'userStatus'=>1],'userId') && 3 != $order->goodsType){//有推荐人并且推荐人状态正常
//            $yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($pid,'realTotalMoney');
//            if($yesterdayBuyMoney >= dataConf('refPreProductYdGTMoney')){//大于设定值
//                $refProductMoney = round($discountMoney * (dataConf('refPreProductYesInSaleScale')*0.01),2);//1
//            }else{
//                $refProductMoney = round($discountMoney * (dataConf('refPreProductNoInSaleScale')*0.01),2);//2
//            }
//            if($refProductMoney > 0){
//                Model('common/UserVouchers')->insertVouchersNotice($pid,$orderId,$refProductMoney,0,'交易订单【'.$order->orderNo.'】推荐所得');
//            }
//        }
        return true;
    }
    /**
     * 即时计算
     */
//     public function speedySettlement($orderId)
//     {
//         $order = model('common/orders')->get($orderId);
//         $shops = model('common/shops')->get($order->shopId);
//         if (empty($shops)) return WSTReturn('结算失败,商家不存在');
//         //$backMoney = 0;
//         $sub_deposit = 0;
//         $deposit_msg = '';
//         $payFrom = $order->payFrom;
//         if ($order->payType == 1) {
//             //在线支付的返还金额=实付金额+惠宝抵扣金额-佣金
//             // $backMoney = $order->realTotalMoney+$order->scoreMoney-$order->commissionFee;
//             //修改为不加入惠宝的结算金额 mark hsf 20180308
//             if ($payFrom == 'ect') {
//                 $ectInfo = db('orders_ect')->where('orderId', $order['orderId'])->field('orderEctNum,ectPrice')->find();
//                 $commissionFee = $order->commissionFee;//佣金
//                 $backMoney = round($ectInfo['orderEctNum'] - ($order->commissionFee / $ectInfo['ectPrice']), 2);
//             } else {

//                 //订单业务员提成
//                 $comDeduct = Db::name('shop_commission')->where('shopId',$order->shopId)->field('comDeduct,userId,userName,deductMoney')->find();
//                 if($comDeduct && $comDeduct['comDeduct']>0){
//                     $deductMoney = $order->realTotalMoney * $comDeduct['comDeduct'] * 0.01;

//                     $deduct['userId'] = $comDeduct['userId'];
//                     $deduct['orderId'] = $order['orderId'];
//                     $deduct['deductMoney'] = $deductMoney;
//                     $deduct['createTime'] = time();
//                     // dump($deduct);die;
//                     Db::name('shop_commission_deduct')->insert($deduct);
//                     $manDeduct = $comDeduct['deductMoney'] + $deductMoney;
//                     Db::name('shop_commission')->where('userId',$comDeduct['userId'])->update(['deductMoney'=>$manDeduct]);
//                 }
                
//                 $commissionFee = $order->commissionFee;//佣金
//                 $backMoney = $order->realTotalMoney - $commissionFee;//返还金额

//                 //商家质保金未交齐,则扣除在线支付返回金额的30%
//                 $deposit_info = Db::name('shops_deposit')->where('shopId', $order->shopId)->field('isFinish,payDeposit,cashDeposit')->find();
//                 if(!$deposit_info){
//                     $deposit_info['shopId']=$order->shopId;
//                     $deposit_info['isFinish']=2;
//                     $deposit_info['cashDeposit']=0;
//                     $deposit_info['payDeposit']=1000;//老商户1000质保金
//                     $deposit_info['passTime']=time();
//                     Db::name('shops_deposit')->insert($deposit_info);
//                 }
//                 if (2 == $deposit_info['isFinish']) {//未交齐质保金
//                     $no_money = $deposit_info['payDeposit'] - $deposit_info['cashDeposit'];
//                     if ($no_money > 0) {
//                         $sub_money = $backMoney * 0.3;//质保金不足,订单扣除30%质保金
//                         $data_deposit = [];
//                         if ($no_money > $sub_money) {//未完成
//                             $sub_deposit = $sub_money;                                
//                         } else {
//                             $sub_deposit = $no_money;
//                             $data_deposit['isFinish'] = 1;
//                             $data_deposit['completeTime'] = time();
//                             //记录店铺订单中扣除的质保金                               
//                         }
//                         //添加到质保金里
//                         $data_deposit['cashDeposit'] = $deposit_info['cashDeposit'] + $sub_deposit;
//                         Db::name('shops_deposit')->where('shopId', $order->shopId)->update($data_deposit);
//                         //添加到质保金记录
//                         $detail = [];
//                         $detail['shopId'] = $order->shopId;
//                         $detail['orderId'] = $order->orderId;
//                         $detail['cashDeposit'] = $sub_deposit;
//                         $detail['payType'] = 2;
//                         $detail['payTime'] = time();
//                         Db::name('shops_deposit_detail')->insert($detail);
                        
//                         $backMoney -= $sub_deposit;
//                         $deposit_msg = ',质保金抵扣¥:'.$sub_deposit;
//                     }
//                 }
//             }
//             if ($backMoney < 0) {
//                 return true;
//             }
//         } else {
//             //货到付款的返还金额=惠宝抵扣金额-佣金
//             //$backMoney = $order->scoreMoney-$order->commissionFee;
//             //修改为不加入惠宝的结算金额 mark hsf 20180308
//             $backMoney = 0;
//         }

//         $data = [];
//         $data['settlementType'] = 1;
//         $data['shopId'] = $order->shopId;
//         //修改为不加入惠宝的结算金额 mark hsf 20180308
//         $data['settlementMoney'] = ($order->payType == 1) ? $order->realTotalMoney : 0;//$order->scoreMoney+(($order->payType==1)?$order->realTotalMoney:0);
//         $data['commissionFee'] = $commissionFee;
//         $data['backMoney'] = $backMoney;
//         $data['settlementStatus'] = 1;
//         $data['settlementTime'] = date('Y-m-d H:i:s');
//         $data['createTime'] = date('Y-m-d H:i:s');
//         $data['settlementNo'] = '';
//         $settlementId = $this->insertGetId($data);
//         if ($settlementId > 0) {
//             $settlementNo = $settlementId . uniqid() . mt_rand(10, 99);//(fmod($this->settlementId,7));
//             $this->where(['settlementId' => $settlementId])->update(['settlementNo' => $settlementNo]);
//             $order->settlementId = $settlementId;
//             $order->save();
// //            dump($backMoney);
// //            dump($payFrom);exit;
//             if ($payFrom == "ect") {
//                 ectLog($shops['userId'], $backMoney, 12, '结算', ['userECT' => ['exp', 'userECT+' . $backMoney]], 1);
//             } else {
//                 //修改商家钱包
//                 $shops->shopMoney = $shops['shopMoney'] + $backMoney;
//                 $shops->save();
//             }

//             //返还金额
//             $lmarr = [];
//             //如果是货到付款并且有惠宝支付的话,还要补上一个惠宝支付的资金流水记录,不然流水上金额不对。
//             // if($order->payType==0 && $order->scoreMoney >0){
//             //     $lm = [];
//             //     $lm['targetType'] = 1;
//             //     $lm['targetId'] = $order->shopId;
//             //     $lm['dataId'] = $this->settlementId;
//             //     $lm['dataSrc'] = 2;
//             //     $lm['remark'] = '结算订单申请【'.$this->settlementNo.'】惠宝支付金额¥'.$order->scoreMoney;
//             //     $lm['moneyType'] = 1;
//             //     $lm['money'] =$order->scoreMoney;
//             //     $lm['payType'] = 0;
//             //     $lm['createTime'] = date('Y-m-d H:i:s');
//             //     $lmarr[] = $lm;
//             // }
//             //收取佣金
//             if ($commissionFee > 0) {
//                 $lm = [];
//                 $lm['targetType'] = 1;
//                 $lm['targetId'] = $order->shopId;
//                 $lm['dataId'] = $settlementId;
//                 $lm['dataSrc'] = 2;
//                 $lm['remark'] = '结算订单申请【' . $settlementNo . '】收取订单佣金¥' . $commissionFee;
//                 $lm['moneyType'] = 0;
//                 $lm['money'] = $commissionFee;
//                 $lm['payType'] = 0;
//                 $lm['createTime'] = date('Y-m-d H:i:s');
//                 $lmarr[] = $lm;
//             }

//             if ($backMoney > 0) {
//                 $lm = [];
//                 $lm['targetType'] = 1;
//                 $lm['targetId'] = $order->shopId;
//                 $lm['dataId'] = $settlementId;
//                 $lm['dataSrc'] = 2;
//                 $lm['remark'] = '结算订单申请【' . $settlementNo . '】返还金额¥' . $backMoney.$deposit_msg;
//                 $lm['moneyType'] = 1;
//                 $lm['money'] = $backMoney;
//                 $lm['payType'] = 0;
//                 $lm['createTime'] = date('Y-m-d H:i:s');
//                 $lmarr[] = $lm;
//             }
//             model('common/LogMoneys')->saveAll($lmarr);
//             return true;
//         }
//         return false;
//     }
}