<?php

namespace App\Http\Controllers\Wap\Other;

use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserService;
use App\Modules\User\Services\UserWealthyOperateRecordService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class XiyueController extends Controller
{
    public function xiyuePayNotity(Request $request){
        $openid = $request->post('openid');
        $sign = $request->post('sign');
        $amount = $request->post('amount');
        $amount = (int)$amount;
        $mySign = _sign(compact('openid','amount'),'8T5MJy4FsJoZspq8');
        if($sign != $mySign){
            return response()->error('PARAM_ERROR');
        }
        $user = UserService::getUserByUnionAndChannelId($openid,6985);
        if(!$user){
            $user =  UserService::addUser(
                ['openid' => $openid,
                    'unionid' => $openid,
                    'distribution_channel_id' =>6985,
                    'send_order_id'=>0,
                    'is_new'=>1,
                    'register_ip'=>''
                ]);

        }
        $this->_xiyueConsume($openid,$amount);

        $result = DB::table('xiyue_zsy_users')->where('uid',$user->id)->select('id')->first();
        if(!$result){
            DB::table('xiyue_zsy_users')->insert([
                'uid'=>$user->id,
                'xiyue_uid'=>0,
                'openid'=>$openid,
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s')
            ]);
        }
        YearOrderService::save_year_order([
            'uid'=>$user->id,
            'fee'=>0,
            'send_order_id'=>0,
            'distribution_channel_id'=>6985
        ]);
        UserWealthyOperateRecordService::create($user->id,365,6985,'yearRecharge',20190828);
        return response()->success();
    }

    public function getUserBalance(Request $request){
        $openid = $request->post('openid');
        $sign = $request->post('sign');
        $mySign = _sign(compact('openid'),'8T5MJy4FsJoZspq8');
        if($sign != $mySign){
            return response()->error('PARAM_ERROR');
        }
        //$user = UserService::getUserByUnionAndChannelId($openid,6985);
        $user = $this->selectXiyueUser($openid);
        return response()->success($user);
    }

    private function _xiyueConsume($openid,$amount){
        if($amount <= 0){
            return false;
        }
        //$user = UserService::getUserByOpenidAndChannelId($openid,6985);
        $user = $this->selectXiyueUser($openid);
        if(!$user) return false;
        /*if($amount > $user->balance || $amount > $user->charge_balance){
            return false;
        }*/
        $consume_amount = $amount;
        if($amount > $user->charge_balance){
            $consume_amount = $user->charge_balance;
        }
        if(!$consume_amount)return false;
        $data = [];
        $data['uid'] = $user->id;
        $data['type'] = 'xiyueconsume';
        $data['attach'] = '';
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['balance'] = $amount;
        if ($user->charge_balance >= $consume_amount) {
            $data['charge_balance'] = $consume_amount;
            $data['reward_balance'] = 0;
            $user->balance -= $consume_amount;
            $user->charge_balance -= $consume_amount;
        } elseif ($user->charge_balance > 0) {
            $data['charge_balance'] = $user->charge_balance;
            $data['reward_balance'] = $consume_amount - $user->charge_balance;
            $reward = $consume_amount - $user->charge_balance;
            $user->balance -= $consume_amount;
            $user->charge_balance = 0;
            $user->reward_balance -= $reward;
        } else {
            $data['charge_balance'] = 0;
            $data['reward_balance'] = $consume_amount;
            $user->balance -= $consume_amount;
            $user->reward_balance -=  $consume_amount;
        }
        $user->save();
        DB::table('user_other_consume_record')->insert($data);
        return true;
    }

    private function selectXiyueUser($openid){
        $user = UserService::getUserByOpenidAndChannelId($openid,6985);
        if($user->charge_balance >0)  return $user;
        $all_user = UserService::getUserByOpenid($openid);
        $select_user = null;
        $temp_time = 0;
        foreach ($all_user as $user_item){
            if($user_item->distribution_channel_id == 6985) continue;
            if($user_item->charge_balance >0){
                $last_read_info = ReadRecordService::getByField($user_item->id,'last_read');
                if(!$last_read_info) continue;
                list($bid,$cid,$time) = explode('_',$last_read_info);
                if($time >$temp_time) {
                    $select_user = $user_item;
                    $temp_time = $time;
                }
            }
        }
        if(!$select_user) return $user;
        return $select_user;
    }

    public function xiyueConsume(Request $request){
        $openid = $request->post('openid');
        $sign = $request->post('sign');
        $amount = $request->post('amount');
        $mySign = _sign(compact('openid','amount'),'8T5MJy4FsJoZspq8');
        if(!$openid || !$amount || ($sign != $mySign)){
            return response()->error('PARAM_ERROR');
        }

        $user = UserService::getUserByOpenidAndChannelId($openid,6985);

        if(!$user) return response()->error('PARAM_ERROR');

        if($amount <= 0){
            return response()->error('PARAM_ERROR');
        }

        if($amount > $user->balance || $amount > $user->charge_balance){
            return response()->error('WAP_INSUFFICIENT_BALANCE');
        }
        $data = [];
        $data['uid'] = $user->id;
        $data['type'] = 'xiyueconsume';
        $data['attach'] = '';
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['balance'] = $amount;
        if ($user->charge_balance >= $amount) {
            $data['charge_balance'] = $amount;
            $data['reward_balance'] = 0;
            $user->balance -= $amount;
            $user->charge_balance -= $amount;
        } elseif ($user->charge_balance > 0) {
            $data['charge_balance'] = $user->charge_balance;
            $data['reward_balance'] = $amount - $user->charge_balance;
            $reward = $amount - $user->charge_balance;
            $user->balance -= $amount;
            $user->charge_balance = 0;
            $user->reward_balance -= $reward;
        } else {
            $data['charge_balance'] = 0;
            $data['reward_balance'] = $amount;
            $user->balance -= $amount;
            $user->reward_balance -=  $amount;
        }
        $user->save();
        DB::table('user_other_consume_record')->insert($data);
        return response()->success($user);
    }

}
