package com.sqx.modules.app.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserSadDetailsDao;
import com.sqx.modules.app.entity.UserMoneyArtificer;
import com.sqx.modules.app.entity.UserSadDetails;
import com.sqx.modules.app.service.UserMoneyArtificerService;
import com.sqx.modules.app.service.UserSadDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.entity.ArtificerTime;
import com.sqx.modules.artificer.entity.FundDetailsResult;
import com.sqx.modules.artificer.entity.Period;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.artificer.service.ArtificerTimeService;
import com.sqx.modules.common.service.CommonInfoService;
import jodd.util.StringUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class UserSadDetailsServiceImpl extends ServiceImpl<UserSadDetailsDao, UserSadDetails> implements UserSadDetailsService {


    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserMoneyArtificerService userMoneyArtificerService;
    @Autowired
    private ArtificerTimeService artificerTimeService;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private UserService userService;

    @Override
    public Result queryUserSadDetails(Integer page, Integer limit, Long userId,Integer classify,Integer type,Long artificerId) {
        IPage<UserSadDetails> page1 = new Page(page, limit);
        QueryWrapper<UserSadDetails> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        if(classify!=null){
            queryWrapper.eq("classify", classify);
        }
        if(type!=null){
            queryWrapper.eq("type", type);
        }
        if(artificerId!=null){
            queryWrapper.eq("artificer_id", artificerId);
        }
        queryWrapper.orderByDesc("create_time");
        return Result.success().put("data", baseMapper.selectPage(page1, queryWrapper));
    }

    @Override
    public Double monthIncome(String date, Long userId) {
        return baseMapper.monthIncome(date,userId);
    }

    @Override
    public BigDecimal selectSumRefund(Long userId,String startTime,String endTime) {

        return baseMapper.selectSumRefund(userId,startTime,endTime);
    }

    @Override
    public Result selectUserMoneyArtificer(Integer page,Integer limit,Long userId,Long artificerId,Integer user){
        IPage<UserMoneyArtificer> userMoneyArtificerIPage = userMoneyArtificerService.page(new Page<>(page, limit),
                new QueryWrapper<UserMoneyArtificer>()
                        .eq(userId!=null,"user_id", userId)
                        .eq(artificerId!=null,"artificer_id",artificerId));
        List<UserMoneyArtificer> records = userMoneyArtificerIPage.getRecords();

        String value = commonInfoService.findOne(392).getValue();
        for(UserMoneyArtificer userMoneyArtificer:records){
            userMoneyArtificer.setUserEntity(userService.getById(userMoneyArtificer.getUserId()));
            Artificer artificer = artificerService.selectArtificerById(userId,userMoneyArtificer.getArtificerId(),null,null);
            if(artificer!=null){
                if("30".equals(value)){

                    SimpleDateFormat sdfHour=new SimpleDateFormat("HH");
                    SimpleDateFormat sdfMinute=new SimpleDateFormat("mm");
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat md = new SimpleDateFormat("MM-dd");
                    Date dateTime = new Date();
                    Calendar calendar=Calendar.getInstance();
                    String hour = sdfHour.format(dateTime);
                    String minute = sdfMinute.format(dateTime);
                    int minuteInt = Integer.parseInt(minute);
                    int hourInt = Integer.parseInt(hour);
                    StringBuilder stringBuilders=new StringBuilder();
                    if(minuteInt>=30){
                        if(hourInt==23){
                            hourInt=0;
                            minuteInt=0;
                        }else{
                            minuteInt=0;
                            hourInt=hourInt+1;
                        }
                    }else{
                        minuteInt=30;
                    }

                    if(hourInt<10){
                        stringBuilders.append("0").append(hourInt);
                    }else{
                        stringBuilders.append(hourInt);
                    }
                    stringBuilders.append(":");
                    if(minuteInt<10){
                        stringBuilders.append("0").append(minuteInt);
                    }else{
                        stringBuilders.append(minuteInt);
                    }

                    calendar=Calendar.getInstance();
                    String date = simpleDateFormat.format(dateTime);
                    String oldDate = simpleDateFormat.format(dateTime);
                    hour = sdfHour.format(dateTime);
                    minute = sdfMinute.format(dateTime);
                    minuteInt = Integer.parseInt(minute);
                    hourInt = Integer.parseInt(hour);
                    if(minuteInt>=30){
                        if(hourInt==23){
                            hourInt=0;
                            minuteInt=0;
                            calendar.add(Calendar.DAY_OF_MONTH,1);
                            date = simpleDateFormat.format(calendar.getTime());
                        }else{
                            minuteInt=0;
                            hourInt=hourInt+1;
                        }
                    }else{
                        minuteInt=30;
                    }
                    while (true){
                        StringBuilder stringBuilder=new StringBuilder();
                        if(hourInt<10){
                            stringBuilder.append("0").append(hourInt);
                        }else{
                            stringBuilder.append(hourInt);
                        }
                        stringBuilder.append(":");
                        if(minuteInt<10){
                            stringBuilder.append("0").append(minuteInt);
                        }else{
                            stringBuilder.append(minuteInt);
                        }
                        ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("artificer_id", artificer.getArtificerId()).eq("artificer_date", date).eq("artificer_time", stringBuilder.toString()));
                        if(artificerTime==null){
                            if(oldDate.equals(date)){
                                artificer.setTime(stringBuilder.toString());
                            }else{
                                artificer.setTime(md.format(calendar.getTime())+" "+stringBuilder.toString());
                            }
                            if(artificer.getStatus()!=null && artificer.getStatus()==2){
                                artificer.setState(3);
                            }else{
                                if(stringBuilder.toString().equals(stringBuilders.toString())){
                                    artificer.setState(1);
                                }else{
                                    artificer.setState(2);
                                }
                            }

                            break;
                        }
                        if(minuteInt==30){
                            if(hourInt==23){
                                hourInt=0;
                                minuteInt=0;
                                calendar.add(Calendar.DAY_OF_MONTH,1);
                                date = simpleDateFormat.format(calendar.getTime());
                            }else{
                                minuteInt=0;
                                hourInt=hourInt+1;
                            }
                        }else{
                            minuteInt=30;
                        }
                    }
                }else{

                    SimpleDateFormat sdf=new SimpleDateFormat("HH");

                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat md = new SimpleDateFormat("MM-dd");
                    Date dateTime = new Date();
                    String date = simpleDateFormat.format(dateTime);
                    String oldDate = simpleDateFormat.format(dateTime);
                    String time = sdf.format(dateTime);
                    String times="";
                    if("23".equals(time)){
                        time="00";
                        times=time+":00";
                    }else{
                        time=String.valueOf(Integer.parseInt(time)+1);
                        times=time+":00";
                    }
                    String nowTimes=times;

                    Calendar calendar=Calendar.getInstance();
                    date = simpleDateFormat.format(dateTime);
                    oldDate = simpleDateFormat.format(dateTime);
                    time = sdf.format(dateTime);
                    times="";
                    if("23".equals(time)){
                        time="00";
                        times=time+":00";
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        date = simpleDateFormat.format(calendar.getTime());
                    }else{
                        time=String.valueOf(Integer.parseInt(time)+1);
                        times=time+":00";
                    }
                    while (true){
                        ArtificerTime artificerTime = artificerTimeService.getOne(new QueryWrapper<ArtificerTime>().eq("artificer_id", artificer.getArtificerId()).eq("artificer_date", date).eq("artificer_time", times));
                        if(artificerTime==null){
                            if(oldDate.equals(date)){
                                times=time+":00";
                                artificer.setTime(times);
                            }else{
                                times=time+":00";
                                artificer.setTime(md.format(calendar.getTime())+" "+times);
                            }
                            if(artificer.getStatus()!=null && artificer.getStatus()==2){
                                artificer.setState(3);
                            }else{
                                if(times.equals(nowTimes)){
                                    artificer.setState(1);
                                }else{
                                    artificer.setState(2);
                                }
                            }
                            break;
                        }
                        if("23".equals(time)){
                            time="00";
                            times=time+":00";
                            calendar.add(Calendar.DAY_OF_MONTH,1);
                            date = simpleDateFormat.format(calendar.getTime());
                        }else{
                            time=String.valueOf(Integer.parseInt(time)+1);
                            times=time+":00";
                        }
                    }
                }
            }
            userMoneyArtificer.setArtificer(artificer);
        }
        if(user!=null && user==1){
            return Result.success().put("data",new PageUtils(userMoneyArtificerIPage));
        }
        return Result.success().put("data",userMoneyArtificerIPage);
    }

    @Override
    public Result selectIncomeByArtificerId(Integer page, Integer limit,Period period) {
        IPage<UserSadDetails> page1 = new Page(page, limit);
        QueryWrapper<UserSadDetails> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", period.getArtificerId());
        if(StringUtil.isNotEmpty(period.getStartFundData().toString())){
            queryWrapper.between("create_time", period.getStartFundData(), period.getEndFundData());
        }
        if(period.getDetailsType()!= null){
            //方便前端判断 传1则查询全部 2查询收入 3查询支出
            switch (period.getDetailsType()){
                case 1:
                    break;
                case 2:
                    queryWrapper.eq("type", 1);
                    break;
                case 3:
                    queryWrapper.eq("type", 2);
                    break;
            }
        }
        //只查询操作余额的数据
        queryWrapper.eq("manipulate_type", 2);
        queryWrapper.orderByDesc("create_time");
        IPage<UserSadDetails> page2 =  baseMapper.selectPage(page1, queryWrapper);
        //资金明细添加到返回对象中
        FundDetailsResult fundDetailsResult = new FundDetailsResult();
        fundDetailsResult.setUserSadDetailsList(page2);
        QueryWrapper<UserSadDetails> queryWrapper1 = new QueryWrapper();
        QueryWrapper<UserSadDetails> queryWrapper2 = new QueryWrapper();
        queryWrapper1.eq("user_id", period.getArtificerId());
        queryWrapper1.select("sum(money) as sum_value");

        queryWrapper2.eq("user_id", period.getArtificerId());
        queryWrapper2.select("sum(money) as sum_value");
        if(StringUtil.isNotEmpty(period.getStartFundData().toString())){
            queryWrapper1.between("create_time", period.getStartFundData(), period.getEndFundData());
            queryWrapper2.between("create_time", period.getStartFundData(), period.getEndFundData());
        }
        //设置类型为进账
        queryWrapper1.eq("type", "1");
        //查询进账
        Map<String, Object> map = baseMapper.selectMaps(queryWrapper1).get(0);
        BigDecimal income = new BigDecimal(0);
        if(map != null) {
            income = new BigDecimal(map.get("sum_value").toString()) ;
        }
        //设置类型为出账
        queryWrapper2.eq("type", "2");
        //查询出账
        Map<String, Object> map2 = baseMapper.selectMaps(queryWrapper2).get(0);
        BigDecimal outgoing = new BigDecimal(0);
        //如果结果为空则没有出账使用默认值0计算
        if(map2 != null){
            outgoing = new BigDecimal(map2.get("sum_value").toString()) ;
        }
        //计算进账减去出账结果为用户该阶段可提现数据
        income.subtract(outgoing);
        //赋值资金明细
        fundDetailsResult.setIncome(income.subtract(outgoing).toString());
        //赋值查询数据开始时间
        fundDetailsResult.setStartFundData(period.getStartFundData());
        //赋值查询数据结束时间
        fundDetailsResult.setEndFundData(period.getEndFundData());
        return Result.success().put("data", fundDetailsResult);
    }
    @Override
    public List<UserSadDetails>  selectIncome(Period period) {
        QueryWrapper<UserSadDetails> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", period.getArtificerId());
        if(StringUtil.isNotEmpty(period.getStartFundData().toString())){
            queryWrapper.between("create_time", period.getStartFundData(), period.getEndFundData());
        }
        if(period.getDetailsType()!= null){
            //方便前端判断 传1则查询全部 2查询收入 3查询支出
            switch (period.getDetailsType()){
                case 1:
                    break;
                case 2:
                    queryWrapper.eq("type", 1);
                    break;
                case 3:
                    queryWrapper.eq("type", 2);
                    break;
            }
        }
        //只查询操作余额的数据
        queryWrapper.eq("manipulate_type", 2);
        queryWrapper.orderByDesc("create_time");
        List<UserSadDetails> page2 =  baseMapper.selectList(queryWrapper);
        return  page2;
    }

    /**
     * 插入明细表
     * update by caolei 2024-6-9
     * @param UserSadDetails
     * @return
     */
    @Override
    public int insert(UserSadDetails UserSadDetails){
        return baseMapper.insert(UserSadDetails);
    }

    @Override
    public Result selectArtificerQianbao(Long artificerId, String startTime, String endTime,Integer page, Integer limit) {
        Artificer artificer = artificerService.getById(artificerId);
        List<UserSadDetails> list = baseMapper.selectArtificerQianbao(artificer.getUserId(),startTime,endTime);
        String bqsr = "0";//本期收入
        for(UserSadDetails par:list){
            if(par.getType()==1){
                bqsr = par.getMoney().toString();
            }
        }
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        QueryWrapper<UserSadDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",artificer.getUserId());
        queryWrapper.eq("bl_role","2");
        queryWrapper.eq("bl_flag","1");
        queryWrapper.eq("state","2");
        queryWrapper.eq("classify","8");
        queryWrapper.ge(StringUtil.isNotEmpty(startTime),"create_time",startTime);
        queryWrapper.le(StringUtil.isNotEmpty(endTime),"create_time",endTime+" 23:59:59");
        IPage<UserSadDetails> iPage = baseMapper.selectPage(new Page<>(page, limit),queryWrapper);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("bqsr",bqsr);
        map.put("startFundData",startTime);
        map.put("endFundData",endTime);
        map.put("data",iPage);
        return Result.success(map);
    }

    @Override
    public BigDecimal selectArtificerMoney(Long userId, @Param("startTime") String startTime, @Param("endTime") String endTime){
        return baseMapper.selectArtificerMoney(userId,startTime,endTime);
    }
}
