package com.app.admin.framework.system.administrator.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.app.admin.framework.system.administrator.dao.SysAdministratorDao;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.framework.core.exception.ValidException;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.service.impl.CrudBaseServiceSupport;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.pwd.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统账号管理
 */
@Service
@Transactional
public class SysAdministratorServiceImpl extends CrudBaseServiceSupport<SysAdministratorDao, SysAdministrator> implements SysAdministratorService {

    public List<SysAdministrator> getPageList(SysAdministrator view, Paging paging) {
        LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministrator::getOrganizationId, view.getOrganizationId());
        wrapper.eq(SysAdministrator::getUserType, LoginUser.TYPE_EMP);
        if (view.getDeptId() != null) {
            wrapper.eq(SysAdministrator::getDeptId, view.getDeptId());
        }
        if (view.getState() != null) {
            wrapper.eq(SysAdministrator::getState, view.getState());
        }
        if (StringUtils.isNotBlank(view.getRealName())) {
            wrapper.like(SysAdministrator::getUsername, view.getRealName());
        }
        wrapper.orderByDesc(SysAdministrator::getCreateTime);
        return this.pageList(wrapper, paging);
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 登录密码,标准md5加密
     * @param usertype 用户类型,可为空(注册会员登录时建议不要为空)
     */
    public AjaxResult login(String username, String password, Integer usertype) {
        if (StringUtils.isBlank(username)) {// 用户名为空
            return AjaxResult.wrapError("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {// 密码为空
            return AjaxResult.wrapError("密码不能为空");
        }
        if (password.length() < 16) {
            password = SecureUtil.md5(password);
        }
        LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministrator::getUsername, username);
        wrapper.eq(SysAdministrator::getUserType, usertype);
        SysAdministrator account = this.getOne(wrapper);
        if (account == null) {// 用户名不存在
            return AjaxResult.wrapError("用户名不存在");
        }
        if (!PasswordUtil.equalsPwd(password, account.getPassword())) {//密码错误
            return AjaxResult.wrapError("密码错误");
        }
        if (StateEnum.DISABLE.equalValue(account.getState())) {// 禁用
            return AjaxResult.wrapError("用户已被禁用");
        }
        return AjaxResult.wrapData(account);
    }

    /**
     * 根据用户名加载用户信息
     *
     * @param username 用户名
     * @return
     */
    public SysAdministrator findByUsername(String username) {
        LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministrator::getUsername, username);
        return this.getOne(wrapper);
    }

    /**
     * 保存系统用户
     *
     * @param entity
     */
    public AjaxResult saveSysUser(SysAdministrator entity, LoginUser loginUser) {
        if (this.checkUsername(entity)) {
            return AjaxResult.wrapError("登录名已经存在");
        }
        entity.setUserType(LoginUser.TYPE_EMP);//普通管理员即员工
        if (entity.getOrganizationId() == null) {
            entity.setOrganizationId(LoginUser.ORGANIZATION_SUPER);
        }
        boolean count;
        if (entity.getOid() == null) {
            entity.setPassword(PasswordUtil.encrypt(LoginUser.DEFAULT_PWD));
            entity.setCreateUserId(loginUser.getId());
            entity.setCreateTime(DateUtil.date());
            count = this.save(entity);
        } else {
            count = this.updateById(entity);
        }
        return AjaxResult.wrap(count);
    }

    /**
     * 修改密码
     *
     * @param oid    用户ID
     * @param newPwd 新密码,MD5加密后
     */
    public AjaxResult updateUserPwd(Long oid, String newPwd) {
        AjaxResult result = AjaxResult.wrap(false);
        if (StringUtils.isBlank(newPwd) || "d41d8cd98f00b204e9800998ecf8427e".equals(newPwd)) {
            result.setMsg("密码不能为空");
        } else if (newPwd.length() < 16) {//密码格式不正确
            result.setMsg("密码格式不正确");
        } else {
            SysAdministrator entity = new SysAdministrator();
            entity.setOid(oid);
            entity.setPassword(PasswordUtil.encrypt(newPwd));
            this.updateById(entity);
            result.setCode(AjaxResult.SUCCESS);
        }
        return result;
    }

    /**
     * 修改用户头像
     *
     * @param oid        用户Id
     * @param headImgUrl 头像URL
     * @return true: 修改成功	 fasle: 修改失败
     */
    public boolean updateHeadImgUrl(Long oid, String headImgUrl) {
        SysAdministrator record = new SysAdministrator();
        record.setOid(oid);
        record.setHeadImgUrl(headImgUrl);
        return this.updateById(record);
    }

    /**
     * 修改状态
     *
     * @param oid       用户Id
     * @param stateEnum 状态
     * @return true: 修改成功	 fasle: 修改失败
     */
    public boolean updateState(Long oid, StateEnum stateEnum) {
        SysAdministrator record = new SysAdministrator();
        record.setOid(oid);
        record.setState(stateEnum.getValue());
        return this.updateById(record);
    }


    /**
     * 保存组织机构管理员
     *
     * @param administrator 管理员
     */
    public SysAdministrator saveOrgAdministrator(SysAdministrator administrator) {
        if (administrator.getOrganizationId() == null) {
            throw new ValidException("组织机构ID不能为空");
        }
        SysAdministrator orgAdministrator = this.getOrgAdministrator(administrator.getOrganizationId());
        if (orgAdministrator != null) {
            if (!orgAdministrator.getState().equals(administrator.getState())) {
                SysAdministrator record = new SysAdministrator();
                record.setOid(orgAdministrator.getOid());
                record.setState(administrator.getState());
                this.updateById(record);

                orgAdministrator.setState(administrator.getState());
            }
            return orgAdministrator;
        }
        boolean check = this.checkUsername(administrator);
        if (check) {//用户名已经存在
            throw new ValidException("管理员登录账号已经存在");
        }
        if (StringUtils.isBlank(administrator.getPassword())) {
            administrator.setPassword(SysAdministrator.DEFAULT_PWD);
        }
        administrator.setPassword(PasswordUtil.encrypt(administrator.getPassword()));
        administrator.setState(StateEnum.NORMAL.getValue());
        administrator.setUserType(LoginUser.TYPE_ADMIN);
        administrator.setCreateTime(DateUtil.date());
        this.save(administrator);

        return administrator;
    }

    /**
     * 获取组织机构管理员
     *
     * @param organizationId 组织机构Id
     */
    public SysAdministrator getOrgAdministrator(Long organizationId) {
        LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministrator::getOrganizationId, organizationId);
        wrapper.eq(SysAdministrator::getUserType, LoginUser.TYPE_ADMIN);
        return this.getOne(wrapper);
    }

    /**
     * 判断姓名是否存在
     *
     * @param administrator
     * @return true: 已存在  false: 不存在
     */
    public boolean checkRealName(SysAdministrator administrator) {
        LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministrator::getRealName, administrator.getRealName());
        if (administrator.getOid() != null) {
            wrapper.ne(SysAdministrator::getOid, administrator.getOid());
        }
        int count = this.count(wrapper);
        return count > 0;
    }

    /**
     * 判断用户名是否存在
     *
     * @param administrator
     * @return true: 已存在  false: 不存在
     */
    public boolean checkUsername(SysAdministrator administrator) {
        LambdaQueryWrapper<SysAdministrator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAdministrator::getUsername, administrator.getUsername());
        if (administrator.getOid() != null) {
            wrapper.ne(SysAdministrator::getOid, administrator.getOid());
        }
        int count = this.count(wrapper);
        return count > 0;
    }
}