<?php

namespace Modules\Audience\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Channel\Services\WechatMinprogram\WechatMinprogramUserService;

class AudienceController extends  CatchController
{
    use ValidatesRequests;
    /**
     * 用户详情
     * @param Request $request
     */
    public function detail(Request $request) {
        $this->validate($request, [
            'uid' => 'required'
        ]);
        $uid = $request->input('uid');
        $userInfo = DB::table(getMiniProgramTableName(1, 'users'))->where('id', $uid)->first();
        if (!$userInfo) {
            return null;
        }
        $ranseRecordTable = 'ranse_record_'.($uid % 8);
        $ranseIds = DB::table('promotions')
            ->where('uid', $this->getLoginUserId())
            ->select('id')->pluck('id');
        if($ranseIds->isEmpty()) {
            return null;
        }
        $ranseRecord = DB::table($ranseRecordTable)->whereIn('ranse_id', $ranseIds)
            ->orderBy('created_at', 'desc')
            ->first();
        if(!$ranseRecord) {
            return null;
        }

        $totalChargeCount = DB::table('orders')
            ->where('uid', $uid)
            ->whereIn('promotion_id', $ranseIds)
            ->where('status', '<>' ,'UNPAID')
            ->count();

        $result = [
            'uid' => $userInfo->id,
            'ranse_start_at' => $ranseRecord->created_at ?: "",
            'charge_coin' => $userInfo->charge_coin,
            'reward_coin' => $userInfo->reward_coin,
            'total_charge_count' => $totalChargeCount,
            'miniprogram_name' => DB::table('miniprogram')
                ->where('id', $userInfo->miniprogram_id)->value('name'),
            'user_created_at' => $userInfo->created_at,
        ];

        return array_merge($result, WechatMinprogramUserService::getLevelText($uid));
    }
}
