<?php
declare (strict_types=1);

namespace app\api\controller;

use think\facade\Db;

class Index extends Base
{
    public function index()
    {
        return '您好！这是一个[api]示例应用';
    }

    /**
     * 注册
     */
    public function reg()
    {
        $param = request()->param();
        $rules = [
            "login_name" => "require|length:2,25",
            'password' => 'require|length:6,25',
            'repassword' => 'require|confirm:password',
        ];
        $this->autoValid($rules, $param);


        // 启动事务，用事务实现注册
        $res = $this->regTrans($param);
        if ($res["code"] != 0) {
            $this->error($res['msg'], $res["code"]);
        }
        $this->success($res['data']);
    }

    /**
     * 注册事务
     */
    private function regTrans($param)
    {
        Db::startTrans();
        try {
            $res = \app\common\model\User::regUser($param["login_name"], $param["password"]);
            if ($res["code"] != 0) {
                // 回滚事务
                Db::rollback();
                return $res;
            }
            $res = \app\common\model\User::login($param["login_name"], $param["password"]);
            if ($res["code"] != 0) {
                // 回滚事务c
                Db::rollback();
                return $res;
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return returnFormat(9999, (string)$e);
        }


        return $res;
    }

    /**
     * 登录
     */
    public function login()
    {
        $param = request()->param();
        $rules = [
            "login_name" => "require|length:2,25",
            'password' => 'require|length:6,25',
        ];
        $this->autoValid($rules, $param);
        $res = \app\common\model\User::login($param["login_name"], $param["password"]);
        if ($res["code"] != 0) {
            $this->error($res['msg'], $res["code"]);
        }
        $this->success($res['data']);
    }

}
