<?php

namespace app\api\controller\many;


use app\models\many\AuctionPay;
use app\models\many\Many;
use app\models\many\ManyDiscipline;
use app\models\many\ManyGreen;
use app\models\many\ManyOrder;
use app\models\store\StoreOrder;
use app\models\user\User;
use app\models\user\UserBill;
use app\Request;
use crmeb\services\GroupDataService;
use crmeb\services\QrcodeService;
use crmeb\services\SystemConfigService;
use crmeb\services\UtilService;
use crmeb\services\upload\Upload;
use think\facade\Db;
use think\facade\Validate;

/**
 * 账单类
 * Class UserBillController
 * @package app\api\controller\user
 */
class ManyController
{
    /**
     * 众筹列表
     * @param Request $request
     * @return mixed
     */
    public function many(Request $request)
    {
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 10],
            ['name']
        ]);
        $list = \app\models\many\Many::list($where);
        return app('json')->success($list);
    }


    /**
     * 众筹详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function details()
    {
        $where = UtilService::getMore([
            ['id'],
        ]);
        $many = Many::find($where['id']);
        if (!$many) return app('json')->fail('没有该场次');
        return app('json')->success($many->toArray());
    }

    /**
     * 投注
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function purchase(Request $request)
    {
        $data = UtilService::postMore([
            ['id'],
            ['price']
        ]);
        Db::startTrans();
        $many = Many::where('id', $data['id'])->lock(true)->find();
        $surplus = $this->surplus($data['id'], $request->uid(),1);
        $user = User::where('uid', $request->uid())->find();
        if (!$many) return app('json')->fail('场次不存在');
        if(!preg_match("/^[1-9][0-9]*$/" ,$data['price'])) return app('json')->fail('请投注整数');
        if ($many['number'] >= $many['money']) return app('json')->fail('已完成无法种树');
        if ($many['status'] == 0) return app('json')->fail('未开启');
        if ($many['end_time'] < time()) return app('json')->fail('已结束');
        if (($many['number']+$data['price']) > $many['money']) return app('json')->fail('还能最大种树'.($many['money']-$many['number']));
        if ($data['price'] > $many['single']) return app('json')->fail('单次最大可以种树'.$many['single']);
        if ($surplus < $data['price']) return app('json')->fail('超过最大可种树额度');
        if (ManyOrder::where('many_id', $many['id'])->where('uid', $user['uid'])->where('stage', $many['stage'])->count() >= 3) return app('json')->fail('超过单场最大抢购数');
        if ($many['add_time'] > time()){
            if ($many['add_time'] - 600 > time()) return app('json')->fail('只能提前十分钟进行,提前种树');
            $advance = SystemConfigService::get('advance');
            $integral = $data['price']* ($advance/100);
            if ($user['integral'] < $integral) return app('json')->fail('阳光不足无法提前投注');
            $user['integral'] -= $integral;
            UserBill::expend('扣除阳光积分', $user['uid'], 'integral', 'ad_integral', $integral, 0, $user['integral'], '提前投注扣除'.$integral.'阳光');
        }
        if ($user['white_integral'] < $data['price']) return app('json')->fail('肥料不够');
        try {
            $many['number'] += round($data['price'], 2);
            $user['white_integral'] -= $data['price'];
            UserBill::expend('扣除肥料', $user['uid'], 'white_integral', 'bet_white_integral', $data['price'], 0,$user['white_integral'],'使用肥料,参与种树-》'.$many['name'].'期数-》'.$many['stage'].'-成功');
            $user->save();
            ManyOrder::create([
                'order_id' => StoreOrder::getNewOrderId(),
                'many_id' => $many['id'],
                'uid' => $user['uid'],
                'stage' => $many['stage'],
                'price' => $data['price'],
            ]);
            if ($many['number'] >= $many['money']){
                $many['suc'] = 1;// 众筹成功
                $many['status'] = 0;// 众筹成功
                ManyDiscipline::create(['many_id' => $many['id'], 'stage' => $many['stage'], 'status' => 1]);// 成功记录
                ManyOrder::order_return($many);
                if ($many['stage'] >= 4){
                    // 期数如果大于等于4
                    $stage = $many['stage'] - 3;
                    ManyOrder::where('many_id', $many['id'])->where('stage', $stage)->update(['is_return' => 1]);// 成功后添加返还状态
                }
            }
            $many->save();
            Db::commit();
            return app('json')->success('种树成功');
        } catch (\Exception $e) {
            Db::rollback();
            return app('json')->fail($e->getMessage());
        }

    }

    /**
     * 还有多少可投注
     * @param $id
     * @param $type
     * @return float|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function surplus($id, $uid,$type = 0)
    {
        if ($type > 0){
            $many = Many::where('id', $id)->find();
            if (!$many) return app('json')->fail('场次不存在');
            $many_order = ManyOrder::where('many_id', $id)->where('uid', $uid)->where('stage', $many['stage'])->sum('price');
            $price = ($many['upper_limit'] - $many_order); // 还可以投注额度
            return $price;
        }else{
            $many = Many::where('id', $id)->find();
            if (!$many) return app('json')->fail('场次不存在');
            $many_order = ManyOrder::where('many_id', $id)->where('uid', $uid)->where('stage', $many['stage'])->sum('price');
            $data['price'] = ($many['upper_limit'] - $many_order); // 还可以投注额度

            return app('json')->fail($data);
        }
    }

    /**
     * 添加收款方式
     * @param Request $request
     * @return void
     */
    public function pay(Request $request)
    {
        $data = UtilService::postMore([
            ['payment'],
            ['image'],
            ['bank'],
            ['name'],
            ['type'],
            ['phone'],
            ['bank_name']
        ], $request);
        if (!$data['type'])  return app('json')->fail('数据传入错误');
        $data['uid'] =$request->uid();
        $model = new AuctionPay();
        $pay = $model->where([['uid', '=', $request->uid()], ['type', '=', $data['type']]])->find();
        $res = Validate::rule([
            'phone' => 'mobile'
        ]);
        $res->message([
            'phone.mobile' => '请填写正确手机格式'
        ]);
        if (!$res->check($data)){
            return app('json')->fail($res->getError());
        }
        if (!empty($pay)){
            if ($data['type'] == 1 ){
                // 微信收款方式
                if (!$data['payment'])  return app('json')->fail('微信账号不能为空');
                if (!$data['image'])  return app('json')->fail('二维码不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                $pay['payment'] = $data['payment'];
                $pay['image'] = $data['image'];
                $pay['name'] = $data['name'];
                $pay['phone'] = $data['phone'];
            }elseif ($data['type'] == 2){
                // 支付宝收款方式
                if (!$data['payment'])  return app('json')->fail('支付宝账号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                $pay['payment'] = $data['payment'];
                $pay['name'] = $data['name'];
            }elseif ($data['type'] == 3){
                // 银行卡收款方式
                if (!$data['payment'])  return app('json')->fail('银行卡号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['bank'])  return app('json')->fail('开户行不能为空');
                $pay['payment'] = $data['payment'];
                $pay['bank'] = $data['bank'];
                $pay['name'] = $data['name'];

            }
            $res = $pay->save();
            if ($res) return app('json')->successful('修改成功');
            return app('json')->fail('修改失败');
        }else{
            if ($data['type'] == 1 ){
                // 微信收款方式
                if (!$data['payment'])  return app('json')->fail('微信账号不能为空');
                if (!$data['image'])  return app('json')->fail('二维码不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');

            }elseif ($data['type'] == 2){
                // 支付宝收款方式
                if (!$data['payment'])  return app('json')->fail('支付宝账号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
            }elseif ($data['type'] == 3){
                // 银行卡收款方式
                if (!$data['payment'])  return app('json')->fail('银行卡号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['bank'])  return app('json')->fail('开户行不能为空');
            }
            $res = $model->save($data);
            if ($res) return app('json')->successful('添加成功');
            return app('json')->fail('添加失败');
        }
    }

    /**
     * 收款方式详情
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pay_list(Request $request)
    {
        $model = new AuctionPay();
        $list = $model->where('uid', $request->uid())->select();

        $list = empty($list)? []: $list->toArray();
        $data['wx'] = [];
        $data['zfb'] = [];
        $data['bank'] = [];
        foreach ($list as $k => $v){
            if ($v['type'] == 1){
                $data['wx'] = $v;
            }elseif ($v['type'] == 2){
                $data['zfb'] = $v;
            }elseif ($v['type'] == 3){
                $data['bank'] = $v;
            }
        }
        return app('json')->successful($data);
    }



}