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

namespace app\common\model\bbfxshop;

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

class Bargain extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }

        if(!in_array('bargain',$base['pay_plugin'])){
            return []; 
        }
        
        return $base['bargain'];
    }
    
    public static function bargainGoodsPrice($id,$user_id){
        $bargain_goods = Db::name("bbfx_bargain_goods")->where(['id'=>$id])->find();
        if(empty($bargain_goods)){
            return __json(0,"砍价商品不存在");
        }
        if($bargain_goods['status'] != 1){
            return __json(0,"砍价商品已下架");
        }
        $goods = Db::name("bbfx_goods")->where(['id'=>$bargain_goods['goods_id']])->find();
        if(empty($goods)){
            return __json(0,"商品不存在");
        }
        if($bargain_goods['status'] != 1){
            return __json(0,"商品已下架");
        }

        if($bargain_goods['etime'] < time()){
            return __json(0,"砍价活动已结束");
        }
         
        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $log = Db::name("bbfx_bargain_goods_log")
            ->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'bargain_goods_id'=>$bargain_goods['id'],'goods_id'=>$goods['id'],'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])
            ->where(['createtime'=>['>',$bargain_goods['stime']]])->find();
        if(!empty($log)){
            return __json(0,"今日已参与该商品的砍价");
        }

        $rule_list = iunserializer($bargain_goods['rule']);
        if(empty($rule_list)){
            return __json(0,"砍价商品规则不存在");
        }

        $price = $bargain_goods['price'];
        $min_price = 0;
        foreach($rule_list as $key => $item){
            $min = round($item['min'],2);
            $max = round($item['max'],2);
            // print_r($min.",".$max);die;
            if($price > $min && $price <= $max){
                $rule = $item;
                $min_price = $min;
                break;
            }
        }
        if(empty($rule)){
            return __json(0,"已砍最低价");
        }
        
        
        if($bargain_goods['e_price'] > $min_price){
            $min_price = $bargain_goods['e_price'];
        }
        

        $bargain_min = $rule['bargain_min'];
        $bargain_max = $rule['bargain_max'];
        if($bargain_min > $bargain_max){
            return __json(0,"规则配置错误");
        }
        
        $random_price = mt_rand($bargain_min * 100, $bargain_max * 100) / 100;
        $random_price = round($random_price, 2);
        // echo "<pre>";
        // print_r($random_price);die;
        $is_monre = false;
        if($min_price > $price - $random_price){
            $random_price = $price - $min_price;
            $is_monre = true;
        }
        
        try{
            Db::startTrans();
            $log_data = [
                'uniacid' => UNIACID,
                'user_id' => $user_id,
                'bargain_goods_id' => $bargain_goods['id'],
                'goods_id' => $goods['id'],
                'o_price'=>$price,
                'price' => $random_price,
                'createtime' => time()
            ];
            
            $log_id = Db::name("bbfx_bargain_goods_log")->insertGetId($log_data);

            if($is_monre){
                $price = $min_price;
                Db::name("bbfx_bargain_goods")->where(['id'=>$id])->update(["price"=>$min_price]);
            }
            else{
                $price = $price - $random_price;
                Db::name("bbfx_bargain_goods")->where(['id'=>$id])->setDec("price",$random_price);
            }

            Db::commit();
        }
        catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

        return __json(1,"砍价成功",['bargain_price'=>$random_price,'price'=>$price,'log_id'=>$log_id]);
    }

    public static function calculateMoney($goods,$user,$delivery_method=1,$address_id=0){
        // 总商品金额(折扣后价格)
        $total_price = 0;
        // 快递费
        $express_fee = 0;
        // 折扣金额
        $total_discount_price = 0;
        // 总商品原价金额
        $total_original_price = 0;
        $totalNum = 0;
        // 会员折扣
        $discount_vip_price = 0;
        $total_discount_vip_price = 0;
        // 优惠券
        $discount_coupon_price = 0;
        $total_discount_coupon_price = 0;
        // 砍价优惠
        $discount_bargain_price = 0;
        $total_discount_bargain_price = 0;

        // 浮动价格
        $total_float_price = 0;

        $is_coupon = false;
        
        $price_data = [];
        
        foreach ($goods as $key => $item){
            $total_original_price += max(1,intval($item['total'])) * floatval($item['price']);
        }
        
        $is_user_coupon = false;
        foreach ($goods as $key => $item){
            $total = max(1,intval($item['total']));
            $totalNum += $total;
    	    $goods_price = floatval($item['price']);
            $original_price = $goods_price * $total;
            $bargain_goods = $item['bargain_goods'];
            $real_goods_price = $bargain_goods['price'];
            $price = $real_goods_price * $total;

            
            $type = 0;
            $float_price = 0;
            $discount_vip_price = 0;
            $discount_coupon_price = 0;
            $discount_bargain_price = max(0,$original_price - $price);
            
            $discount_price = $discount_vip_price + $discount_coupon_price + $discount_bargain_price;
            
            $total_discount_price += $discount_price;
            
            $total_discount_vip_price += $discount_vip_price;
            $total_discount_coupon_price += $discount_coupon_price;
            $total_discount_bargain_price += $discount_bargain_price;


            $total_price += $price;
            $total_float_price += $float_price;

            // echo "<pre>";
            // print_r($total_price);die;
            
            $price_data[] = array(
                'float_price'=>round($float_price,2),
                'price'=>round($price,2),
                'total_price'=>round($original_price,2),
                'discount_price'=>round($discount_price,2),
                'discount_vip_price'=>round($discount_vip_price,2),
                'discount_coupon_price'=>round($discount_coupon_price,2),
                'discount_bargain_price'=>round($discount_bargain_price,2),
                'user_coupon_id'=>0,
                'type'=>$type,
                'seckill_activity_id'=>0,
                'seckill_goods_id'=>0,
                'pintuan_goods_id'=>0,
                'bargain_goods_id'=>$bargain_goods['id'],
            );
        }
        
        if($delivery_method == 1){
            $express_fee = \app\common\model\bbfxshop\Shippingfee::calculateShippingFee($goods,$address_id,$total_price);
        }
        
        // echo "<pre>";
        // print_r($price_data);die;
        // print_r($total_discount_price);die;
        $result = array(
            "express_fee"=>round($express_fee,2),
            "float_price"=>round($float_price,2),
            "total_price"=>max(0,round($total_price,2)),
            "original_price"=>round($total_original_price,2),
            "discount_price"=>round($total_discount_price,2),
            "discount_vip_price"=>round($total_discount_vip_price,2),
            "discount_coupon_price"=>round($total_discount_coupon_price,2),
            "discount_bargain_price"=>round($total_discount_bargain_price,2),
            "price_data"=>$price_data,
            "totalNum"=>$totalNum
        );

        $coupon = [];
        $is_user_coupon = false;
        if(!empty($coupon) && $is_user_coupon){
            $result['coupon'] = $coupon;
        }
        
        return $result;
    }

    public static function task(){
        self::initGoodsPrice();
    } 

    public static function initGoodsPrice(){

        $list = Db::name("bbfx_bargain_goods")->where(['uniacid'=>UNIACID,'status'=>1,'effective_day'=>['>',0],'etime'=>['<',time()]])->select();
        if(empty($list)){
            return __json(0,"没有商品需要更新");
        }

        try{
            foreach ($list as $key => $item){
                $data = [
                    'price'=>$item['s_price'],
                    'stime'=>strtotime(date("Y-m-d 00:00:00")),
                    'etime'=>strtotime(date("Y-m-d 00:00:00")." +".$item['effective_day']." day")
                ];
                Db::name("bbfx_bargain_goods")->where(["id"=>$item['id']])->update($data);
            }
        }
        catch(\Exception $e){
            return __json(0,$e->getMessage());
        }

        return __json(1,"更新成功");
    } 

    public static function getCategoryList(){
        $where = ["uniacid"=>UNIACID];
        $list = Db::name("bbfx_bargain_goods_category")->where($where)->order("sort desc,id desc")->select();
        return $list;
    } 
}