package cn.com.ty.lift.ud.userInfo.controller;

import java.math.BigDecimal;
import java.util.List;

import cn.com.ty.lift.ud.common.DelReq;
import cn.com.ty.lift.ud.utils.QrCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.com.ty.lift.common.model.PushMessage;
import cn.com.ty.lift.common.model.PushUserInfo;
import cn.com.ty.lift.ud.userAccount.service.IUserAccountService;
import cn.com.ty.lift.ud.userInfo.controller.query.UserInfoQuery;
import cn.com.ty.lift.ud.userInfo.mapper.entity.RedEnvelopRequest;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoDto;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserLevelDto;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserRequest;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserVipDto;
import cn.com.ty.lift.ud.userInfo.service.IUserInfoService;
import cn.com.xwy.boot.web.dto.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 用户表 API
 *
 * @author Xson
 * @date 2020-05-09
 */
@Api(tags = "用户表 API - 魏瑞锋")
//@CrossOrigin
@RestController
@RequestMapping("/api/userInfos")
public class UserInfoController {

    private final Logger log = LoggerFactory.getLogger(UserInfoController.class);

    private @Autowired IUserInfoService userInfoService;
    
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    
    private @Autowired IUserAccountService iUserAccountService;

    @ApiOperation(value = "获取首页个人信息")
    @PostMapping("/getUserInfo/{id}")
    public RestResponse getUserInfo(@PathVariable("id") Long id) {
        if (id == null) {
            return RestResponse.fail("用户ID不能为空");
        }
        return userInfoService.getUserInfo(id);
    }

    @ApiOperation(value = "附近的人")
    @PostMapping("/getNearUser")
    public RestResponse getNearUser(@RequestBody UserInfoDto userInfoDto) {
        if (null == userInfoDto.getLon()) {
            return RestResponse.fail("经度不能为空");
        }
        if (null == userInfoDto.getLat()) {
            return RestResponse.fail("纬度不能为空");
        }
        // 经纬度范围限制
        if (userInfoDto.getLon().compareTo(0D) >= 0 && userInfoDto.getLon().compareTo(180D) <= 0
            && userInfoDto.getLat().compareTo(0D) >= 0 && userInfoDto.getLat().compareTo(90D) <= 0) {
            return userInfoService.getNearUser(userInfoDto);
        }
        return RestResponse.fail(null, "经纬度值超出范围");
    }

    @PostMapping("/listExpert")
    @ApiOperation(value = "专家列表")
    public RestResponse listExpert(@RequestBody UserInfoQuery userInfoQuery) {
        return userInfoService.listExpert(userInfoQuery);
    }

    @PostMapping("/listGroupExpert")
    @ApiOperation(value = "app 专家abc分别列表")
    public RestResponse listGroupExpert(@RequestBody UserInfoQuery userInfoQuery) {
        return userInfoService.listGroupExpert(userInfoQuery);
    }

    @PostMapping("/queryAllExpert")
    @ApiOperation(value = "所有专家")
    public RestResponse queryAllExpert() {
        return userInfoService.queryAllExpert();
    }

    @GetMapping("/query/{id}")
    @ApiOperation(value = "获取用户详情")
    public RestResponse get(@PathVariable("id") Long id) {
        UserInfoEntity finOneById = userInfoService.getByUserId(id);
        return RestResponse.success(finOneById, "Queried successfully");
    }

    @PostMapping("/addExpert")
    @ApiOperation(value = "添加专家")
    public RestResponse addExpert(@RequestBody UserInfoEntity userInfoEntity) {
        return userInfoService.addExpert(userInfoEntity);
    }

    @PostMapping("/addUser")
    @ApiOperation(value = "新增用户")
    public RestResponse addUser(@RequestBody UserRequest userRequest) {
        if (null == userRequest.getMobile()) {
            return RestResponse.fail("手机号不能为空");
        }
        if (null == userRequest.getPassword()) {
            return RestResponse.fail("密码不能为空");
        }
        if (null == userRequest.getName()) {
            return RestResponse.fail("真实姓名不能为空");
        }
        return userInfoService.addUser(userRequest);
    }

    @PostMapping("/deleteUser")
    @ApiOperation(value = "冻结用户")
    public RestResponse deleteUser(@RequestBody DelReq req) {
        return userInfoService.deleteUser(req.getIds());
    }

    @PostMapping("/noDeleteUser")
    @ApiOperation(value = "启用用户")
    public RestResponse noDeleteUser(@RequestBody DelReq req) {
        return userInfoService.noDeleteUser(req.getIds());
    }

    @PostMapping("/updateUser")
    @ApiOperation(value = "修改用户信息")
    public RestResponse updateUser(@RequestBody UserInfoEntity userInfoEntity) {
        return userInfoService.updateUser(userInfoEntity);
    }

    @PostMapping("/listUser")
    @ApiOperation(value = "用户列表")
    public RestResponse listUser(@RequestBody UserInfoQuery userInfoQuery) {
        return userInfoService.listUser(userInfoQuery);
    }

    @PostMapping("/toWhichVip/{userId}")
    @ApiOperation(value = "后台判断当前用户是否可以升级为vip")
    public RestResponse toWhichVip(@PathVariable("userId") Long userId) {
        return userInfoService.toWhichVip(userId);
    }

    @PostMapping("/toVip")
    @ApiOperation(value = "后台升级为会员")
    public RestResponse toVip(@RequestBody UserVipDto urEntity) {
        if(null == urEntity.getUserId()){
            return RestResponse.fail("用户ID不能为空");
        }
        return userInfoService.toVip(urEntity);
    }

    @PostMapping("/cancelVip")
    @ApiOperation(value = "后台取消会员")
    public RestResponse cancelVip(@RequestBody UserLevelDto userLevelDto) {
        return userInfoService.cancelVip(userLevelDto);
    }

    @PostMapping("/toVipApp")
    @ApiOperation(value = "app端升级为会员")
    public RestResponse toVipApp(@RequestBody UserVipDto urEntity) {
        if(null == urEntity.getUserId()){
            return RestResponse.fail("用户ID不能为空");
        }
        return userInfoService.toVipApp(urEntity);
    }

    @GetMapping("/punishment")
    @ApiOperation(value = "惩罚（弃用）")
    @Deprecated
    public RestResponse punishment(Long userId, BigDecimal money) {
        return userInfoService.updateUserBalance(userId, money);
    }

    @GetMapping("/sendRedEnvelope")
    @ApiOperation(value = "发红包")
    public RestResponse sendRedEnvelope(Long userId, Long redEncelopId) {
        return userInfoService.sendRedEnvelope(userId, redEncelopId);
    }

    @PostMapping("/batchSendRedEnvelope")
    @ApiOperation(value = "批量发红包")
    public RestResponse batchSendRedEnvelope(@RequestBody RedEnvelopRequest redEnvelopRequest) {
        return userInfoService.batchSendRedEnvelope(redEnvelopRequest.getUserList(), redEnvelopRequest.getRedElvelopId());
    }

    //todo  测试用
    @PostMapping("/cancelOverTimeVip")
    @ApiOperation(value = "测试-定时任务取消会员")
    public void cancelOfVip( ) {
          userInfoService.cancelOverTimeVip();
    }
    
    @GetMapping("/invitationUserToExpert")
    @ApiOperation(value = "邀请成为专家")
    public RestResponse invitationUserToExpert(String userId) {
        //发送消息,信鸽推送
        PushUserInfo pushUserInfo = iUserAccountService.getPushUserInfoByUserId(userId);
        PushMessage pushMessage = PushMessage.invitationUserToExpert();
        pushMessage.sendTokenOnPlatform(jmsMessagingTemplate, pushUserInfo);
        return RestResponse.success("邀请成功");
    }

    @PostMapping("/rebuildQrCode/{userId}")
    @ApiOperation(value = "重新生成邀请码和二维码图片")
    public RestResponse rebuildQrCode(@PathVariable("userId") Long userId) {
        try {
            String qrCodeUrl = QrCodeUtil.getQrCode(userId, "/wode/vip");
            //
            int code = (int)(((Math.random() * 9) + 1) * 100000);
            UserInfoEntity userInfo = new UserInfoEntity();
            userInfo.setUserId(userId);
            userInfo.setQrCodeUrl(qrCodeUrl);
            userInfo.setRequestCode(code);
            userInfoService.updateUser(userInfo);
            return RestResponse.success(null,"生成成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.success(null,"生成失败");
        }


    }

    @GetMapping("/getNewInfo")
    @ApiOperation(value = "查询最新的用户信息和app菜单权限")
    public RestResponse getNewInfo( Long userId) {
        return userInfoService.getNewInfo(userId);
    }
    
    @GetMapping("/getUserByCompanyId")
    @ApiOperation(value = "查询团队下的用户")
    public RestResponse getUserByCompanyId( Long companyId) {
        if(companyId == null) {
            return RestResponse.fail("您未加入团队");
        }
        return userInfoService.getUserByCompanyId(companyId);
    }

    @GetMapping("/getExpertRewardedCount")
    @ApiOperation(value = "获取专家被打赏的次数")
    public RestResponse getExpertRewardedCount(Long expert) {
        if(expert == null) {
            return RestResponse.fail("专家id不能为空");
        }
        return userInfoService.getExpertRewardedCount(expert);
    }


    @GetMapping("/getRewardList")
    @ApiOperation(value = "获取用户打赏记录")
    public RestResponse getRewardList(Long userId) {
        if(userId == null) {
            return RestResponse.fail("用户id不能为空");
        }

        return userInfoService.getRewardList(userId);
    }


    @PostMapping("/saveVipID")
    @ApiOperation(value = "添加会员ID")
    public RestResponse saveVipID(@RequestBody UserInfoEntity entity){
        if (null == entity.getUserId()){
            return RestResponse.fail("用户id不能为空");
        }
        if (entity.getUserId().equals(-1L)){
            return RestResponse.fail("不能对游客进行操作");
        }
        if (StringUtils.isBlank(entity.getVipId())){
            return RestResponse.fail("vip id为不能为空");
        }
        return userInfoService.saveVipID(entity);
    }
}