<?php
namespace app\models\store;
use app\models\system\SystemUserLevel;
use app\models\user\User;
use app\models\user\UserBill;
use crmeb\basic\BaseModel;
use crmeb\services\UtilService;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Log;
use think\Model;

class Package extends BaseModel
{
    use ModelTrait;

    /**
     * 预约
     * @param $uid
     * @param $package_manager
     * @param $price
     * @param $day
     * @param $proportion
     * @return Package|bool|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function reserve($uid,$whole_id,$time_id,$to_uid,$price,$first_price,$last_id)
    {
        $user = User::find($uid);
        $data['uid'] = $uid;
        $data['whole_id'] = $whole_id;
        $data['time_id'] = $time_id;
        $data['first_price'] = $first_price;
        $data['last_id'] = $last_id;
        $data['price'] = $price;
        if(empty($user['phone']) || empty($user['wx_no']) || empty($user['alipay_no'])) return self::setErrorInfo('请点我的到个人中设置，完善信息后下单!');
        if($to_uid==0)
        {
            $stock = StoreWholesale::where('id',$whole_id)->value('stock');
            if($stock<1)  return self::setErrorInfo('库存不足!');
        }
        if(cache('reserve_'.$uid,1) &&  false) return self::setErrorInfo('你已报名，无需重复报名');
        if($last_id>0 && self::where('last_id',$last_id)->where('uid',$uid)->find())
        {
            return self::setErrorInfo('你已报名，无需重复报名');
        }elseif($last_id>0 && self::where('last_id',$last_id)->where('status','>',-1)->find())
        {
            return self::setErrorInfo('该订单已有预约');
        }
        else
        {
            cache('reserve_'.$uid,1,60);
        }

        $integral = bcmul($price,bcdiv(sys_config('reserve_integral'),100,2),2);
        if($integral>$user['gold'])
        {
            cache('reserve_'.$uid,null);
            return self::setErrorInfo('金豆不足，请先买金豆专区');
        }
        if($last_id>0 && self::where('id',$last_id)->value('status')==3) {
            cache('reserve_'.$uid,null);
            return self::setErrorInfo('已有用户预约，换个商品预约');
        }
        $data['add_time'] = time();
        $data['order_id'] = self::getNewOrderId();
        if($to_uid==0)
        {
            $to_uid = User::where('is_sys', 1)->order('sys_pay asc,uid asc')->value('uid');
            User::where('uid',$to_uid)->inc('sys_pay',1)->update();
        }
        if(intval($to_uid)==0)  return self::setErrorInfo('系统未设置发包用户信息，联系客服设置发包用户，稍后在来！');
        $data['to_uid'] = $to_uid;
        self::beginTrans();
        try{
            $data['use_integral'] = $integral;
            $res = self::create($data);
            User::where('uid',$uid)->dec('gold',$integral)->update();
            UserBill::expend("预约扣金豆",$uid,'gold','pay_money',$integral,$res['id'],bcsub($user['gold'],$integral,2),'预约扣除'.$integral."金豆");
            if($last_id==0) {
                User::edit(['is_whole' => 1], $uid);
                StoreWholesale::where('id',$whole_id)->inc('sales',1)->dec('stock',1)->update();
            }
            if($last_id>0) self::where('id',$last_id)->update(['status'=>3]);
            self::commitTrans();
            return $res->toArray();

        }catch (Exception $e)
        {
            cache('reserve_'.$uid,null);
            Log::error('预约出错：' . $e->getLine().'--'.$e->getMessage());
            return self::setErrorInfo($e->getMessage(),true);
        }
    }
    /**
     * 生成订单唯一id
     * @param $uid 用户uid
     * @return string
     */
    public static function getNewOrderId()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'pk' . $msectime . mt_rand(10000, 99999);
        while (self::be(['order_id' => $orderId])) $orderId = 'pk' . $msectime . mt_rand(10000, 99999);
        return $orderId;
    }


    /**
     * 我的订单
     * @return bool|string
     */
    public static function getlist()
    {
        $rs = sys_data('package_manager');
        $am= explode("~",sys_config('start_time'));
        $pm= explode("~",sys_config('end_time'));
        foreach ($rs as &$v) {
            $v['cts'] =self::where('package_manager',$v['id'])->where('add_time','>=',strtotime(date("Y-m-d ")))->where('add_time','<',strtotime(date("Y-m-d ").$v['end']))->count();
            $v['cts'] = bcadd($v['virtual'],$v['cts']);
        }

        return $rs;
    }

    /**
     * 收货确认
     * @param $id
     */
    public static function take($id)
    {
        $info = self::find($id);
        $data['status'] = 2;
        $data['paid'] = 1;
        $data['pay_time'] = time();
        self::beginTrans();
        try {
            $gold_bond = bcmul($info['price'],bcdiv(sys_config('gold_bond'),100,3),2);
            User::where('uid',$info['uid'])->inc('integral',$gold_bond)->update();
            $user = User::where('uid',$info['uid'])->find();
            UserBill::income('订单金券收益',$info['uid'],'integral','package',$gold_bond,$info['id'],$user['gold'],'订单金券收益'.$gold_bond);
            $res = self::edit($data,$id);
            /*

            User::where('uid',$info['to_uid'])->inc('brokerage_price',$confirm_receipt)->update();
            $to_user = User::where('uid',$info['to_uid'])->find();
            UserBill::income('订单确认收益',$info['to_uid'],'now_money','brokerage',$confirm_receipt,$info['id'],$to_user['brokerage_price'],'订单确认收益'.$confirm_receipt);
            */
            if($info['last_id']>0) self::edit(['status'=>4],$info['last_id']);
            self::commitTrans();
        }
        catch (Exception $e)
        {
            Log::error('收货错误：' .$e->getFile().'行'.$e->getLine()."原因:".$e->getMessage());
            self::setErrorInfo('收货确认错误',true);
        }
        return true;

    }

    /**
     * 订单无效
     * @param $id
     */
    public static function invalid($id,$re='')
    {
        $data['status'] = -1;
        $data['re'] = $re;
        $last_id = self::where('id',$id)->value('last_id');
        $info = self::find($id);
        if($last_id>0) self::edit(['status'=>2],$last_id); else StoreWholesale::where('id',$info['whole_id'])->dec('sales',1)->inc('stock',1)->update();
        return self::edit($data,$id);
    }

    /**
     * 支付超时
     */
    public static function time_out()
    {
        $list = self::where('status',0)->where('add_time','<',strtotime("-".sys_config('order_whole_time')." hour"))->select();
        foreach ($list as $v)
        {
            if($v['last_id']>0) self::edit(['status'=>2],$v['last_id']); else StoreWholesale::where('id',$v['whole_id'])->dec('sales',1)->inc('stock',1)->update();
            self::edit(['status'=>-2],$v['id']);
        }
        return true;
    }

    /**
     * 收货确认超时
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function take_outs()
    {
        $data['status'] = 2;
        $data['paid'] = 1;
        $list = self::where('pay_time', '<', strtotime("-" . sys_config('order_whole_time') . " hour"))->where('status',1)->select()->toArray();
        self::beginTrans();
        try {
            foreach ($list as $info) {
                $gold_bond = bcmul($info['price'],bcdiv(sys_config('gold_bond'),100,3),2);
                User::where('uid',$info['uid'])->inc('integral',$gold_bond)->update();
                $user = User::where('uid',$info['uid'])->find();
                UserBill::income('订单金券收益',$info['uid'],'integral','package',$gold_bond,$info['id'],$user['gold'],'订单金券收益'.$gold_bond);
                $res = self::edit($data,$info['id']);
                $to_user = User::where('uid', $info['to_uid'])->find();
                if ($info['last_id'] > 0) self::edit(['status' => 4], $info['last_id']);
                self::edit($data, $info['id']);
                $package_income = bcmul($info['price'], bcdiv(sys_config('package_income'), 100, 3), 2);
                User::where('uid', $info['to_uid'])->dec('gold', $package_income)->update();
                if($to_user['gold']<=0)
                {
                      User::where('uid', $info['to_uid'])->update(['gold'=>0]);
                      continue;
                }
                UserBill::income('扣除收益', $info['to_uid'], 'gold', 'dec', $package_income, $info['id'], $to_user['gold'], '订单未确认收货系统确认，扣除收益' .$package_income );

            }
        } catch (Exception $e) {
            Log::error('收货错误：' . $e->getFile() . '行' . $e->getLine() . "原因:" . $e->getMessage());
            self::setErrorInfo('收货确认错误', true);
        }
        self::commitTrans();
        return true;
    }
    public static function take_out($id)
    {
        $info = self::where('submit_time','<',strtotime("-".sys_config('order_whole_time')." hour"))->where('id',$id)->find();
        if($info)
        {
            $data['status'] = 2;
            $data['paid'] = 1;
            $data['pay_time'] = time();
            self::beginTrans();
            try {
                $package_income = bcmul($info['price'], bcdiv(sys_config('package_income'), 100, 3), 2);
                User::where('uid', $info['to_uid'])->dec('gold', $package_income)->update();
                $to_user = User::where('uid', $info['to_uid'])->find();
                UserBill::expend('扣除收益', $info['to_uid'], 'gold', 'dec', $package_income, $info['id'], $to_user['gold'], '订单未确认收货系统确认，扣除收益' .$package_income );
                if($to_user['gold']<=0)
                {
                    User::where('uid', $info['to_uid'])->update(['gold'=>0]);
                }
                if ($info['last_id'] > 0) self::edit(['status' => 4], $info['last_id']);
                self::edit($data,$id);
                self::commitTrans();
            }
            catch (Exception $e)
            {
                Log::error('收货错误：' .$e->getFile().'行'.$e->getLine()."原因:".$e->getMessage());
                self::setErrorInfo('收货确认错误',true);
            }
            return true;
        }
        else
        {
            return self::setErrorInfo('未到'.sys_config('order_whole_time')."小时，不能后台确认");
        }
    }
    /**
     * 获取中奖用户编号
     * 先根据投入积分求出未中奖用户，然后在获取中奖用户
     * @param $user
     * @return array
     */
    public static function getrand($user, $prize_person_num = 1)
    {
        $user_arr = []; //随机数组
        $n = 0;
        $count = 0;$sum = 0;
        foreach ($user as $v)
        {
            $sum += bcadd(100,0,0);
        }
        foreach ($user as $v) {
            $user_arr [$n] = [
                'id' => $v['id'],
                "start" => $count,
                "end" => $count + ($sum-bcadd(100,0,0)),
            ];
            $n++;
            $count +=($sum-bcadd(100,0,0))+1;
        }
        $prize_arr = [];
        $n = $prize_person_num;   //中奖人数
        while (sizeof($prize_arr) < $n) {
            $random = mt_rand(0, $count);   //随机数
            foreach ($user_arr as $item) {
                if ($random >= $item['start'] && $random <= $item['end'] && !in_array($item['id'],$prize_arr)) {
                    $prize_arr[] = $item['id'];
                    break;
                }
            }
        }
        return $prize_arr;
    }

    /**
     * 获取列表
     * @param $where
     */
    public static function lst($where)
    {
        $model = new self;
        if(isset($where['data']) && $where['data']!='')
        {
            $model = $model->getModelTime($where,$model);
        }
        else
        {
            $model = $model->where('pay_time','<',strtotime("today"));
        }
        if(isset($where['uid']) && $where['uid']>0) $model = $model->where('uid',$where['uid']);
        if(isset($where['to_uid']) && $where['to_uid']>0) $model = $model->where('to_uid',$where['to_uid']);
        if(isset($where['status']) && $where['status']>-4) $model = $model->where('status',$where['status']);
        if(isset($where['time_id']) && $where['time_id']>-4) $model = $model->where('time_id',$where['time_id']);
        $count = $model->value('count(id)')?:0;
        $data = $model->order('id desc')->page($where['page'],$where['limit'])->select()->toarray();
        $whole = [];
        foreach (sys_data('whole_time') as $v)
        {
            $whole[$v['id']] = $v['time'];
        }
        foreach ($data as &$v)
        {
            $v['time_id_title'] = $whole[$v['time_id']];
            if($v['whole_id']) {
                $v['whole'] = StoreWholesale::find($v['whole_id']);
            }
            else
            {
                $v['whole'] = [];
            }
            $v['user'] = User::where('uid',$v['uid'])->field('real_name,avatar,phone')->find()->toArray();
            if($v['to_uid']>0) {
                $v['touser'] = User::where('uid', $v['to_uid'])->field('real_name,avatar,phone,wx_qr,wx_no,alipay_no,alipay_name,account_Bank,bank_card,bank_name,bank_branch')->find()->toArray();
            }
        }
        return compact('count','data');
    }



    /**
     * 获取会员升级订单
     */
    public static function orderlist($where)
    {
        $model = new self;
        if(isset($where['data']) && $where['data'] !='') $model = $model->getModelTime($where,$model,"add_time");
        if(isset($where['paid']) && $where['paid'] >-1)  $model = $model->where('paid',$where['paid']);
        if(isset($where['status']) && $where['status'] >-4)  $model = $model->where('status',$where['status']);
        if(isset($where['key']) && $where['key'] !='') $model = $model->where('order_id','like',"%".$where['key']."%");
        $model = $model->order('id desc');
        $whole = [];
        foreach (sys_data('whole_time') as $v)
        {
            $whole[$v['id']] = $v['time'];
        }
        return self::page($model, function ($v)use($whole) {
            $v['time_id_title'] = $whole[$v['time_id']];
            $v['user'] = User::where('uid',$v['uid'])->field('nickname,real_name,avatar,phone')->find()->toArray();
            if($v['to_uid']>0) {
                $v['touser'] = User::where('uid', $v['to_uid'])->field('real_name,real_name,avatar,phone,wx_qr,wx_no,alipay_no,alipay_name,account_Bank,bank_card,bank_name,bank_branch')->find()->toArray();
            }
            else
            {
                $v['touser'] = null;
            }
        }, $where);
    }
}
