<?php

namespace Modules\Task\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Illuminate\Support\Collection;
use Jason\Api\Api;
use Modules\Task\Facades\TaskFacade;
use Modules\Task\Models\Task;

class UserController extends Controller
{
    /**
     * Notes: 微信步数
     *
     * @Author: 玄尘
     * @Date: 2022/10/26 9:46
     */
    public function wechatStep(Request $request)
    {

        try {
            $key  = 'steps';
            $task = Task::query()->where('key', $key)->first();
            if ($task && $task->status != Task::STATUS_UP) {
                throw  new \Exception('任务关闭');
            }

            $toDayStartTimestamp = Carbon::now()->startOfDay()->timestamp;//当天开始的时间戳

            $app = Factory::miniProgram([
                'app_id'        => env('WECHAT_MINI_PROGRAM_APPID'),
                'secret'        => env('WECHAT_MINI_PROGRAM_SECRET'),
                'response_type' => 'collection',
            ]);

            $session = $app->auth->session($request->code);
            if ($session->errcode) {
                return $this->failed($session->errmsg);
            }

            $decryptedData = $app->encryptor->decryptData(
                $session->session_key,
                $request->iv,
                $request->encryptData
            );

            $list = collect($decryptedData['stepInfoList']);

            if ($list->isNotEmpty()) {
                $toDay = $list->where('timestamp', $toDayStartTimestamp)->first();
                if ($toDay) {
                    TaskFacade::do($key, Api::userId(), [
                        'steps' => $toDay['step']
                    ], $toDay['step']);
                }

                if ($toDay['step'] >= $task->task_number) {
                    return $this->success('任务完成');
                } else {
                    throw new  \Exception('您今天的步数未达标');
                }
            } else {
                throw new  \Exception('未获取到微信运动数据');
            }


        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }
    }

}
