<?php

namespace app\common\api;

use app\common\model\MessageRecord;

class MessageRecordApi {

    public static function getList($params = []) {
        $where = [];
        $name = $params["name"];
        $phone = $params["phone"];
        $type = $params["type"];
        $state = $params["state"];
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        if ($name) {
            $where[] = ["name", "like", "%{$name}%"];
        }
        if ($phone) {
            $where[] = ["phone", "like", "%{$phone}%"];
        }
        if ($type) {
            $where[] = ["type", "=", "{$type}"];
        }
        if ($state) {
            $where[] = ["type", "=", "{$state}"];
        }
        $count = MessageRecord::whereOr($where)->count();
        $list = MessageRecord::whereOr($where)
                        ->order(["createTime" => $order])
                        ->limit($offset, $limit)
                        ->select()->toArray();
        return ["total" => $count, "rows" => $list];
    }

    public static function checkVerificationCode($phone, $code) {
        $response = new \stdClass();
        $response->code = 500;
        $codeResult = MessageRecord::where('smsType', 1)->where('phone', $phone)->order('createTime', 'desc')->find();

        if (!$codeResult) {
            $response->msg = "请先发送验证码";
            return $response;
        }
        if (!$code) {
            $response->msg = "请输入手机验证码";
            return $response;
        }
        if ($codeResult["params"] != $code) {
            $response->msg = "验证码错误";
            return $response;
        }
        if (time() - strtotime($codeResult['createTime']) > 300) {
            $response->msg = "验证码过期，请重新发送";
            return $response;
        }
        $response->code = 200;
        return $response;
    }

}
