package com.sqx.modules.app.controller;

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.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserVip;
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.app.service.UserVipService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.creditRecord.service.CreditRecordService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.pay.service.PayDetailsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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 CommonInfoService commonInfoService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CreditRecordService recordService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CashOutService cashOutService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserVipService userVipService;

    @ApiOperation("赠送用户会员")
    @PostMapping("/giveUserVip")
    public Result giveUserVip(Long userId, Integer type, Integer day) {
        return userService.giveUserVip(userId, type, day);
    }

    @GetMapping(value = "/getRiderList")
    @ApiOperation("获取骑手列表")
    public Result getRiderList(Integer page, Integer limit, UserEntity userEntity) {
        return Result.success().put("data", userMoneyService.getRiderList(page, limit, userEntity));
    }


    @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);
        UserVip userVip = userVipService.selectUserVipByUserId(userId);
        if(userVip!=null){
            userEntity.setIsVip(userVip.getIsVip());
            userEntity.setEndTime(userVip.getEndTime());
        }else{
            userEntity.setIsVip(2);
        }
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        Double money = userMoney.getMoney().doubleValue();
        Double inviteMoney = userMoney.getInviteMoney().doubleValue();
        String date = DateUtils.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        BigDecimal income = cashOutService.sumMoney(date, "month",1);
        //查询邀请人数
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        //本月接单
        int takeOrdersCount = ordersService.selectTakeOrdersCount(userId, date);
        //本月订单
        int myOrdersCount = ordersService.selectMyOrdersCount(userId, date);

        map.put("money", money);
        map.put("inviteMoney", inviteMoney);
        map.put("userEntity", userEntity);
        map.put("consume", consume);
        map.put("income", income);
        map.put("count", count);
        map.put("takeOrdersCount", takeOrdersCount);
        map.put("myOrdersCount", myOrdersCount);
        return Result.success().put("data", map);
    }


    @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) {
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        if (type == 1) {
            userDao.updateMoney(1, userId, money);
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserType(2);
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("管理端充值：" + money);
            userMoneyDetails.setTitle("管理端充值金额");
            userMoneyDetails.setType(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        } else {
            userDao.updateMoney(2, userId, money);
            userMoneyDetails.setUserType(2);
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("管理端减少：" + money);
            userMoneyDetails.setTitle("管理端减少金额");
            userMoneyDetails.setType(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));

        }
        userMoneyDetailsService.save(userMoneyDetails);
        return Result.success();
    }


    @RequestMapping(value = "/selectUserList", method = RequestMethod.GET)
    @ApiOperation("查询所有用户列表")
    @ResponseBody
    public Result selectUserList(Integer page, Integer limit,UserEntity userEntity) {
        return Result.success().put("data", userService.selectUserPage(page, limit, userEntity));
    }


    @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);
        } 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));
        //设置今日新增
        homeMessageResponse.setNewToday(userService.queryUserCount(1, null));
        //设置本月新增
        homeMessageResponse.setNewMonth(userService.queryUserCount(2, null));
        //设置本年新增
        homeMessageResponse.setNewYear(userService.queryUserCount(3, 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);
    }

    /**
     * 接单分析
     *
     * @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));
        userMessageResponse.setVipUserNumber(userService.userMessage(date, type));
        userMessageResponse.setUserNumber(userService.queryUserCount(type, date) - userService.userMessage(date, type));
        return Result.success().put("data", userMessageResponse);
    }

    @GetMapping("/updateUserMoney")
    @ApiOperation("修改用户余额")
    public Result updateUserMoney(Integer type, Long userId, BigDecimal money) {
        return userMoneyService.updateUserMoney(type, userId, money);
    }

    /**
     * @param userId 用户id
     * @param type   1:增加 2减少
     * @param score  操作的分数
     * @return
     */
    @ApiOperation("修改用户信用分")
    @PostMapping("updateUserCredit")
    public Result updateUserCredit(Long userId, Integer type, Integer score, String remark,String orderNo,Integer isDriver) {
        int maxScore = Integer.parseInt(commonInfoService.findOne(363).getValue());
        if (score <= 0) {
            return Result.error("请填入大于0的数");
        }
        UserEntity userEntity = userService.getById(userId);
        String text;
        if (type == 1) {
            text = "增加";
            if (userEntity.getCreditScore() + score > maxScore) {
                return Result.error("最多增加" + (maxScore - userEntity.getCreditScore()) + "分");
            }
            recordService.updateUserCreditRecord(userEntity, 1, score, remark,orderNo,isDriver);
        } else {
            text = "扣除";
            if (userEntity.getCreditScore() < score) {
                return Result.error("当前用户最多扣除" + userEntity.getCreditScore() + "分");
            }
            recordService.updateUserCreditRecord(userEntity, 2, score, remark,orderNo,isDriver);
        }
        MessageInfo riderMessageInfo = new MessageInfo();
        riderMessageInfo.setContent("管理员" + text + "您" + score + "信用分,当前信用分" + userEntity.getCreditScore());
        riderMessageInfo.setTitle("信用分变动通知");
        riderMessageInfo.setState(String.valueOf(5));
        riderMessageInfo.setUserName(userEntity.getUserName());
        riderMessageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        riderMessageInfo.setCreateAt(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        riderMessageInfo.setIsSee("0");
        messageService.save(riderMessageInfo);
        return messageService.save(riderMessageInfo) ? Result.success() : Result.error();
    }

    @ApiOperation("数据中心")
    @GetMapping(value = "findDataCenter")
    public Result findDataCenter() {
        return userService.findDataCenter();
    }

    @ApiOperation("用户筛选")
    @GetMapping(value = "selectUserStatistics")
    public Result selectUserStatistics(String date, Integer dateType) {
        return userService.selectUserStatistics(date, dateType);
    }

    @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);
            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);
    }


}