package com.sqx.modules.app.controller;

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.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserVipDao;
import com.sqx.modules.app.dao.VipDetailsDao;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.response.HomeMessageResponse;
import com.sqx.modules.app.response.UserMessageResponse;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.dao.OrdersDao;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.entity.Certification;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.artificer.service.RealNameService;
import com.sqx.modules.bl.commission.jjr.entity.JjrData;
import com.sqx.modules.bl.commission.jjr.service.JjrDataService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jodd.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fang
 * @date 2020/7/30
 */
@RestController
@Api(value = "用户管理", tags = {"用户管理"})
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private PayDetailsService payDetailsService;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private RealNameService realNameService;
    @Autowired
    private CashOutService cashOutService;
    @Autowired
    private VipDetailsDao vipDetailsDao;
    @Autowired
    private UserVipDao userVipDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private JjrDataService jjrDataService;

    @GetMapping("/queryByInvitationCode")
    @ApiOperation("通过邀请码查询用户")
    public Result queryByInvitationCode(String invitationCode){
        UserEntity userEntity = userService.queryByInvitationCode(invitationCode);
        return Result.success().put("data",userEntity);
    }
    @GetMapping("/merchantPromotion")
    @ApiOperation("商家推广统计")
    public Result merchantPromotion(UserEntity userEntity,Integer page, Integer limit){
        IPage<UserEntity> ResultUserEntity = userService.merchantPromotion(userEntity,page,limit);
        return Result.success().put("data",ResultUserEntity);
    }


    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@ApiParam("用户id") @PathVariable Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.queryByUserId(userId);
        JjrData jjrData = jjrDataService.getByCode(userEntity.getBlJjrCode());
        if(jjrData != null){
            userEntity.setJjrName(jjrData.getName());
        }
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        //查询用户钱包
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        Double income = cashOutService.sumMoneyMonthByUserId(date, userId);
        //查询邀请人数
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        //本月订单数
        int ordersCount = ordersDao.selectCountOrderByUserId(userId,null, date);
        Artificer artificer = artificerService.selectArtificerByUserId(userId);
        //本月收入
        BigDecimal ordersMoney=new BigDecimal("0.00");
        if(artificer!=null){
            ordersMoney = ordersDao.selectSumMoneyMonth(artificer.getArtificerId(), date);
        }
        UserVip userVip = userVipDao.selectById(userId);
        if(userVip!=null){
            userEntity.setMember(userVip.getIsVip().intValue());
            userEntity.setVipEndTime(userVip.getEndTime());
        }
        map.put("artificer", artificer);
        map.put("userEntity", userEntity);
        map.put("money", userMoney);
        map.put("consume", consume);
        map.put("income", income);
        map.put("count", count);
        map.put("ordersCount", ordersCount);
        map.put("ordersMoney", ordersMoney);
        return Result.success().put("data", map);
    }

    @PostMapping("/updateSafetyMoney")
    @ApiOperation("修改")
    public Result updateSafetyMoney(Long userId,Integer type, BigDecimal money){
        userMoneyDao.updateCashDeposit(type, userId, money.doubleValue());
        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        userMoneyDetails.setClassify(1);
        userMoneyDetails.setUserId(userId);
        if(type==1){
            userMoneyDetails.setTitle("[保证金]增加保证金");
            userMoneyDetails.setContent("系统增加保证金");
        }else{
            userMoneyDetails.setTitle("[保证金]减少保证金");
            userMoneyDetails.setContent("系统减少保证金");
        }
        userMoneyDetails.setType(type);
        userMoneyDetails.setMoney(money);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(sdf.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        if(userMoney.getCashDeposit().doubleValue()>0){
            UserEntity userEntity = userService.selectUserById(userId);
            userEntity.setIsCashDeposit(2);
            userService.updateById(userEntity);
        }else{
            UserEntity userEntity = userService.selectUserById(userId);
            userEntity.setIsCashDeposit(1);
            userService.updateById(userEntity);
        }
        return Result.success();
    }



    @RequestMapping(value = "/addCannotMoney/{userId}/{money}/{type}", method = RequestMethod.POST)
    @ApiOperation("修改金额")
    @ResponseBody
    public Result addCannotMoney(@PathVariable("userId") Long userId,@PathVariable("money") Double money,@PathVariable("type") Integer type){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());

        Artificer artificer = artificerService.selectArtificerByUserId(userId);

        if(type==1){
            userMoneyService.updateMoney(1,userId,money);
            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userId);
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getMoney());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setByUserId(((SysUserEntity)SecurityUtils.getSubject().getPrincipal()).getUserId());
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("管理端充值："+money);
            userMoneyDetails.setTitle("管理端充值金额");
            userMoneyDetails.setType(1);
            userMoneyDetails.setCreateTime(format);
            if(artificer != null){
                userMoneyDetails.setBlRole(2);
            }else{
                userMoneyDetails.setBlRole(1);
            }
            userMoneyDetails.setBlFlag(1);
            userMoneyDetailsService.save(userMoneyDetails);
            PayDetails payDetails = new PayDetails();
            payDetails.setState(1);
            payDetails.setCreateTime(format);
            payDetails.setOrderId("系统充值金额");
            payDetails.setUserId(userId);
            payDetails.setMoney(money);
            payDetails.setClassify(5);
            payDetails.setRemark(((SysUserEntity)SecurityUtils.getSubject().getPrincipal()).getUserId().toString());
            payDetailsService.save(payDetails);
        }else{
            userMoneyService.updateMoney(2,userId,money);

            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userId);
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getMoney());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setByUserId(((SysUserEntity)SecurityUtils.getSubject().getPrincipal()).getUserId());
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("管理端减少："+money);
            userMoneyDetails.setTitle("管理端减少金额");
            userMoneyDetails.setType(2);
            userMoneyDetails.setCreateTime(format);
            if(artificer != null){
                userMoneyDetails.setBlRole(2);
            }else{
                userMoneyDetails.setBlRole(1);
            }
            userMoneyDetails.setBlFlag(1);
            userMoneyDetailsService.save(userMoneyDetails);
            PayDetails payDetails = new PayDetails();
            payDetails.setState(1);
            payDetails.setCreateTime(format);
            payDetails.setOrderId("系统减少金额");
            payDetails.setUserId(userId);
            payDetails.setMoney(money);
            payDetails.setClassify(5);
            payDetails.setRemark(((SysUserEntity)SecurityUtils.getSubject().getPrincipal()).getUserId().toString());
            payDetailsService.save(payDetails);
        }
        return Result.success();
    }


    @RequestMapping(value = "/selectUserList", method = RequestMethod.GET)
    @ApiOperation("查询所有用户列表")
    @ResponseBody
    public Result selectUserList(Integer page, Integer limit,
                                 @ApiParam("用户id 手机号 昵称 模糊搜索") String phone,
                                 @ApiParam("性别 1男 2女") Integer sex,
                                 @ApiParam("来源  ") String platform,
                                 @ApiParam("0全部  1用户 2技师  ") Integer isAuthentication,
                                 @ApiParam("手机终端") String sysPhone,
                                 @ApiParam("状态 1正常 2封禁") Integer status,
                                 String userName,String invitationCode,Integer member,
                                 Integer ordersUser,String inviterCode,Integer isAgency,
                                 Integer isShop,String artificerName) {
        return Result.success().put("data", userService.selectUserPage(page, limit, phone, sex, platform, isAuthentication,sysPhone,
                status,userName,invitationCode,inviterCode,member,ordersUser,isAgency,isShop,artificerName));
    }


    @RequestMapping(value = "/deleteUserByUserId/{userId}", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ResponseBody
    public Result deleteUserByUserId(@PathVariable("userId") Long userId) {
        userService.removeById(userId);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserByUserId", method = RequestMethod.POST)
    @ApiOperation("修改用户")
    @ResponseBody
    public Result updateUserByUserId(@RequestBody UserEntity userEntity) {
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserStatusByUserId", method = RequestMethod.GET)
    @ApiOperation("禁用或启用用户")
    @ResponseBody
    public Result updateUserByUserId(Long userId) {
        UserEntity byId = userService.getById(userId);
        if (byId.getStatus().equals(1)) {
            byId.setStatus(2);
            userService.sendMsg(byId.getPhone(),"fh");
        } else {
            byId.setStatus(1);
        }
        userService.updateById(byId);
        return Result.success();
    }


    /**
     * 获取openid
     *
     * @param code 微信code
     * @return openid
     */
    @GetMapping("/openId/{code:.+}/{userId}")
    @ApiOperation("根据code获取openid")
    public Result getOpenid(@PathVariable("code") String code, @PathVariable("userId") Long userId) {
        return userService.getOpenId(code, userId);
    }

    /**
     * 信息分析
     *
     * @return
     */
    @GetMapping("/homeMessage")
    @ApiOperation("信息分析")
    public Result homeMessage() {
        HomeMessageResponse homeMessageResponse = new HomeMessageResponse();
        //   0查总   1查天  2查月  3查年
        //设置总用户人数
        homeMessageResponse.setTotalUsers(userService.queryUserCount(0, null, null,null));
        //设置今日新增
        homeMessageResponse.setNewToday(userService.queryUserCount(1, null, null,null));
        //设置本月新增
        homeMessageResponse.setNewMonth(userService.queryUserCount(2, null, null,null));
        //设置本年新增
        homeMessageResponse.setNewYear(userService.queryUserCount(3, null, null,null));

        //设置总收入
        homeMessageResponse.setTotalRevenue(userService.queryPayMoney(0));
        //设置今日收入
        homeMessageResponse.setTodayRevenue(userService.queryPayMoney(1));
        //设置本月收入
        homeMessageResponse.setMonthRevenue(userService.queryPayMoney(2));
        //设置本年收入
        homeMessageResponse.setYearRevenue(userService.queryPayMoney(3));

        return Result.success().put("data", homeMessageResponse);
    }


    /**
     * 用户统计
     */
    @GetMapping("/selectUserMessage")
    @ApiOperation("用户统计")
    public Result selectUserMessage(String date, Integer type){
        //统计总用户、用户、技师、手机号用户
        int userCount = userService.queryUserCount(type, date,null,null);
        int puUserCount = userService.queryUserCount(type, date,1,null);
        int jiUserCount = userService.queryUserCount(type, date,2,null);
        int phoneUserCount = userService.queryUserCount(type, date,null,1);
        int appCount = userService.userPlatform("app", date, type);
        int wxCount = userService.userPlatform("小程序", date, type);
        int wapCount = userService.userPlatform("H5", date, type);
        Map<String,Integer> result=new HashMap<>();
        result.put("userCount",userCount);
        result.put("puUserCount",puUserCount);
        result.put("jiUserCount",jiUserCount);
        result.put("phoneUserCount",phoneUserCount);
        result.put("appCount",appCount);
        result.put("wxCount",wxCount);
        result.put("wapCount",wapCount);
        return Result.success().put("data",result);
    }

    /**
     * 服务收益
     */
    @GetMapping("/selectOrdersMoney")
    @ApiOperation("服务收益")
    public Result selectOrdersMoney(String date, Integer type){
        //总收入  1待支付  2进行中  3待评论  4已取消  5已完成
        BigDecimal sumMoney = ordersDao.selectOrdersMoney(date, type, 1);
        //进行中订单
        BigDecimal jinMoney = ordersDao.selectOrdersMoney(date, type, 2);
        //已完成订单
        BigDecimal wanMoney = ordersDao.selectOrdersMoney(date, type, 3);
        //平台收益
        BigDecimal pingMoney = ordersDao.selectOrdersMoney(date, type, 4);
        Map<String,BigDecimal> result=new HashMap<>();
        result.put("sumMoney",sumMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("jinMoney",jinMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("wanMoney",wanMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("pingMoney",pingMoney.setScale(2,BigDecimal.ROUND_DOWN));
        return Result.success().put("data",result);
    }

    /**
     * 订单统计
     */
    @GetMapping("/selectCountOrders")
    @ApiOperation("订单统计")
    public Result selectCountOrders(String date, Integer type){
        //状态 1待支付 2待服务 3待评论 4已取消  5已完成  6进行中  7出发 8到达
        int ordersCount = ordersDao.selectCountOrders(date, type, null);
        int dzfCount = ordersDao.selectCountOrders(date, type, 1);
        int dfwCount = ordersDao.selectCountOrders(date, type, 2);
        int dplCount = ordersDao.selectCountOrders(date, type, 3);
        int yqxCount = ordersDao.selectCountOrders(date, type, 4);
        int ywcCount = ordersDao.selectCountOrders(date, type, 5);
        int jxzCount = ordersDao.selectCountOrders(date, type, 6);
        int cfCount = ordersDao.selectCountOrders(date, type, 7);
        int ddCount = ordersDao.selectCountOrders(date, type, 8);
        Map<String,Integer> result=new HashMap<>();
        result.put("ordersCount",ordersCount);
        result.put("dzfCount",dzfCount);
        result.put("dfwCount",dfwCount);
        result.put("dplCount",dplCount);
        result.put("yqxCount",yqxCount);
        result.put("ywcCount",ywcCount);
        result.put("jxzCount",jxzCount);
        result.put("cfCount",cfCount);
        result.put("ddCount",ddCount);
        return Result.success().put("data",result);
    }


    @GetMapping("/selectMoneyCount")
    @ApiOperation("统计收益")
    public Result selectMoneyCount(String date,Integer type){
        //支付类型 1订单  2实名认证   3充值  4优惠券  5会员
        Double ordersMoney = payDetailsService.selectSumPayByType(date, type, 1);
        Double realMoney = payDetailsService.selectSumPayByType(date, type, 2);
        Double money = payDetailsService.selectSumPayByType(date, type, 3);
        Double couponMoney = payDetailsService.selectSumPayByType(date, type, 4);
        Double memberMoney = payDetailsService.selectSumPayByType(date, type, 5);
        Map<String,Object> result=new HashMap<>();
        BigDecimal sumMoney = BigDecimal.valueOf(ordersMoney).add(BigDecimal.valueOf(realMoney));
        sumMoney = sumMoney.add(BigDecimal.valueOf(money));
        sumMoney = sumMoney.add(BigDecimal.valueOf(couponMoney));
        sumMoney = sumMoney.add(BigDecimal.valueOf(memberMoney));
        result.put("ordersMoney",ordersMoney);result.put("realMoney",realMoney);
        result.put("money",money);result.put("couponMoney",couponMoney);
        result.put("memberMoney",memberMoney);result.put("sumMoney",sumMoney);
        return Result.success().put("data",result);
    }


    /**
     * 接单分析
     *
     * @return
     */
    @GetMapping("/takingOrdersMessage")
    @ApiOperation("接单分析")
    public Result takingOrdersMessage(Long page, Long limit, String date, Long type) {
        Page<Map<String, Object>> iPage = new Page<>(page, limit);
        return userService.takingOrdersMessage(iPage, type, date);
    }

    /**
     * 用户分析
     */
    @GetMapping("/userMessage")
    @ApiOperation("用户分析")
    public Result userMessage(String date, int type) {
        UserMessageResponse userMessageResponse = new UserMessageResponse();
        userMessageResponse.setTotalNumber(userService.queryUserCount(type, date, null,null));
        userMessageResponse.setVipUserNumber(userService.userMessage(date, type));
        userMessageResponse.setUserNumber(userService.queryUserCount(type, date, null,null) - userService.userMessage(date, type));
        return Result.success().put("data", userMessageResponse);
    }

    @PostMapping("/updateArtificer")
    @ApiOperation("修改用户为技师")
    public Result updateArtificer(@RequestBody Certification certification){
        if(certification.getStatus().equals(1)){
            UserEntity user = userService.getById(certification.getUserId());
            certification.setStatus(1);
            certification.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            user.setIsAuthentication(2);
            Artificer artificer = artificerService.selectArtificerByUserId(user.getUserId());
            if(artificer==null){
                artificer=new Artificer();
                artificer.setStatus(2);
                artificer.setUserId(certification.getUserId());
                artificer.setArtificerSales(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                artificer.setCreateTime(sdf.format(new Date()));
                artificer.setCreditScore(BigDecimal.valueOf(100));
                artificer.setTripWay(1);
                artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
            }
            artificer.setArtificerName(certification.getName());
            artificer.setArtificerImg(certification.getAvatar());
            artificer.setLifePhoto(certification.getImagePhoto());
            artificer.setCertificate(certification.getCertification());
            artificer.setContent(certification.getIndividualResume());
            artificer.setClassifyId(certification.getClassifyId());
            if(artificer.getArtificerId()!=null){
                artificerService.updateById(artificer);
            }else{
                artificerService.save(artificer);
            }


            BigDecimal cashDeposit = certification.getMoney();
            Long userId = user.getUserId();
            userMoneyDao.updateCashDeposit(1, userId, cashDeposit.doubleValue());
            user.setIsCashDeposit(2);
            userService.updateById(user);
        }else{
            UserEntity user = userService.getById(certification.getUserId());
            Artificer artificer = artificerService.selectArtificerByUserId(user.getUserId());
            if(artificer!=null){
                UserEntity userEntity = userService.selectUserById(artificer.getUserId());
                if(userEntity!=null){
                    userEntity.setIsAuthentication(0);
                    userService.updateById(userEntity);
                    realNameService.remove(new QueryWrapper<Certification>().eq("user_id",userEntity.getUserId()));
                }
                artificerService.removeById(artificer.getArtificerId());
            }

        }
        return Result.success();
    }


    @PostMapping("/updateUserIsAgency")
    @ApiOperation("修改是否为推广员")
    public Result updateUserIsAgency(Long userId,Integer isAgency){
        UserEntity userEntity=new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setIsAgency(isAgency);
        userService.updateById(userEntity);
        return Result.success();
    }

    @GetMapping("/selectAgencyOrdersMoneyList")
    @ApiOperation("查询推广员收益排行榜")
    public Result selectAgencyOrdersMoneyList(Integer page,Integer limit,String userName,String phone,String startTime,String endTime){
        return userService.selectAgencyOrdersMoneyList(page, limit, userName, phone, startTime, endTime);
    }


    @PostMapping("/giveUserVip")
    @ApiOperation("赠送用户会员")
    public Result giveUserVip(Long userId,Integer day){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查看用户是否是会员
        UserVip userVip = userVipDao.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
        Calendar cal = Calendar.getInstance();
        if(userVip!=null){
            Date endDate = null;
            try {
                endDate = sdf.parse(userVip.getEndTime());
                if (endDate != null && System.currentTimeMillis() < (endDate.getTime())) {
                    cal.setTime(endDate);
                }
            } catch (Exception e) {
                e.getMessage();
            }
        }else{
            userVip=new UserVip();
            //设置会员类型
            userVip.setVipNameType(1);
            //设置开通会员的用户id
            userVip.setUserId(userId);
            //设置会员的购买时间
            userVip.setCreateTime(sdf.format(new Date()));
            userVip.setIsVip(1L);
        }
        BigDecimal money=BigDecimal.ZERO;
        MessageInfo messageInfo=new MessageInfo();
        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        userMoneyDetails.setMoney(money);
        userMoneyDetails.setUserId(userId);

        userMoneyDetails.setContent("系统赠送"+day+"天会员");
        messageInfo.setContent("系统赠送"+day+"天会员");
        cal.add(Calendar.DAY_OF_MONTH, day);

        userVip.setEndTime(sdf.format(cal.getTime()));
        if(userVip.getVipId()!=null){
            userVipDao.updateById(userVip);
        }else{
            userVipDao.insert(userVip);
        }
        userMoneyDetails.setTitle("开通会员");
        userMoneyDetails.setType(2);
        userMoneyDetails.setCreateTime(sdf.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);
        UserEntity userEntity = userService.selectUserById(userId);
        messageInfo.setTitle("开通会员");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageInfo.setCreateAt(sdf.format(new Date()));
        messageInfo.setIsSee("0");
        messageService.saveBody(messageInfo);
        if(StringUtil.isNotBlank(userEntity.getClientid())){
            userService.pushToSingle(messageInfo.getTitle(),messageInfo.getContent(),userEntity.getClientid());
        }
        return Result.success();
    }

    @PostMapping("/removeUserVip")
    @ApiOperation("取消用户会员")
    public Result removeUserVip(Long userId){
        UserVip userVip = userVipDao.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
        if(userVip!=null){
            userVipDao.deleteById(userVip.getVipId());
        }
        UserEntity userEntity = userService.selectUserById(userId);
        MessageInfo messageInfo=new MessageInfo();
        messageInfo.setTitle("取消会员");
        messageInfo.setContent("系统取消了你的会员");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageInfo.setCreateAt(DateUtils.format(new Date()));
        messageInfo.setIsSee("0");
        messageService.saveBody(messageInfo);
        return Result.success();
    }

    @GetMapping("/selectUserCountStatisticsByTime")
    @ApiOperation("用户统计")
    public Result selectUserCountStatisticsByTime(String startTime,String endTime){
        List<Integer> userCountList=new ArrayList<>();
        List<String> year=new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=Calendar.getInstance();
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(parse);
        while (true){
            String dateTime = simpleDateFormat.format(calendar.getTime());
            int i = userService.queryUserCount(1, dateTime,null,null);
            userCountList.add(i);
            year.add(dateTime);
            if(dateTime.equals(endTime)){
                break;
            }
            calendar.add(Calendar.DATE,1);
        }
        Map<String,Object> result=new HashMap<>();
        result.put("userCountList",userCountList);
        result.put("year",year);
        return Result.success().put("data",result);
    }

    @PostMapping("/integral")
    @ApiOperation("积分")
    public Result integral(String type,Integer current,Integer size,String date,String artificerId) throws ParseException {
        return Result.success(userService.integral(type,current,size,date,artificerId));
    }
}