package com.sptg.permissions.biz.controller;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.TreeUtil;
import com.sptg.permissions.api.dto.AccountDto;
import com.sptg.permissions.api.dto.LoginDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Menu;
import com.sptg.permissions.api.entity.Role;
import com.sptg.permissions.api.enums.PermissionsEnum;
import com.sptg.permissions.api.feigns.AccountAuthenticationFeign;
import com.sptg.permissions.biz.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * title: AccountAuthenticationController
 * package: com.sptg.permissions.biz.controller
 * description: 账号认证-控制器
 *
 *                  
 *                 
 */
@RestController
@RequiredArgsConstructor
public class AccountAuthenticationController implements AccountAuthenticationFeign {

    private final AccountServiceInterface accountServiceInterface;
    private final MenuServiceInterface menuServiceInterface;
    private final AccountRoleServiceInterface accountRoleServiceInterface;
    private final RoleServiceInterface roleServiceInterface;


    @Override
    @PostMapping(value = "/account/authLogin")
    public Account authLogin(@RequestBody LoginDto loginDto) {
        Account account = this.accountServiceInterface.selectById(loginDto.getId());
        if (null != account){
            //  校验密码
            if (account.getLoginPwd().equals(loginDto.getLoginPwd())){
                //  设置账号的权限信息
                this.setupAccountAuthority(account);
            }else {
                account = null;
            }
        }
        return account;
    }

    @Override
    @PostMapping(value = "/account/login")
    public ResultBean<Account> login(@RequestBody LoginDto loginDto) {
        Account account = this.accountServiceInterface.selectByLoginName(loginDto.getLoginName());
        if (null != account){
            //  校验账号是否可用
            if (OperationConstant.TWO == account.getIsEnable()){
                return new ResultBean<>(PermissionsEnum.USER_NOT_ENABLE);
            }
            //  校验密码
            String md5Pwd = this.accountServiceInterface.passwordEncrypt(loginDto.getLoginPwd());
            if (md5Pwd.equals(account.getLoginPwd())){
                //  设置账号的权限信息
                this.setupAccountAuthority(account);
                return new ResultBean<>(ResultEnum.SUCCESS,account);
            }
        }
        //  用户名或密码错误
        return new ResultBean<>(PermissionsEnum.AUTHENTICATION_ERROR);
    }

    @Override
    @PostMapping(value = "/account/oauth/login")
    public ResultBean<Account> oauthLogin(@RequestBody LoginDto loginDto) {
        Account account = this.accountServiceInterface.selectByLoginName(loginDto.getLoginName());
        if (null != account){
            //  校验账号是否可用
            if (OperationConstant.TWO == account.getIsEnable()){
                return new ResultBean<>(PermissionsEnum.USER_NOT_ENABLE);
            }
            this.setupAccountAuthority(account);
            return new ResultBean<>(ResultEnum.SUCCESS,account);
        }
        //  用户名或密码错误
        return new ResultBean<>(PermissionsEnum.AUTHENTICATION_OAUTH_ERROR);
    }

    @Override
    @GetMapping(value = "/account/reload/{id}")
    public Account reload(@PathVariable(value = "id")Serializable id) {
        //  获取账号信息
        Account account = this.accountServiceInterface.selectById(id);
        //  校验账号是否可用
        if (OperationConstant.TWO == account.getIsEnable()){
            return null;
        }
        //  设置账号的权限信息
        this.setupAccountAuthority(account);
        return account;
    }

    @Override
    @PostMapping(value = "/account/getByOpenid")
    public ResultBean<Account> getByOpenid(@RequestBody String openid) {
       ResultBean<Account> resultBean = this.accountServiceInterface.getByOpenid(openid);
       Account account = resultBean.getData();
       //开启了小程序端登录权限
       if(account!=null && account.getIsWeChatLogin()==1){
           //  设置账号的权限信息
           this.setupAccountAuthority(account);
       }
       return resultBean;
    }

    @Override
    @PostMapping(value = "/account/bindOpenid")
    public ResultBean<Boolean> bindOpenid(@RequestBody AccountDto dto) {
        return this.accountServiceInterface.bindOpenid(dto);
    }

    /**
     * 功能描述: 设置账号的权限信息
     * @param account 账号信息
     *                  
     *                       
     */
    private void setupAccountAuthority(Account account){
        //  获取用户的角色列表
        List<Long> roleIdList = this.accountRoleServiceInterface.selectRoleIdListByAccountId(account.getId());
        //  过滤不可用的角色
        for (int i =0; i < roleIdList.size(); i++){
            Role role = this.roleServiceInterface.selectById(roleIdList.get(i));
            if (role.getIsEnable().equals(OperationConstant.TWO)){
                roleIdList.remove(i);
                --i;
            }
        }
        //  获取用户可操作的菜单列表
        List<Menu> menuList = this.menuServiceInterface.selectListByRoleIdList(roleIdList);
        //  初始化用户可操作的权限列表
        List<String> tokenList = new ArrayList<>(menuList.size());
        menuList.forEach((menu -> {
            if (!StringUtils.isEmpty(menu.getToken())) {
                tokenList.add(menu.getToken());
            }
        }));
        account.setTokenList(tokenList);
        //  以树形的结构将菜单列表进行排序
        account.setMenuList(TreeUtil.tree(menuList));
    }

}
