<?php

$is_script = 1;
include_once __DIR__ . '/../../index.php';


use app\api\model\User as UserModel;
use app\api\model\ProductOrder as ProductOrderModel;
use enum\order\ProductOrder as ProductOrderEnum;

$user_model = new UserModel;
$product_order_model = new ProductOrderModel;

//分批操作，每次1000条

$order_refund_list = [];

//退款金额
$order_refund_list_db = $product_order_model->field('UserId,sum(RefundAmount) as money')
            ->where(['OrderState' => ['in', ProductOrderEnum::$Refunds]])
            ->where(['agent_id'=>0])
            ->group(['UserId'])
            ->fetchAll();

foreach ($order_refund_list_db as $info){
    $order_refund_list[$info['UserId']] = $info['money'];
}
//支付金额
$order_pay_list_db = $product_order_model->field('UserId,sum(PaymentAmount) as money')
            ->where(['OrderState' => ['in', ProductOrderEnum::$PayComplete]])
            ->where(['agent_id'=>0])
            ->group(['UserId'])
            ->fetchAll();


//根据等级
$i=1;
foreach ($order_pay_list_db as $info){
    //如果有退款，先减去退款
    if(isset( $order_refund_list[$info['UserId']])){
        $info['money'] -= $order_refund_list[$info['UserId']];
    }
    $temp = [];
    $temp = [
        'ConsumeAmount' => $info['money'],
    ];
    $new_discount_id = 0;
    if ($info['money']>=200 && $info['money']<500){
        $new_discount_id = 1;
    } elseif($info['money']>=500 && $info['money']<1500) {
        $new_discount_id = 2;
    } elseif($info['money']>=1500 && $info['money']<3000) {
        $new_discount_id = 4;
    } elseif($info['money']>=3000 && $info['money']<6000) {
        $new_discount_id = 5;
    } elseif($info['money']>=6000) {
        $new_discount_id = 6;
    }

    $user_info = $user_model->getOne(['Id'=>$info['UserId'],'agent_id'=>0]);

    //新折扣大于老折扣，且不为代理用户
    if($new_discount_id>$user_info['discount_id'] && $user_info['agent_id']==0){
        $temp['discount_id'] = $new_discount_id;
    }

    // $user_model->updateOne(['Id'=>$info['UserId'],'agent_id'=>0],$temp);
    echo $i."\r";
    $i++;
}
