package com.crm.manager.controller;

import com.crm.login.rely.backend.controller.BaseLoginController;
import com.crm.manager.service.UserInfoService;
import com.crm.manager.service.UserRoleService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.constant.RegexpConstants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.user.info.SalesInfoDropdownDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.login.InfoEntity;
import com.crm.rely.backend.model.dto.user.info.UserInfoDto;
import com.crm.rely.backend.model.dto.user.info.UserInfoSearchDto;
import com.crm.rely.backend.model.entity.user.info.*;
import com.crm.rely.backend.model.pojo.table.UserInfoTable;
import com.crm.rely.backend.service.SysCountryService;
import com.crm.rely.backend.util.GetIpAndMac;
import com.crm.rely.backend.util.MD5Util;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

import static java.util.regex.Pattern.matches;

/**
 * @program: crm-backend
 * @description:
 * @author: houn
 * @create: 2019-07-25 15:57
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseLoginController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private SysCountryService sysCountryService;

    /**
     * 登录信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public BaseResultDto login(@RequestBody @Validated UserLoginEntity entity, HttpServletRequest request) throws Exception {

        //密码处理为
        entity.setPassword(MD5Util.getMD5(entity.getPassword()));

        /**
         * 处理登录时间 登录ip 登录地区
         */
        entity.setIp(GetIpAndMac.getIp(request));
        String returnStr = sysCountryService.getAdderByIp(entity.getIp());

        entity.setAddress(returnStr);
        entity.setTime(new Date());

        UserInfoEntity userInfoEntity = userInfoService.login(entity);

        String accessToken = super.login(userInfoEntity);

        return BaseResultDto.success(Constants.LOGIN_SUCCESS, accessToken);
    }

    /**
     * 退出登录
     *
     * @param httpServletRequest
     * @throws Exception
     */
    @Override
    @PostMapping("/logout")
    public BaseResultDto logout(HttpServletRequest httpServletRequest) throws Exception {

        return super.logout(httpServletRequest);
    }

    /**
     * 获取登录信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/info")
    public BaseResultDto info(UserInfoEntity entity) throws Exception {

        UserInfoDto userInfoDto = new UserInfoDto();

        BeanUtils.copyProperties(entity, userInfoDto);

        Long roleId;
        if (PrefixEnum.PREFIX_SYSTEM.equals(entity.getPrefix())) {
            roleId = 0L;
        } else {
            roleId = entity.getRoleId();
        }
//        List<UserNodeDisplayDto> userNodeDisplayDtos = userRoleService.getUserNodeDisplay(roleId);
//        userInfoDto.setDisplay(userNodeDisplayDtos);

        return BaseResultDto.success(userInfoDto);
    }

    @PostMapping("/display/{roleId}")
    public String getUserNodeDisplay(@PathVariable("roleId") Long roleId) throws Exception {
        userRoleService.getUserNodeDisplay(roleId);
        return "success";
    }

    /**
     * 添加用户
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    public BaseResultDto add(@RequestBody @Validated UserInfoAddEntity entity) throws Exception {
        entity.setEmail(entity.getEmail().toLowerCase());
        //密码
        entity.setPassword(MD5Util.getMD5(entity.getPassword()));

        if (entity.getIpLimit() == null) {
            entity.setIpLimit(0);
        }
        //如果登录名不填 默认为邮箱
        if (Strings.isNullOrEmpty(entity.getUsername())) {
            entity.setUsername(entity.getEmail());
        }

        //如果不填是否禁用 默认为1 可以登录
        if (entity.getValid() == null) {
            entity.setValid(1);
        }

        userInfoService.add(entity);

        return BaseResultDto.success(Constants.ADD_SUCCESS);
    }

    @PostMapping("/add/sales")
    public BaseResultDto addSales(@RequestBody UserInfoAddEntity entity) throws Exception {
        if (Strings.isNullOrEmpty(entity.getEmail()) || Strings.isNullOrEmpty(entity.getPassword()) || Strings.isNullOrEmpty(entity.getName()) || Strings.isNullOrEmpty(entity.getUsername())
                || Strings.isNullOrEmpty(entity.getIbNo())) {
            return BaseResultDto.error(Constants.PARAMETER_ERROR);
        }
        entity.setEmail(entity.getEmail().toLowerCase());
        //密码
        entity.setPassword(MD5Util.getMD5(entity.getPassword()));
        entity.setPid(1L);
        entity.setValid(1);
        entity.setRoleId(1023L);

        if (entity.getIpLimit() == null) {
            entity.setIpLimit(0);
        }
        //如果登录名不填 默认为邮箱
        if (Strings.isNullOrEmpty(entity.getUsername())) {
            entity.setUsername(entity.getEmail());
        }

        //如果不填是否禁用 默认为1 可以登录
        if (entity.getValid() == null) {
            entity.setValid(1);
        }

        userInfoService.add(entity);

        return BaseResultDto.success(Constants.ADD_SUCCESS);
    }

    /**
     * 修改用户信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/update/sales")
    public BaseResultDto updateSales(@RequestBody UserInfoUpdateEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setEmail(entity.getEmail().toLowerCase());
        if (Strings.isNullOrEmpty(entity.getEmail()) || Strings.isNullOrEmpty(entity.getName()) || Strings.isNullOrEmpty(entity.getUsername())
                || Strings.isNullOrEmpty(entity.getIbNo())) {
            return BaseResultDto.error(Constants.PARAMETER_ERROR);
        }
        entity.setEmail(entity.getEmail().toLowerCase());
        entity.setPid(1L);
        entity.setValid(1);
        entity.setRoleId(1023L);
        if (entity.getIpLimit() == null) {
            entity.setIpLimit(0);
        }

        //验证是否为空
        if (!Strings.isNullOrEmpty(entity.getPassword())) {

            //验证格式
            if (!matches(RegexpConstants.REGEXP_PWD, entity.getPassword())) {
                return BaseResultDto.error(Constants.PASSWORD_FORMAT_ERROR);
            }

            entity.setPassword(MD5Util.getMD5(entity.getPassword()));
        }
        UserInfoTable userInfoTable = userInfoService.update(entity);
        //保存到redis
        infoEntity.setValid(userInfoTable.getValid() == null ? 0 : userInfoTable.getValid());
        BeanUtils.copyProperties(userInfoTable, infoEntity);
        saveLoginInfo(infoEntity);

        return BaseResultDto.success();
    }

    /**
     * 删除用户信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/delete")
    public BaseResultDto delete(@RequestBody @Validated UserInfoDeleteEntity entity) throws Exception {

        userInfoService.delete(entity);

        return BaseResultDto.success(Constants.DELETE_SUCCESS);
    }

    /**
     * 修改用户信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/update")
    public BaseResultDto update(@RequestBody @Validated UserInfoUpdateEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setEmail(entity.getEmail().toLowerCase());

        if (entity.getIpLimit() == null) {
            entity.setIpLimit(0);
        }
        //验证是否为空
        if (!Strings.isNullOrEmpty(entity.getPassword())) {

            //验证格式
            if (!matches(RegexpConstants.REGEXP_PWD, entity.getPassword())) {
                return BaseResultDto.error(Constants.PASSWORD_FORMAT_ERROR);
            }

            entity.setPassword(MD5Util.getMD5(entity.getPassword()));
        }
        UserInfoTable userInfoTable = userInfoService.update(entity);
        //保存到redis
        infoEntity.setValid(userInfoTable.getValid() == null ? 0 : userInfoTable.getValid());
        BeanUtils.copyProperties(userInfoTable, infoEntity);
        saveLoginInfo(infoEntity);

        return BaseResultDto.success();
    }

    /**
     * 查询用户 page
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/page")
    public BaseResultDto searchPage(@RequestBody @Validated UserInfoSearchEntity entity) throws Exception {

        BaseResultWithPagerDto resultWithPagerDto = userInfoService.searchPage(entity);

        return resultWithPagerDto;
    }

    /**
     * 单个查询
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/single")
    public BaseResultDto searchSingle(@RequestBody @Validated SingleLongEntity entity) throws Exception {

        UserInfoSearchDto userInfoSearchDto = userInfoService.searchSingle(entity.getId());

        return BaseResultDto.success(Constants.SEARCH_SUCCESS, userInfoSearchDto);
    }


    /**
     * 未登录修改密码发送邮件
     *
     * @param entity
     * @param req
     * @return
     */
    @PostMapping("/update/password/send/email")
    public BaseResultDto updatePasswordSendEmail(@RequestBody @Validated UserUpdatePasswordSendEmailEntity entity,
                                                 HttpServletRequest req) throws Exception {


        entity.setIp(GetIpAndMac.getIp(req));
        entity.setTime(new Date());
        userInfoService.updatePasswordSendEmail(entity);

        return BaseResultDto.success(Constants.SEND_SUCCESS);
    }

    /**
     * 未登录根据邮件修改密码
     *
     * @param entity
     * @param req
     * @return
     */
    @PostMapping("/update/email/password")
    public BaseResultDto updatePassword(@RequestBody @Validated UserUpdateEmailPasswordEntity entity,
                                        HttpServletRequest req) throws Exception {

        entity.setModifyIp(GetIpAndMac.getIp(req));
        entity.setModifyTime(new Date());
        entity.setPassword(MD5Util.getMD5(entity.getPassword()));

        userInfoService.updatePassword(entity);

        return BaseResultDto.success(Constants.SUCCESS);
    }

    @PostMapping("/update/login/password")
    public BaseResultDto updatePassword(@RequestBody @Validated UserUpdateLoginPasswordEntity entity,
                                        HttpServletRequest req, InfoEntity infoEntity) throws Exception {

        entity.setId(infoEntity.getId());
        if (entity.getNewPassword().equals(entity.getOldPassword())) {
            return BaseResultDto.error(Constants.PASSWORD_NEW_AND_OLD_IDENTICAL_ERROR);
        }

        entity.setModifyIp(GetIpAndMac.getIp(req));
        entity.setModifyTime(new Date());
        entity.setModifyUser(infoEntity.getId());
        entity.setNewPassword(MD5Util.getMD5(entity.getNewPassword()));
        entity.setOldPassword(MD5Util.getMD5(entity.getOldPassword()));

        userInfoService.updatePassword(entity);
        return BaseResultDto.success(Constants.UPDATE_SUCCESS);
    }

    @PostMapping("/sales")
    public BaseResultDto<List<SalesInfoDropdownDto>> salesInfoDropdown() throws Exception {
        return userInfoService.getSalesInfoDropdown();
    }

    @PostMapping("/agent")
    public BaseResultDto<List<SalesInfoDropdownDto>> agentDropdown() throws Exception {
        return userInfoService.getAgentDropdown();
    }
}
