package co.dc.aptiv.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import co.dc.commons.basedao.BaseDao;
import co.dc.aptiv.pojo.RolePojo;
import co.dc.aptiv.pojo.UserPojo;

/**
 * @describe: 用户
 * @author: liuxinglong
 * @version: 2018/4/17 15:21
 */
@Service("userService")
public class UserService extends BaseDao<UserPojo> {

    private static final Log log = LogFactory.getLog(UserService.class);

    @Resource
    private QueryRunner queryRunner;
    @Resource
    private RoleService roleService;

    @Override
    protected String getTableName() {
        return UserPojo.tableName;
    }


    public boolean checkDb() {
        log.info("检查数据库连接");
        try {
            queryRunner.query("select count(*) from " + getTableName(), new ScalarHandler());
            return true;
        } catch (Exception e) {
            log.error("检查数据库连接-异常:", e);
            return false;
        }
    }

    /**
     * 登陆操作-成功则返回且修改登录状态
     *
     * @param loginname
     * @param password
     * @return
     */
    public UserPojo checklogin(String loginname, String password) {
        log.info("登陆操作-成功则返回且修改登录状态-String loginname=" + loginname + ",String password=" + password);
        UserPojo userPojo = new UserPojo();
        try {
            userPojo = queryRunner.query("select * from " + getTableName() + " where loginname = ? and password = ? and delFlag = 0 limit 1", new BeanHandler<UserPojo>(UserPojo.class), loginname, password);
            if (userPojo != null) {
                RolePojo rolePojo = roleService.findById(userPojo.getRoleid());
                userPojo.setPowers(rolePojo.getPowers());
                userPojo.setRolename(rolePojo.getRolename());
            }
        } catch (SQLException e) {
            log.error("登陆操作-成功则返回且修改登录状态-异常:", e);
        }
        return userPojo;
    }

    /**
     * 退出操作-成功则返回且修改登录状态
     *
     * @param password
     * @return
     */
    public UserPojo loginout(String password) {
        log.info("退出操作-成功则返回且修改登录状态-String password=" + password);
        UserPojo userPojo = new UserPojo();
        try {
            userPojo = queryRunner.query("select * from " + getTableName() + " where loginstatus = 1 and password = ? limit 1", new BeanHandler<UserPojo>(UserPojo.class), password);
            if (userPojo != null) {
                //修改登陆状态
                userPojo.setLoginstatus("0");
                update(userPojo);
            }
        } catch (SQLException e) {
            log.error("退出操作-成功则返回且修改登录状态-异常:", e);
        }
        return userPojo;
    }

    /**
     * 切换登陆操作-成功则返回且修改登录状态
     *
     * @param preloginname
     * @param loginname
     * @param password
     * @return
     */
    public UserPojo changelogin(String preloginname, String loginname, String password) {
        UserPojo userPojo = new UserPojo();
        return userPojo;
    }

    /**
     * 获取权限内的所有用户的信息
     *
     * @param datatype 1获取当前登录用户--2获取当前用户权限之内能获取的所有用户
     * @return
     */
    public List<UserPojo> getuserinfo(UserPojo userPojo, int datatype) {
        log.info("获取权限内的所有用户的信息");
        List<UserPojo> userPojos = new ArrayList<UserPojo>();
        if (datatype == 2) {
            try {
                if (roleService.findById(userPojo.getRoleid()).getPowers().indexOf("管理用户") >= 0) {
                    userPojos = queryList("select * from " + getTableName() + " where delflag = ?", "0");
                    for (int i = 0; i < userPojos.size(); i++) {
                        userPojos.get(i).setPowers(roleService.findById(userPojos.get(i).getRoleid()).getPowers());
                        userPojos.get(i).setRolename(roleService.findById(userPojos.get(i).getRoleid()).getRolename());
                    }
                } else {
                    userPojo.setPowers(roleService.findById(userPojo.getRoleid()).getPowers());
                    userPojos.add(userPojo.setRolename(roleService.findById(userPojo.getRoleid()).getRolename()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                userPojo = queryRunner.query("select * from " + getTableName() + " where loginstatus = 1 limit 1", new BeanHandler<UserPojo>(UserPojo.class));
                if (userPojo != null) {
                    userPojo.setPowers(roleService.findById(userPojo.getRoleid()).getPowers());
                    userPojos.add(userPojo.setRolename(roleService.findById(userPojo.getRoleid()).getRolename()));
                }
            } catch (Exception e) {
                log.error("获取权限内的所有用户的信息-异常:", e);
            }
        }
        return userPojos;
    }

    /**
     * 修改权限
     *
     * @param id
     * @param roleid
     * @return
     */
    public int updaterole(UserPojo userPojo, long id, long roleid) {
        log.info("修改权限-long id=" + id + ", long roleid=" + roleid);
        int upid = 0;
        try {
            if (userPojo.getId() == id) {
                upid = -1;
            } else {
                upid = update("roleid", roleid, "id", id);
            }
        } catch (Exception e) {
            log.error("修改权限-异常:", e);
        }
        return upid;
    }

    /**
     * 修改密码
     *
     * @param id
     * @param prepass
     * @param nowpass
     * @return
     */
    public int updatepass(long id, String prepass, String nowpass) {
        log.info("修改密码-long id=" + id + ", String prepass=" + prepass + ", String nowpass=" + nowpass);
        int upid = 0;
        try {
            upid = queryRunner.update("update " + getTableName() + " set password = ? where id = ? and password = ?", nowpass, id, prepass);
        } catch (SQLException e) {
            log.error("修改密码-异常:", e);
        }
        return upid;
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    public int deluser(UserPojo userPojo, long id) {
        log.info("删除用户-long id=" + id);
        int upid = 0;
        try {
            if (userPojo.getId() == id) {
                upid = -1;
            } else {
                upid = update("delflag", "1", "id", id);
            }
        } catch (Exception e) {
            log.error("删除用户-异常:", e);
        }
        return upid;
    }

    /**
     * 检查用户名是否已经被使用
     *
     * @param loginname
     * @return
     */
    public boolean checkloginname(String loginname) {
        log.info("检查用户名是否已经被使用-" + loginname);
        try {
            UserPojo uu = findByParam("loginname", loginname);
            if (uu != null && uu.getId() > 0) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            log.error("检查用户名是否已经被使用-异常:", e);
            return true;
        }
    }

}
