package com.sqx.modules.app.controller.app;

import cn.hutool.core.date.DateUtil;
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.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyArtificer;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserMoneyResult;
import com.sqx.modules.app.service.UserMoneyArtificerService;
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.entity.Artificer;
import com.sqx.modules.artificer.entity.Period;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.utils.PeriodUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/app/userMoney")
@Api("app 钱包 ")
public class AppUserMoneyController {

    private UserMoneyService userMoneyService;
    private UserMoneyDetailsService userMoneyDetailsService;
    private UserMoneyArtificerService userMoneyArtificerService;
    private UserService userService;
    private ArtificerService artificerService;

    @Login
    @GetMapping("/selectUserMoneyArtificer")
    @ApiOperation("查询用户充值师傅钱包")
    public Result selectUserMoneyArtificer(Integer page,Integer limit,Long artificerId,@RequestAttribute Long userId){
        return userMoneyDetailsService.selectUserMoneyArtificer(page, limit, userId,artificerId,1);
    }

    @Login
    @GetMapping("/selectUserMoneyArtificers")
    @ApiOperation("查询用户充值师傅钱包")
    public Result selectUserMoneyArtificers(Integer page,Integer limit,Long artificerId){
        IPage<UserMoneyArtificer> page1 = userMoneyArtificerService.page(new Page<>(page, limit), new QueryWrapper<UserMoneyArtificer>().eq(artificerId != null, "artificer_id", artificerId));
        List<UserMoneyArtificer> records = page1.getRecords();
        for(UserMoneyArtificer userMoneyArtificer:records){
            userMoneyArtificer.setUserEntity(userService.getById(userMoneyArtificer.getUserId()));
            userMoneyArtificer.setArtificer(artificerService.selectArtificerById(null,userMoneyArtificer.getArtificerId(),null,null));
        }

        return Result.success().put("data",new PageUtils(page1));
    }

    @Login
    @PostMapping("/payUserMoneyArtificer")
    @ApiOperation("钱包充值 用户指定师傅钱包")
    public Result payUserMoneyArtificer(@RequestAttribute Long userId,Long artificerId,BigDecimal money){
        return userMoneyService.payUserMoneyArtificer(userId, artificerId, money);
    }



    @GetMapping("/selectMyMoney")
    @Login
    @ApiOperation("我的钱包余额")
    public Result selectMyMoney(@RequestAttribute Long userId) {
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        UserMoneyResult userMoneyResult = new UserMoneyResult();
        userMoneyResult.setUserId(userMoney.getUserId());
        userMoneyResult.setMoney(userMoney.getMoney());
        userMoneyResult.setCashDeposit(userMoney.getCashDeposit());
        userMoneyResult.setId(userMoney.getId());
        //获取当前时间
        Date CurrentPeriod = new Date();
        //获取当前时间周期的上一个周期
        Period periodDate= PeriodUtil.previousIssue(CurrentPeriod);
        Period period = new Period();
        period.setArtificerId(String.valueOf(userId));
        period.setDetailsType(1);
        //获取上一周期的最后一天
        period.setStartFundData(periodDate.getStartFundData());
//        period.setEndFundData(CurrentPeriod);
        period.setEndFundData(periodDate.getEndFundData());
        List<UserMoneyDetails> filteredPersons = userMoneyDetailsService.selectIncome(period);
        //进账
        double incomeLong=  filteredPersons.stream()
                .filter(UserMoneyDetails -> UserMoneyDetails.getType() == 1)
                .mapToDouble(UserMoneyDetails -> UserMoneyDetails.getMoney().doubleValue())
                .sum();
        //出账
        double outgoingLong=  filteredPersons.stream()
                .filter(UserMoneyDetails -> UserMoneyDetails.getType() == 2)
                .filter(UserMoneyDetails -> !UserMoneyDetails.getContent().contains("管理端减少"))
                .mapToDouble(UserMoneyDetails -> UserMoneyDetails.getMoney().doubleValue())
                .sum();

        BigDecimal income = BigDecimal.valueOf(incomeLong).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal outgoing = BigDecimal.valueOf(outgoingLong).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal balance = income.subtract(outgoing).setScale(2,BigDecimal.ROUND_HALF_UP);

//        BigDecimal ktxje = userMoney.getMoney().subtract(balance);
        if(balance.compareTo(BigDecimal.ZERO) < 0){
            balance = BigDecimal.ZERO;
        }
        //插入可提现金额
        userMoneyResult.setWithdrawableAmount(balance);
        return Result.success().put("data",userMoneyResult);
    }

    /**
     * 我的收益
     */
    @GetMapping("/selectMyProfit")
    @Login
    @ApiOperation("我的收益")
    public Result selectMyProfit(@RequestAttribute Long userId) {
        return Result.success().put("data", userMoneyService.selectMyProfit(userId));
    }


    /**
     * 余额明细
     */
    @GetMapping("/balanceDetailed")
    @Login
    @ApiOperation("余额明细")
    public Result balanceDetailed(@RequestAttribute Long userId, Long page, Long limit) {
        Page<UserMoneyDetails> pages = new Page<>(page, limit);
        return Result.success().put("data", userMoneyService.balanceDetailed(userId, pages));
    }

    @Login
    @ApiOperation("钱包明细")
    @GetMapping("/queryUserMoneyDetails")
    public Result queryUserMoneyDetails(Integer page, Integer limit,@RequestAttribute Long userId,Integer classify,Integer type,Long artificerId) {

        return userMoneyDetailsService.queryUserMoneyDetails(page, limit, userId,classify,type,artificerId);
    }

    /**
     * 收益明细
     */
    @GetMapping("/profitDetailed")
    @Login
    @ApiOperation("收益明细")
    public Result profitDetailed(@RequestAttribute Long userId, Long page, Long limit,Integer fundType) {
        Artificer artificer = artificerService.selectArtificerByUserId(userId);

        String startTime = "";
        String endTime = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(fundType==1){//当日
            startTime = sdf.format(new Date());
            endTime = sdf.format(new Date())+" 23:59:59";
        }else if(fundType == 2){//当期
            Period period = new Period();
            period.setArtificerId(artificer.getArtificerId()+"");
            period.setFundData(new Date());
            period.setFundType(1);
            period = PeriodUtil.calculationPeriod(period);
            startTime = sdf.format(period.getStartFundData());
            endTime = sdf.format(period.getEndFundData())+" 23:59:59";
        }else if(fundType == 3){//当月
            Period period = new Period();
            period.setArtificerId(artificer.getArtificerId()+"");
            period.setFundData(new Date());
            period.setFundType(3);
            period = PeriodUtil.calculationPeriod(period);
            startTime = sdf.format(period.getStartFundData());
            endTime = sdf.format(period.getEndFundData())+" 23:59:59";
        }

        if(page == null){page = 1L;}
        if(limit == null){limit = 10L;}
        Page page1 = new Page(page, limit);
        return userMoneyService.profitDetailed(artificer.getArtificerId(), page1,startTime,endTime);
    }



}
