package ${domain}.action.ajax.wsys;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import ${domain}.frame.auth.LocalData;
import ${domain}.frame.auth.Token;
import ${domain}.frame.base.BaseResponse;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.excel.WExcel;
import ${domain}.frame.excel.exception.TemplateNotMatchException;
import ${domain}.frame.utils.CookieUtil;
import ${domain}.frame.utils.LogUtil;
import ${domain}.frame.utils.MD5Util;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.RequestUtil;
import ${domain}.frame.utils.ResponseUtil;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsys.ent.User;
import ${domain}.module.wsys.mgr.TokensManager;
import ${domain}.module.wsys.mgr.UserManager;
import ${domain}.module.wsys.req.TokensCreateRequest;
import ${domain}.module.wsys.req.TokensLogoutRequest;
import ${domain}.module.wsys.req.UserChangePwdRequest;
import ${domain}.module.wsys.req.UserCreateRequest;
import ${domain}.module.wsys.req.UserDeleteRequest;
import ${domain}.module.wsys.req.UserFindRequest;
import ${domain}.module.wsys.req.UserLoginRequest;
import ${domain}.module.wsys.req.UserLogoutRequest;
import ${domain}.module.wsys.req.UserUpdateRequest;
import ${domain}.module.wsys.rsp.TokensCreateResponse;
import ${domain}.module.wsys.rsp.TokensLogoutResponse;
import ${domain}.module.wsys.rsp.UserChangePwdResponse;
import ${domain}.module.wsys.rsp.UserCreateResponse;
import ${domain}.module.wsys.rsp.UserDeleteResponse;
import ${domain}.module.wsys.rsp.UserFindResponse;
import ${domain}.module.wsys.rsp.UserLoginResponse;
import ${domain}.module.wsys.rsp.UserLogoutResponse;
import ${domain}.module.wsys.rsp.UserUpdateResponse;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class UserAjax {

    @Value("${r'${web.url.auth.admin}'}")
    private String admin;
    @Value("${r'${web.url.auth.pwd}'}")
    private String pwd;
    @Autowired
    private TokensManager tokensManager;
    @Autowired
    private UserManager userManager;

    public UserCreateResponse create(UserCreateRequest request) {
        return userManager.create(request, LocalData.getToken());
    }

    public UserDeleteResponse delete(UserDeleteRequest request) {
        return userManager.delete(request, LocalData.getToken());
    }

    public UserUpdateResponse update(UserUpdateRequest request) {
        return userManager.update(request, LocalData.getToken());
    }

    public UserChangePwdResponse changePwd(UserChangePwdRequest request) {
        if (admin.equals(LocalData.getToken().getUserName())) {
            UserChangePwdResponse response = new UserChangePwdResponse();
            response.addError(ErrorType.BUSINESS_ERROR, "超级管理员无法通过网页变更登录密码!");
            return response;
        }
        return userManager.changePwd(request, LocalData.getToken());
    }

    public UserFindResponse find(UserFindRequest request) {
        return userManager.find(request, LocalData.getToken());
    }

    public UserLoginResponse login(UserLoginRequest request, Token token, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        UserLoginResponse response = new UserLoginResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getUsername().equals(admin)) {//超级管理员登录
            String generatePwd = MD5Util.generatePwd(request.getPassword());
            if (!generatePwd.equals(pwd)) {
                response.addError(ErrorType.BUSINESS_ERROR, "用户名或密码错误!");
            } else {
                Date current = new Date();
                Calendar instance = Calendar.getInstance();
                instance.setTime(current);
                instance.add(Calendar.HOUR_OF_DAY, 3);//默认一个小时内有效

                TokensCreateRequest tokensCreateRequest = new TokensCreateRequest();
                tokensCreateRequest.setToken(UUID.randomUUID().toString());
                tokensCreateRequest.setUserId(0L);
                tokensCreateRequest.setUserName(admin);
                tokensCreateRequest.setLoginTime(current);
                tokensCreateRequest.setValidTime(instance.getTime());
                tokensCreateRequest.setValid(true);
                tokensCreateRequest.setDeptId(null);
                tokensCreateRequest.setDeptCode(null);
                tokensCreateRequest.setDeptName(null);
                tokensCreateRequest.setTerminalType("WEB");
                tokensCreateRequest.setTerminalIp(RequestUtil.getIp(httpServletRequest));
                tokensCreateRequest.setTerminalInfo(RequestUtil.getUserAgent(httpServletRequest));
                TokensCreateResponse tokensCreateResponse = tokensManager.create(tokensCreateRequest, LocalData.getSysToken());

                if (tokensCreateResponse.hasError()) {
                    response.addErrors(tokensCreateResponse.getErrors());
                    return response;
                }
                Cookie cookie = CookieUtil.newCookie("token", tokensCreateRequest.getToken());
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                response.setToken(tokensCreateRequest.getToken());
            }
        } else {//管理员登录
            UserFindRequest userFindRequest = new UserFindRequest();
            userFindRequest.setUserName(request.getUsername());
            UserFindResponse userFindResponse = userManager.find(userFindRequest, LocalData.getSysToken());

            if (userFindResponse.hasError()) {
                response.addErrors(userFindResponse.getErrors());
                return response;
            } else if (userFindResponse.getResult().size() == 0) {
                response.addError(ErrorType.BUSINESS_ERROR, "用户名或密码错误!");
                return response;
            } else if (userFindResponse.getResult().size() > 1) {
                response.addError(ErrorType.BUSINESS_ERROR, "用户信息异常!");
                return response;
            }

            User user = userFindResponse.getResult().get(0);

            String generatePwd = MD5Util.generatePwd(request.getPassword());
            if (!generatePwd.equals(user.getUserPwd())) {
                response.addError(ErrorType.BUSINESS_ERROR, "用户名或密码错误!");
                return response;
            }

            Date current = new Date();
            Calendar instance = Calendar.getInstance();
            instance.setTime(current);
            instance.add(Calendar.HOUR_OF_DAY, 3);//默认一个小时内有效

            TokensCreateRequest tokensCreateRequest = new TokensCreateRequest();
            tokensCreateRequest.setToken(UUID.randomUUID().toString());
            tokensCreateRequest.setUserId(user.getId());
            tokensCreateRequest.setUserName(user.getUserName());
            tokensCreateRequest.setLoginTime(current);
            tokensCreateRequest.setValidTime(instance.getTime());
            tokensCreateRequest.setValid(true);
            tokensCreateRequest.setDeptId(user.getDeptId());
            tokensCreateRequest.setDeptCode(user.getDeptCode());
            tokensCreateRequest.setDeptName(user.getDeptName());
            tokensCreateRequest.setTerminalType("WEB");
            tokensCreateRequest.setTerminalIp(RequestUtil.getIp(httpServletRequest));
            tokensCreateRequest.setTerminalInfo(RequestUtil.getUserAgent(httpServletRequest));
            TokensCreateResponse tokensCreateResponse = tokensManager.create(tokensCreateRequest, LocalData.getSysToken());

            if (tokensCreateResponse.hasError()) {
                response.addErrors(tokensCreateResponse.getErrors());
                return response;
            }
            Cookie cookie = CookieUtil.newCookie("token", tokensCreateRequest.getToken());
            httpServletResponse.addCookie(cookie);
            response.setToken(tokensCreateRequest.getToken());
        }

        return response;
    }

    public UserLogoutResponse logout(UserLogoutRequest request) {
        UserLogoutResponse response = new UserLogoutResponse();

        Token token = LocalData.getToken();
        if (token != null) {
            TokensLogoutRequest tokensLogoutRequest = new TokensLogoutRequest();
            tokensLogoutRequest.setToken(token.getToken());
            TokensLogoutResponse tokensLogoutResponse = tokensManager.logout(tokensLogoutRequest, LocalData.getSysToken());
            if (tokensLogoutResponse.hasError()) {
                response.addErrors(tokensLogoutResponse.getErrors());
                return response;
            }
        }
        CookieUtil.clearCookie("token");
        return response;
    }

    public Object template() {
        return ResponseUtil.apply(new WExcel<>(User.class));
    }

    public Object exports(UserFindRequest request) {
        UserFindResponse response = userManager.find(request, LocalData.getToken());
        if (response.hasError()) {
            return response;
        } else if (response.getTotalCount() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "导出数据为空");
            return response;
        }
        return ResponseUtil.apply(new WExcel<>(User.class).addDatas(response.getResult()));
    }

    public Object imports(MultipartFile file) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            WExcel sheet = new WExcel<>(User.class).read(file.getBytes(), new WExcel.Processor<User>() {
                @Override
                public List<String> exec(User o, int index) {
                    UserCreateRequest request = MapperUtil.map(o, UserCreateRequest.class);
                    return ValidationUtil.validate(request);
                }
            });

            if (sheet.hasError()) {
                return ResponseUtil.apply(sheet.getBytes(), sheet.getName() + "-检查.xlsx");
            } else {
                return baseResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.dumpException(e);
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件出错");
        } catch (TemplateNotMatchException e) {
            baseResponse.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
        }
        return baseResponse;
    }
}
