package com.huiju.estateagents.center.sysUser.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.entity.SysUser;
import com.huiju.estateagents.center.sysUser.service.ISysTokenService;
import com.huiju.estateagents.center.sysUser.service.ISysUserService;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.service.ITaUserService;
import com.huiju.estateagents.channel.sysChannel.entity.TaChannelProxy;
import com.huiju.estateagents.channel.sysChannel.service.ITaChannelProxyService;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.common.MD5Utils;
import com.huiju.estateagents.common.StringUtils;
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.HashMap;
import java.util.Map;

/**
 * <p>
    * 系统用户 系统中心账户 前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-09-11
 */
@RestController
@RequestMapping("/api")
public class SysUserController extends BaseController {

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

    @Autowired
    public ISysUserService iSysUserService;
    
    @Autowired
    private ISysTokenService sysTokenService;

    @Autowired
    private ITaUserService iTaUserService;

    @Autowired
    private ITaChannelProxyService iTaChannelProxyService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/sysUser",method= RequestMethod.GET)
    public ResponseBean sysUserList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
									 @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<SysUser> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<SysUser> result = iSysUserService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysUserList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param sysUser 实体对象
     * @return
     */
    @RequestMapping(value="/sysUser",method= RequestMethod.POST)
    public ResponseBean sysUserAdd(@RequestBody SysUser sysUser){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iSysUserService.save(sysUser)){
                responseBean.addSuccess(sysUser);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysUserAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 修改对象
     * @param sysUser 实体对象
     * @return
     */
    @RequestMapping(value="/center/sysUser",method= RequestMethod.PUT)
    public ResponseBean sysUserUpdate(@RequestBody SysUser sysUser,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            String userName = JWTUtils.getSubject(request);
            sysUser.setPassword(MD5Utils.md5(sysUser.getPassword()));
            sysUser.setUserName(userName);
            if (iSysUserService.updateById(sysUser)){
                responseBean.addSuccess(sysUser);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysUserUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/sysUser/{id}",method= RequestMethod.GET)
    public ResponseBean sysUserGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iSysUserService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysUserDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/center/current",method=RequestMethod.GET)
    public ResponseBean currentUser(HttpServletRequest request){
        Map map = JWTUtils.getUserIdAndOrgId(request);
        QueryWrapper<TaChannelProxy> taChannelProxyQueryWrapper = new QueryWrapper<>();
        taChannelProxyQueryWrapper.eq("user_name", map.get("userName")).or().eq("channel_tel", map.get("userName"));
        TaChannelProxy taChannelProxy = iTaChannelProxyService.getOne(taChannelProxyQueryWrapper);
        if (StringUtils.isEmpty(taChannelProxy.getUserName())){
            taChannelProxy.setUserName(map.get("userName").toString());
        }
        return ResponseBean.success(taChannelProxy);
    }
    
    @PostMapping("/center/signin")
    public ResponseBean signin(@RequestBody String paramStr) {
        JSONObject params = JSONObject.parseObject(paramStr);
        if (params == null) {
            return ResponseBean.error("非法参数", ResponseBean.ERROR_MISSING_PARAMS);
        }

        QueryWrapper<TaChannelProxy> taChannelProxyQueryWrapper = new QueryWrapper<>();
        String userName = params.getString("userName");
        if (StringUtils.isEmpty(userName)){
            return ResponseBean.error("用户名不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        taChannelProxyQueryWrapper.eq("user_name", userName).or().eq("channel_tel", userName);

        //验证用户名密码是否正确
        TaChannelProxy taChannelProxy = iTaChannelProxyService.getOne(taChannelProxyQueryWrapper);
        String defaultPsw = MD5Utils.md5(params.getString("password"));
        if (taChannelProxy == null || !defaultPsw.equals(taChannelProxy.getPassword())) {
            return ResponseBean.error("用户名或密码错误", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        //校验是否过期且是否停用
        if (LocalDateTime.now().isAfter(taChannelProxy.getExpireDate()) || taChannelProxy.getStatus() == 0){
            return ResponseBean.error("当前后台服务已到期，请联系管理员", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Map map = new HashMap();
        map.put("userName", StringUtils.isEmpty(taChannelProxy.getUserName()) ? taChannelProxy.getChannelTel() : taChannelProxy.getUserName());
        map.put("channelId",taChannelProxy.getChannelId().toString());
        String token = JWTUtils.newTokenByMap(map);

        //保存token
        sysTokenService.saveToken(token);
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", taChannelProxy);
        
        return ResponseBean.success(result);
    }

    @PostMapping("/center/changePassword")
    public ResponseBean changePassword(@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 channelId = getChannelId(request);

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

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

    @PostMapping("/center/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("成功退出");
    }

    @RequestMapping(value="/center/logo",method= RequestMethod.GET)
    public ResponseBean getLogoImg(HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer channelId = getChannelId(request);
        TaChannelProxy taChannelProxy = iTaChannelProxyService.getById(channelId);
        responseBean.addSuccess(taChannelProxy);
        return responseBean;
    }

}
