<?php
namespace app\api\controller\activity;
use app\models\store\Package;
use app\models\store\StoreWholesale;
use app\models\user\User;
use app\models\user\UserBill;
use app\Request;
use crmeb\services\QrcodeService;
use crmeb\services\UtilService;

class WholeController
{
    /**
     * 秒杀产品时间区间
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {

        //秒杀时间段
        $seckillTime = sys_data('whole_time') ?? [];
        $seckillTimeIndex = 0;
        if (count($seckillTime)) {
            foreach ($seckillTime as $key => &$value) {
                $currentHour = date('H');
                $activityEndHour = bcadd((int)$value['time'], (int)$value['continued'], 0);
                if ($activityEndHour > 24) {
                    $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                    $value['state'] = '即将开始';
                    $value['status'] = 2;
                    $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                } else {
                    if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '抢购中';
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                        $value['status'] = 1;
                        if (!$seckillTimeIndex) $seckillTimeIndex = $key;
                    } else if ($currentHour < (int)$value['time']) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '即将开始';
                        $value['status'] = 2;
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                    } else if ($currentHour >= $activityEndHour) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '已结束';
                        $value['status'] = 0;
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                    }
                }
            }
        }
        $data['lovely'] = sys_config('seckill_header_banner');
        if (strstr($data['lovely'], 'http') === false && strlen(trim($data['lovely']))) $data['lovely'] = sys_config('site_url') . $data['lovely'];
        $data['lovely'] = str_replace('\\', '/', $data['lovely']);
        $data['seckillTime'] = $seckillTime;
        $data['seckillTimeIndex'] = $seckillTimeIndex;
        $data['seckillCont'] = StoreWholesale::getWholeContStatus();
        return app('json')->successful($data);
    }

    /**
     * 秒杀产品列表
     * @param Request $request
     * @param $time
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lst(Request $request, $time)
    {
        list($page, $limit) = UtilService::getMore([
            ['page', 0],
            ['limit', 0],
        ], $request, true);
        if (!$time) return app('json')->fail('参数错误');
        $seckillInfo = Package::lst(['time_id'=>$time,'page'=>$page,'limit'=>$limit,'status'=>2]);
        if (count($seckillInfo)) {
            foreach ($seckillInfo['data'] as &$v) {
                $v['price'] = bcadd(bcmul($v['price'],bcdiv(sys_config('pass_on',3),100,2),2),$v['price'],2);
            }
        }
        return app('json')->successful($seckillInfo);
    }

    /**
     * 秒杀产品详情
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function detail(Request $request, $id, $time = 0, $status = 1,$is_news=0)
    {
        $storeInfo = StoreWholesale::getValidProduct($id,'',$is_news);
        if ($storeInfo)
            $storeInfo = $storeInfo->hidden(['cost', 'add_time', 'is_del'])->toArray();
        else
            $storeInfo = [];
        if (!$id || !$storeInfo) return app('json')->fail('商品不存在或已下架!');
        $siteUrl = sys_config('site_url');
        $storeInfo['image'] = set_file_url($storeInfo['image'], $siteUrl);
        $storeInfo['image_base'] = set_file_url($storeInfo['image'], $siteUrl);
        $storeInfo['code_base'] = QrcodeService::getWechatQrcodePath($id . '_seckill_detail_wap.jpg', '/activity/seckill_detail/' . $id . '/' . $time . '/' .$status);
        $uid = $request->uid();
        $storeInfo['uid'] = $uid;
        $data['storeInfo'] = $storeInfo;
        $user = $request->user();
        $data['isSeckillEnd'] = StoreWholesale::checkStatus($id);
        return app('json')->successful($data);
    }
    /**
     * 预约
     * @param Request $request
     */
    public function reserve(Request $request)
    {
        list($whole_id,$time_id,$price,$to_uid,$first_price,$last_id) = UtilService::postMore(
            [
                ['whole_id',0],
                ['time_id',0],
                ['price',0],
                ['to_uid',0],
                ['first_price',0],
                ['last_id',0],
            ],$request,true
        );
        if($whole_id==0) return app('json')->fail('商品不能为空');
        if($time_id==0) return app('json')->fail('时间段不能为空');
        if($price==0) return app('json')->fail('价格不能为0');
        if($to_uid==0) $first_price = $price;

        $rs = Package::reserve($request->uid(),$whole_id,$time_id,$to_uid,$price,$first_price,$last_id);
        if($rs)
        {
            return app('json')->successful($rs);
        }
        else
        {
            return app('json')->fail(Package::getErrorInfo());
        }
    }
    /**
     * 我的记录
     * @param Request $request
     * @return mixed
     */
    public function mylist(Request $request)
    {
        $where = UtilService::postMore(
            [
                ['page',1],
                ['limit',10],
                ['data',''],
                ['status',-4],
            ],$request
        );
        $where['uid'] = $request->uid();
        return app('json')->successful(Package::lst($where));
    }

    /**
     * 上传评证
     * @param Request $request
     */
    public function evaluation(Request $request)
    {
        $where = UtilService::postMore(
            [
                ['pay_evaluation',''],
            ],$request
        );
        if($where['pay_evaluation']=='') return app('json')->fail('上传图片评证');
        if(!Package::be(['uid'=>$request->uid(),'id'=>input('id'),'status'=>0]))return app('json')->fail('参数错误或已上传!');
        $where['submit_time'] = time();
        $where['status'] = 1;
        return app('json')->successful(Package::edit($where,input('id')));
    }

    /**
     * 我的订单
     * @param Request $request
     * @return mixed
     */
    public function order(Request $request)
    {
        $where = UtilService::postMore(
            [
                ['page',1],
                ['limit',0],
                ['status',-4],
            ],$request
        );
        $where['to_uid'] = $request->uid();
        return app('json')->successful(Package::lst($where));
    }

    /**
     * 订单审核
     * @param Request $request
     */
    public function audit(Request $request)
    {
        $where = UtilService::postMore(
            [
                ['re',''],
                ['status',1],
            ],$request
        );
        $id = input('id');
        if(!Package::be(['to_uid'=>$request->uid(),'status'=>1,'id'=>$id])) return app('json')->fail('参数有误或已审核');
        if($where['status']==2)
        {
            $rs = Package::take($id);
        }
        else
        {
            $rs = Package::invalid($id,$where['re']);
        }
        if($rs) return app('json')->successful('审核通过');
        else return app('json')->fail(Package::getErrorInfo());

    }
    /**
     * 新人批发
     * @param Request $request
     */
    public function news(Request $request)
    {
        $time_id = input('time_id',0);
        $where = null;
        if($time_id>0)
        {
            $where['time_id'] = $time_id;
        }
        return app('json')->successful(StoreWholesale::where('is_del',0)->where($where)->where('is_show',1)->select()->toArray());
    }

    /**
     * 批发详情
     * @param Request $request
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(Request $request,$id)
    {
        $info = Package::find($id);
        if (!$info) return app('json')->fail('非法数据');
        $info = $info->toArray();
        $info['whole'] = StoreWholesale::find($info['whole_id'])->toArray();
        $info['isSeckillEnd'] = StoreWholesale::checkStatus($info['whole_id']);
        $info['price'] = bcadd(bcmul($info['price'],bcdiv(sys_config('pass_on',3),100,2),2),$info['price'],2);
        return app('json')->successful($info);
    }

    /**
     * 金豆池
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pool(Request $request)
    {
        $sum = UserBill::where('category','gold')->where('pm',0)->value('sum(number)')?:0;
        $count = UserBill::where('category','gold')->where('pm',0)->value('count(number)')?:0;
        $data = UserBill::where('category','gold')->where('pm',0)->order('id desc')->page(input('page',1),input('limit',10))->select()->toArray();
        foreach ($data as &$v)
        {
            $v['user'] = User::find($v['uid'])->toArray();
        }
        return app('json')->successful(compact('sum','count','data'));
    }

    public function take_delivery(Request $request,$id)
    {
        $info = Package::find($id);
        if (!$info) return app('json')->fail('非法数据');
        $info = $info->toArray();
        if($info['status']!=2)  return app('json')->fail('状态是不是支付完成，不能提货');
        User::where('uid',$info['uid'])->inc('integral',$info['price'])->update();
        $user = $request->user();
        UserBill::income('订单提货',$info['uid'],'integral','package',$info['price'],$info['id'],bcadd($user['integral'],$info['price'],2),'订单收货'.$info['price']);
        Package::edit(['status'=>5],$id);
        return app('json')->successful('提货完成');

    }
}