<?php
/**
 * Created by PhpStorm.
 * User: chouchou
 * Date: 2019-6-9
 * Time: 21:55
 */

namespace app\admin\controller;

use app\admin\model\AdminModel;
use app\admin\model\StaffPropertyModel;
use app\admin\validate\ResetValidate;
use think\facade\Session;
use think\Request;

class Reset extends Base
{
    public function edit(){
        return $this->fetch('reset');
    }

    public function update(Request $request){

        $validate = new ResetValidate;
        if(!$validate->check($request->post())){
            return jsonErr($validate->getError());
        }

        $user  =  Session::get('user');

        //普通用户
        if(!$user['is_admin']){

            //查询就密码是否正确
            $map['passwd'] = decrypt($request->post('old_password'));
            $map['staff_id'] = $user['user_id'];

            $staff = StaffPropertyModel::get($map);

            //用户ID与密码不匹配
            if(!$staff){
                return jsonErr('当前密码错误');
            }


            $staff->passwd = decrypt($request->post('password'));
            if($staff->save()){
                return jsonSuc('重置成功');
            }
            return jsonErr('重置失败，请核对密码');
            //管理员
        } else {
            $map['password'] = decrypt($request->post('old_password'));
            $map['id'] = $user['user_id'];

            $admin = AdminModel::get($map);

            //用户ID与密码不匹配
            if(!$admin){
                return jsonErr('当前密码错误');
            }


            $admin->password = decrypt($request->post('password'));
            if($admin->save()){
                return jsonSuc('重置成功');
            }
            return jsonErr('重置失败，请核对密码');
        }

    }
}