package com.ycwl.basic.service.pc.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.exception.RoleStatusException;
import com.ycwl.basic.mapper.AdminUserMapper;
import com.ycwl.basic.mapper.RoleMapper;
import com.ycwl.basic.model.jwt.JwtInfo;
import com.ycwl.basic.model.pc.adminUser.entity.LoginEntity;
import com.ycwl.basic.model.pc.adminUser.req.*;
import com.ycwl.basic.model.pc.adminUser.resp.AdminUserListRespVO;
import com.ycwl.basic.model.pc.adminUser.resp.LoginRespVO;
import com.ycwl.basic.model.pc.menu.MenuNode;
import com.ycwl.basic.service.pc.AdminUserService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import com.ycwl.basic.utils.SnowFlakeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.ycwl.basic.constant.PermissionConstant.ROLE_STATUS;


@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    AdminUserMapper adminUserMapper;


    @Autowired
    RoleMapper roleMapper;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public ApiResponse list(AdminUserListReqVO adminUserListReqVO) {
        PageHelper.startPage(adminUserListReqVO.getPageNum(), adminUserListReqVO.getPageSize());
        List<AdminUserListRespVO> list = adminUserMapper.list(adminUserListReqVO);
        PageInfo<AdminUserListRespVO> pageInfo = new PageInfo(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse addOrUpdate(AddOrUpdateAdminUserReqVO addOrUpdateAdminUserReqVO) {
        addOrUpdateAdminUserReqVO.setPassword(DigestUtil.md5Hex(addOrUpdateAdminUserReqVO.getPassword()));
        String id = addOrUpdateAdminUserReqVO.getId();
        if (StringUtils.isBlank(id)) {
            addOrUpdateAdminUserReqVO.setId(SnowFlakeUtil.getId());
//            String password = addOrUpdateAdminUserReqVO.getPassword();
//            addOrUpdateAdminUserReqVO.setPassword(password);
            int add = adminUserMapper.add(addOrUpdateAdminUserReqVO);
            if (add > 0) {
                return ApiResponse.success(null);
            }
        } else {
            int update = adminUserMapper.update(addOrUpdateAdminUserReqVO);
            if (update > 0) {
                return ApiResponse.success(null);
            }
        }
        return ApiResponse.fail("失败");
    }

    @Override
    public ApiResponse delete(String id) {
        if (adminUserMapper.delete(id) > 0) {
            return ApiResponse.success(null);
        }
        return ApiResponse.fail("失败");
    }

    @Override
    public ApiResponse resetPassword(ResetPasswordReqVO resetPasswordReqVO) {
        resetPasswordReqVO.setPassword(DigestUtil.md5Hex(resetPasswordReqVO.getPassword()));
        if (adminUserMapper.resetPassword(resetPasswordReqVO) > 0) {
            return ApiResponse.success(null);
        }
        return ApiResponse.fail("失败");
    }



    @Override
    public ApiResponse login(LoginReqVO loginReqVO) throws Exception {
        String account = loginReqVO.getAccount();
        String password = loginReqVO.getPassword();
        LoginEntity login = adminUserMapper.login(account);
        if (login == null) {
            return ApiResponse.fail("账号不存在或密码错误");
        }
        if (!login.getPassword().equals(DigestUtil.md5Hex(password))) {
            return ApiResponse.fail("账号不存在或密码错误");
        }
        String roleId = login.getRoleId();

        Object roleObject = redisTemplate.opsForValue().get(ROLE_STATUS + roleId);

        if (roleObject != null) {
            if (roleObject.toString().equals("0")) {
                throw new RoleStatusException("该角色下的账号已被封禁，请联系管理员");
            }
        }
        List<MenuNode> menuById = roleMapper.getMenuById(roleId);
        List<MenuNode> MenuList = new ArrayList<>();
        for (MenuNode item : menuById) {
            if ("-1".equals(item.getParentId())) {
                MenuList.add(item);
            }
            for (MenuNode item2 : menuById) {
                if (item2.getParentId().equals(item.getId())) {
                    if (item.getChildrenList() == null) {
                        item.setChildrenList(new ArrayList<>());
                    }
                    item.getChildrenList().add(item2);
                }
            }
        }
        LoginRespVO loginRespVO = new LoginRespVO();
        String token = jwtTokenUtil.generateToken(new JwtInfo(login.getStaffName(), login.getStaffId(), roleId, login.getAccount(), login.getAccount(), null,null));
        loginRespVO.setToken(token);
        loginRespVO.setName(login.getStaffName());
        loginRespVO.setTypeName(login.getTypeName());
        loginRespVO.setMenuNodeList(MenuList);
        return ApiResponse.success(loginRespVO);
    }

    @Override
    public ApiResponse updatePassword(UpdatePasswordReqVO updatePasswordReqVO) {
        String userId = BaseContextHandler.getUserId();
        updatePasswordReqVO.setId(userId);
        String passwordByAccount = adminUserMapper.getPasswordByAccount(updatePasswordReqVO.getId());
        String pwd = DigestUtil.md5Hex(updatePasswordReqVO.getPwd());
        if (!passwordByAccount.equals(pwd)) {
            return ApiResponse.fail("密码错误！修改失败");
        }
        String newPwd = DigestUtil.md5Hex(updatePasswordReqVO.getNewPwd());
        updatePasswordReqVO.setNewPwd(newPwd);
        if (adminUserMapper.updatePassword(updatePasswordReqVO) > 0) {
            return ApiResponse.success(null);
        }
        return ApiResponse.fail("失败");
    }
}
