<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\workerapi\logic;


use app\common\enum\LoginEnum;
use app\common\enum\notice\NoticeEnum;
use app\common\model\sale\Sale;
use app\common\logic\BaseLogic;
use app\common\service\sms\SmsDriver;
use think\facade\Config;
use think\facade\Db;


/**
 * Sale逻辑
 * Class SaleLogic
 * @package app\workerapi\logic
 */
class SaleLogic extends BaseLogic
{


    public static function login($params)
    {
        try {
            // 账号/手机号 密码登录
            $where = ['mobile' => $params['mobile']];
            $user = Sale::where($where)->findOrEmpty();
            if ($user->isEmpty()) {
                throw new \Exception('无此用户');
            }

            // 账号密码登录
            if (LoginEnum::ACCOUNT_PASSWORD == $params['scene']) {
                if (!isset($params['password'])) {
                    throw new \Exception('请输入密码');
                }
                $passwordSalt = Config::get('project.unique_identification');
                if ($user['password'] !== create_password($params['password'], $passwordSalt)) {
                    throw new \Exception('密码错误');
                }
            }

            // 手机验证码登录
            if (LoginEnum::MOBILE_CAPTCHA == $params['scene']) {
                if (!isset($params['code'])) {
                    throw new \Exception('请输入手机验证码');
                }
                $smsDriver = new SmsDriver();
                $result = $smsDriver->verify($params['mobile'], $params['code'], NoticeEnum::LOGIN_CAPTCHA);
                if (!$result) {
                    throw new \Exception('验证码错误');
                }
            }

            //获取token
            $token = create_token($params['mobile']);
            $user->token = $token;
            $user->save();

            return [
                'id' => $user['id'],
                'mobile' => $user['mobile'],
                'sale_token' => $token,
            ];
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function getSaleIdByToken($sale_token)
    {
        $user = Sale::where('token',$sale_token)->findOrEmpty();
        if ($user->isEmpty()) {
            return -1;
        }
        return $user['id'];
    }


}