<?php

namespace app\mobile\logic;

use app\model\AccountModel;
use app\model\AccountTokenModel;
use app\model\CommonModel;
use app\model\GroupModel;
use app\model\ThemeModel;
use app\model\VideoModel;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\response\Json;

class AccountLogic extends BaseLogic
{
    //登录
    public static function login(array $data = []): Json
    {
        Db::startTrans();
        try {

            $rs = AccountModel::field('id,username,name,password,salt,starttime,expiretime,status')
                ->where(['is_del' => CommonModel::$del_normal, 'username' => $data['username']])
                ->findOrEmpty();

            if ($rs->isEmpty()) throw new Exception('该卡号不存在,请仔细核对');
            if (get_password($data['password'], $rs->salt) != $rs->password) throw new Exception('密码错误');

            $date = date('Y-m-d H:i:s');

            if (($date < $rs->starttime) || ($date > $rs->expiretime)) throw new Exception('该卡不在有效期内');


            $update_data = ['updaterid' => $rs->id, 'updater' => $rs->name, 'updatetime' => $date];

            if ($rs->status == AccountModel::$status_not_active) {
                //处理激活信息
                $update_data['status'] = AccountModel::$status_activated;
                $update_data['activetime'] = $date;
            }


            //更新账户相关信息
            AccountModel::where(['is_del' => CommonModel::$del_normal, 'id' => $rs->id])->save($update_data);

            //维护token
            $token = base64_encode($rs->username . $rs->salt . (string)time());

            $res = AccountTokenModel::field('id')
                ->where('accountid', $rs->id)
                ->findOrEmpty()
                ->isEmpty();

            $expire = Config::get('common.expire');
            if ($res) AccountTokenModel::create(['token' => $token, 'expiretime' => date('Y-m-d H:i:s', time() + $expire), 'accountid' => $rs->id]);
            else AccountTokenModel::where(['accountid' => $rs->id])->update(['token' => $token, 'expiretime' => date('Y-m-d H:i:s', time() + $expire)]);


            //获取微信网页授权URL
//            $url = '';
//            if ($data['callback_url'] != '') $url = WechatLogic::getOauthRedirect($data['callback_url'], $token);

            Db::commit();

//            return json_show($url ? CommonModel::$error_jump : CommonModel::$success, '登录成功', ['token' => $token, 'url' => $url]);
            return json_show(CommonModel::$success, '登录成功', ['token' => $token]);

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_param, $exception->getMessage());
        }

    }

    //登出
    public static function logout(): Json
    {

        $info = AccountTokenModel::where(['accountid' => self::$aid])->save(['token' => '', 'expiretime' => date('Y-m-d H:i:s')]);

        return $info ? json_show(CommonModel::$success, '登出成功') : json_show(CommonModel::$error_param, '登出失败');

    }

    //详情
    public static function info(): Json
    {

        $info = AccountModel::where(['id' => self::$aid])
            ->field('id,username,mobile,name,starttime,expiretime')
            ->findOrEmpty()
            ->toArray();

        return $info ? json_show(CommonModel::$success, '获取账户详情成功', $info) : json_show(CommonModel::$error_token, '账户为空');

    }

    //更改密码
    public static function updatePassword(array $data = []): Json
    {
        $rs = AccountModel::field('id,password,salt')
            ->where(['is_del' => CommonModel::$del_normal, 'id' => self::$aid])
            ->findOrEmpty()
            ->getData();//password,salt这两个字段在模型里定义了隐藏,所以要在这里使用getData方法获取原始数据

        if (empty($rs)) return json_show(CommonModel::$error_token, '该账户不存在');

        if (get_password($data['old_password'], $rs['salt']) != $rs['password']) return json_show(CommonModel::$error_param, '密码错误');

        $salt = randomkeys(6);
        $password = get_password($data['new_password'], $salt);

        $da = [
            'pwd' => $data['new_password'],
            'salt' => $salt,
            'password' => $password,
            'updaterid' => self::$aid,
            'updater' => self::$aname,
            'updatetime' => date('Y-m-d H:i:s'),
        ];

        $rs = AccountModel::where(['id' => self::$aid, 'is_del' => CommonModel::$del_normal])
            ->save($da);

        return $rs ? json_show(CommonModel::$error_token, '修改密码成功') : json_show(CommonModel::$error_param, '修改密码失败');

    }

    //通过微信端code绑定账户
//    public static function bindAccountByCode(): Json
//    {
//
//        $openId = WechatLogic::getOauthAccessToken();
//
//        $rs = AccountModel::where('id', self::$aid)
//            ->save(['wx_openId' => $openId, 'updaterid' => self::$aid, 'updater' => self::$aname, 'updatetime' => date('Y-m-d H:i:s')]);
//
//        return $rs ? json_show(CommonModel::$success, '绑定成功') : json_show(CommonModel::$error_param, '绑定失败');
//
//    }


}