package com.huiju.estateagents.center.taUser.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.sysUser.entity.SysToken;
import com.huiju.estateagents.center.sysUser.service.ISysTokenService;
import com.huiju.estateagents.center.taUser.entity.TaTagUser;
import com.huiju.estateagents.center.taUser.entity.TaTags;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.entity.TaUserRole;
import com.huiju.estateagents.center.taUser.service.*;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.common.MD5Utils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.TaRoleMapper;
import com.huiju.estateagents.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 用户表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-09-11
 */
@RestController
@RequestMapping("/api")
public class TaUserController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaUserController.class);

    @Autowired
    public ITaUserService iTaUserService;

    @Autowired
    public ITaOrgService iTaOrgService;
    
    @Autowired
    private ISysTokenService sysTokenService;

    @Autowired
    private ITaRoleService iTaRoleService;

    @Autowired
    private ITaUserAuthMenuService iTaUserAuthMenuService;

    @Autowired
    private ITaUserAuthButtonService iTaUserAuthButtonService;
    
    @Autowired
    private ITaTagUserService taTagUserService;
    
    @Autowired
    private ITaPersonBuildingService taPersonBuildingService;
    
    @Autowired
    private ITaUserRoleService taUserRoleService;

    @Autowired
    private TaRoleMapper taRoleMapper;

    @Autowired
    private ITaPersonService iTaPersonService;

    @Autowired
    private ITaMiniappService iTaMiniappService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/center/taUser",method= RequestMethod.GET)
    public ResponseBean taUserList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
									 @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                     @RequestParam(value = "miniAppName", required = false) String miniAppName, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();

        try {
            //使用分页插件
		    IPage pg = new Page<>(pageNum, pageSize);
            IPage<Map<String,Object>> result = iTaUserService.getPageList(pg, getChannelId(request), miniAppName);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/channel/taUser",method= RequestMethod.GET)
    public ResponseBean taUserChannelList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage pg = new Page<>(pageNum, pageSize);
            IPage<Map<String,Object>> result = iTaUserService.getPageList(pg, null, null);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taUser 实体对象
     * @return
     */
    @RequestMapping(value="/center/taUser",method= RequestMethod.POST)
    public ResponseBean taUserAdd(@RequestBody TaUser taUser, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer channelId = getChannelId(request);
        try {
            responseBean.addSuccess(iTaUserService.newUserAndOrg(taUser, channelId));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @PutMapping(value = "/{plat}/turn/taUser/{id}/{type}")
    public ResponseBean turnUser(@PathVariable String type, @PathVariable Integer id, @PathVariable("plat")String plat) {
        try {
            iTaUserService.turnUserOnOrNot(id, "on".equals(type), plat);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }

        return ResponseBean.success("ok");
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taUser/{id}", method= RequestMethod.DELETE)
    public ResponseBean taUserDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaUserService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taUser 实体对象
     * @return
     */
    @RequestMapping(value="/center/taUser/{id}",method= RequestMethod.PUT)
    public ResponseBean taUserUpdate(@PathVariable Integer id,
                                        @RequestBody TaUser taUser){
        ResponseBean responseBean = new ResponseBean();
        try {
            iTaUserService.updateInfoWithOrg(taUser);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    /**
     * 获取用户信息
     */
    @RequestMapping(value="/center/taUser/{id}",method= RequestMethod.GET)
    public ResponseBean taUserGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaUserService.getInfoWithOrg(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }

        return responseBean;
    }

    /**
     * 重置密码
     * @param plat
     * @param id
     * @return
     */
    @PutMapping(value = "/{plat}/password/taUser/{id}")
    public ResponseBean resetPassword(@PathVariable String plat, @PathVariable Integer id, HttpServletRequest request) {
        if (!"center".equals(plat) && !"admin".equals(plat)) {
            return ResponseBean.error("您没有权限进行此操作", ResponseBean.ERROR_AUTH_EXPIRED);
        }

        String newPass = plat.equals("center") ? "abc@123" : "123456";
        try {
            iTaUserService.resetPassword(id, newPass);
            return ResponseBean.success("新密码为: " + newPass);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }


    /**
     * 业务端  修改密码
     * @return/
     */
    @PutMapping(value = "/admin/update/password")
    public ResponseBean updatePassword( @RequestParam String originalPassword,
                                        @RequestParam String newPassword,
                                        HttpServletRequest request) {

        if (org.apache.commons.lang3.StringUtils.isBlank(newPassword) || newPassword.length() < 6) {
            return ResponseBean.error("新密不能小于6位", ResponseBean.ERROR_UNAVAILABLE);
        }

        Integer userId = getUserId(request);

        // 校验当前旧密码是否正确
        String password = MD5Utils.md5(MD5Utils.md5(originalPassword));
        TaUser taUser = iTaUserService.getById(userId);
        if (!password.equals(taUser.getLoginPassword())){
            return ResponseBean.error("旧密码错误,请重新输入", ResponseBean.ERROR_UNAVAILABLE);
        }

        try {
            iTaUserService.resetPassword(userId, newPassword);
            return ResponseBean.success("操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 获取当前用户信息
     * @param request
     * @return
     */
    @RequestMapping(value="/admin/taUser/current",method= RequestMethod.GET)
    public ResponseBean taUserGetCurrent(HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Map userMap = new HashMap();
        Map map = JWTUtils.getUserIdAndOrgId(request);
        try {
            TaUser taUser = iTaUserService.getById(map.get("userId").toString());
            List<TaRole> roles = iTaRoleService.getRolesByUser(taUser.getUserId());
            ResponseBean authMenu = iTaUserAuthMenuService.getMenuByUserId(null, null, taUser.getUserId().toString(),taUser.getOrgId());
            ResponseBean authButton = iTaUserAuthButtonService.getButtonByUserId(null, null, taUser.getUserId().toString(),taUser.getOrgId());
            QueryWrapper<TaMiniapp> taMiniappQueryWrapper = new QueryWrapper<>();
            taMiniappQueryWrapper.eq("org_id", getOrgId(request));
            TaMiniapp taMiniapp = iTaMiniappService.getOne(taMiniappQueryWrapper);
            //
            TaOrg taOrg = iTaOrgService.getById(taUser.getOrgId());

            taUser.setMenus((List<SysMenu>) authMenu.getData());
            taUser.setButtons((List<SysButtonInMenu>) authButton.getData());
            taUser.setRoles(roles);
            taUser.setLoginPassword("");
            taUser.setMiniAppName(taMiniapp.getName());
            taUser.setOrgName(taOrg.getName());
            taUser.setOrgThumb(taOrg.getThumb());
            taUser.setOrgLogo(taOrg.getLogo());
            taUser.setOrgDesc(taOrg.getOrgDesc());
            taUser.setBossDisplay(taOrg.getBossDisplay());

            //获取所有菜单
            List<SysMenu> allMenus = (List<SysMenu>) iTaUserAuthMenuService.getAllMenu(null, null,taUser.getOrgId(), roles).getData();
            List<SysButtonInMenu> allButtons = (List<SysButtonInMenu>) iTaUserAuthButtonService.getAllButton(null, null).getData();


            userMap.put("taUser", taUser);
            userMap.put("menuList", allMenus);
            userMap.put("buttonList", allButtons);
            responseBean.addSuccess(userMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 用户手机号登录
     * @param paramStr
     * @return
     */
    @PostMapping("/admin/taUser/signin")
    public ResponseBean signin(@RequestBody String paramStr) {
        JSONObject params = JSONObject.parseObject(paramStr);
        if (params == null) {
            return ResponseBean.error("非法参数", ResponseBean.ERROR_MISSING_PARAMS);
        }
    
        String userName = params.getString("loginName");
        String userPassword = params.getString("loginPassword");
    
        //验证用户名密码是否正确
        QueryWrapper<TaUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("login_name",userName);
        sysUserQueryWrapper.eq("login_password", MD5Utils.md5(userPassword));
        TaUser taUser = iTaUserService.getOne(sysUserQueryWrapper);
        if (taUser == null) {
            return ResponseBean.error("用户名或密码错误", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        QueryWrapper<TaUser> taUserQueryWrapper = new QueryWrapper<>();
        taUserQueryWrapper.eq("org_id", taUser.getOrgId());
        taUserQueryWrapper.eq("is_admin", 1);
        TaUser taUserAdmin = iTaUserService.getOne(taUserQueryWrapper);

        if (taUserAdmin.getExpDate().isBefore(LocalDateTime.now())){
            return ResponseBean.error("该账号已经过期，请联系管理员", ResponseBean.ERROR_UNAVAILABLE);
        }

        if (!taUser.getStatus().equals(CommConstant.STATUS_NORMAL) ) {
            return ResponseBean.error("该账号已经停用，请联系管理员", ResponseBean.ERROR_UNAVAILABLE);
        }


        List<TaRole> roles = iTaRoleService.getRolesByUser(taUser.getUserId());
        taUser.setRoles(roles);
        taUser.setLoginPassword("");
        Map map = new HashMap();
        map.put("userId",taUser.getUserId().toString());
        map.put("orgId",taUser.getOrgId().toString());
        String token = JWTUtils.newTokenByMap(map);

        // 先尝试删除这个Token
        // 因为偶尔出现了，Token插入失败，报的错就是主键重复
        sysTokenService.removeById(token);

        //保存token
        sysTokenService.saveToken(token);
    
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", taUser);

        return ResponseBean.success(result);
    }
    
    @PostMapping("/admin/taUser/signout")
    public ResponseBean signout(HttpServletRequest request) {
        String token = JWTUtils.getToken(request);
        QueryWrapper<SysToken> sysTokenQueryWrapper = new QueryWrapper<>();
        sysTokenQueryWrapper.eq("token",token);
        sysTokenService.remove(sysTokenQueryWrapper);
        return ResponseBean.success("成功退出");
    }
    
    
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taUser",method= RequestMethod.GET)
    public ResponseBean taUserList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                   @RequestParam(value ="userName",required = false) String userName,
                                   @RequestParam(value ="phone",required = false) String phone,
                                   @RequestParam(value ="status",required = false) Integer status,
                                   @RequestParam(value ="isConsultant",required = false) Integer isConsultant,
                                   @RequestParam(value ="miniStatus",required = false) Integer miniStatus,
                                   @RequestParam(value ="buildingId",required = false) String buildingId,
                                   HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage pg = new Page<>(pageNum, pageSize);
            TaUser taUser = new TaUser();
            taUser.setOrgId(getOrgId(request));
            taUser.setUserName(userName);
            taUser.setPhone(phone);
            taUser.setStatus(status);
            taUser.setBuildingId(buildingId);
            if(null != isConsultant && isConsultant == 1){
                taUser.setIsConsultant(true);
            }else if (null != isConsultant && isConsultant == 0){
                taUser.setIsConsultant(false);
            }
            taUser.setMiniStatus(miniStatus);

            IPage<TaUser> result = iTaUserService.seleUserList(pg,taUser,getTaPersonBuildingListByUserId(request));
            List<TaUser> taUserList = result.getRecords();
            taUserList.forEach(e -> {
                List<TaTags> taTagsList = iTaUserService.getTagsList(e);
                e.setTaTagsList(taTagsList);

//                Integer person = iTaPersonService.judgeBindStatusByCondition(e.getUserId(), getOrgId(request), e.getPhone());
//                e.setMiniStatus(0 == person ? 0 : 1);
            });
            result.setRecords(taUserList);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    
    /**
     * 获取用户信息
     */
    @RequestMapping(value="/admin/taUser/{id}",method= RequestMethod.GET)
    public ResponseBean adminUserGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaUser taUser = iTaUserService.getById(id);
            QueryWrapper<TaTagUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",id);
            List<TaTagUser> taTagUserList = taTagUserService.list(queryWrapper);
            List<Integer> tags = new ArrayList<>();
            taTagUserList.forEach(e -> {
                tags.add(e.getTagId());
            });
            taUser.setTaTags(tags);
            //获取角色信息
            QueryWrapper<TaUserRole> taUserRoleQueryWrapper = new QueryWrapper<>();
            taUserRoleQueryWrapper.eq("user_id",id);
            List<TaUserRole> taUserRoleList = taUserRoleService.list(taUserRoleQueryWrapper);
            List<Integer> ids = new ArrayList<>();
            taUserRoleList.forEach(e -> {
                ids.add(e.getRoleId());
            });
            taUser.setRoleIds(ids);
            taUser.setLoginPassword("");
            QueryWrapper<TaPersonBuilding> taPersonBuildingQueryWrapper = new QueryWrapper<>();
            taPersonBuildingQueryWrapper.eq("user_id",taUser.getUserId());
            List<TaPersonBuilding> taPersonBuildingList = taPersonBuildingService.list(taPersonBuildingQueryWrapper);
            //非置业顾问可以授权多个项目
            if (taPersonBuildingList.size() > 0){
                if (taUser.getIsConsultant()){
                    taUser.setBuildingId(taPersonBuildingList.get(0).getBuildingId());
                    QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
                    taPersonQueryWrapper.eq("user_id",id);
                    taPersonQueryWrapper.eq("org_id",taUser.getOrgId());
                    TaPerson taPerson = iTaPersonService.getOne(taPersonQueryWrapper);
                    if (null != taPerson){
                        taUser.setConsultantPersonId(taPerson.getPersonId());
                    }
                }else {
                    List<String> buildings = new ArrayList<>();
                    taPersonBuildingList.forEach(e -> {
                        buildings.add(e.getBuildingId());
                    });
                    taUser.setBuildingIds(buildings);
                }
            }
            responseBean.addSuccess(taUser);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        
        return responseBean;
    }
    
    /**
     * 保存对象
     * @param taUser 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taUser",method= RequestMethod.POST)
    public ResponseBean adminUserAdd(@RequestBody TaUser taUser,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            taUser.setOrgId(getOrgId(request));
            responseBean.addSuccess(iTaUserService.addAdminUser(taUser));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 修改对象
     * @param id  实体ID
     * @param taUser 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taUser/{id}",method= RequestMethod.PUT)
    public ResponseBean adminUserUpdate(@PathVariable Integer id,
                                     @RequestBody TaUser taUser,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            taUser.setUserId(id);
            taUser.setOrgId(getOrgId(request));
            responseBean.addSuccess(iTaUserService.updateAdminUser(taUser));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taUserUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    // 树形菜单
    @RequestMapping(value="/center/taUser/city/tree",method= RequestMethod.GET)
    public ResponseBean cityTree(){
        ResponseBean taUser = iTaUserService.cityTree();
        return taUser;
    }

    /**
     * 员工离职
     * @return
     */
    @RequestMapping(value = "/admin/user/departure/{userId}", method = RequestMethod.PUT)
    public ResponseBean departureUser(@PathVariable("userId") Integer userId,
                                      @RequestParam(value = "customerIdList", required = false) List<String> customerIdList,
                                      @RequestParam(value = "consultantUserId", required = false) Integer consultantUserId) {
        ResponseBean responseBean = new ResponseBean();
        responseBean = iTaUserService.departureUser(userId, customerIdList, consultantUserId);
        return responseBean;
    }
}
