package com.sqx.modules.creditRecord.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.DateUtils;
import com.sqx.common.utils.ShiroUtils;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.creditRecord.dao.CreditRecordDao;
import com.sqx.modules.creditRecord.entity.CreditRecord;
import com.sqx.modules.creditRecord.entity.CreditRecordEntity;
import com.sqx.modules.creditRecord.entity.CreditRecordMapEntity;
import com.sqx.modules.creditRecord.service.CreditRecordService;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-05-17
 */
@Service
public class CreditRecordServiceImpl extends ServiceImpl<CreditRecordDao, CreditRecord> implements CreditRecordService {

    @Autowired
    private UserService userService;
    @Resource
    private CreditRecordDao creditRecordDao;

    @Override
    public IPage<CreditRecord> getCreditRecordList(Integer page, Integer limit, CreditRecord creditRecord) {
        Page<CreditRecord> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(creditRecord).orderByDesc("create_time"));
    }

    @Override
    public void updateUserCreditRecord(UserEntity userEntity, Integer type, Integer score, String remark,String orderNo,Integer isDriver) {
        CreditRecord creditRecord = new CreditRecord();
        creditRecord.setCreateTime(LocalDateTime.now());
        creditRecord.setLastCreditScore(userEntity.getCreditScore());
        creditRecord.setType(type);
        creditRecord.setRiderUserId(userEntity.getUserId());
        creditRecord.setRiderPhone(userEntity.getPhone());
        creditRecord.setRiderUserName(userEntity.getUserName());
        creditRecord.setNum(score);
        int nowScore;
        if (type == 1) {
            nowScore = userEntity.getCreditScore() + score;
        } else {
            nowScore = userEntity.getCreditScore() - score;
        }
        creditRecord.setNextCreditScore(nowScore);
        SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
        if (sysUserEntity!=null){
            creditRecord.setSysUserId(sysUserEntity.getUserId());
            creditRecord.setSysUserName(sysUserEntity.getUsername());
        }else {
            creditRecord.setSysUserId(userEntity.getUserId());
            creditRecord.setSysUserName(userEntity.getUserName());
        }
        creditRecord.setReason(remark);
        creditRecord.setOrdersNo(orderNo);
        creditRecord.setIsDriver(isDriver);
        baseMapper.insert(creditRecord);

        if (isDriver == 0){
            userEntity.setCreditScore(nowScore);
        }else {
            userEntity.setCreditScoreSf(nowScore);
        }
        userService.updateById(userEntity);
    }

    @Override
    public CreditRecordEntity getScore(Long userId, Integer isDriver){
        return creditRecordDao.getScore(userId,isDriver);
    }

    public Map<String,Object> getFilledScore(Long userId, Integer isDriver,Integer several){
        //获取过滤时间并格式化
        String createTime = userService.selectUserById(userId).getCreateTime();
        Date parse = null;
        try {
            parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String format = DateUtils.format(parse, DateUtils.DATE_PATTERN_MONTH);
        //从数据库取所需数据
        Map<String, Object> orderedMap = new LinkedHashMap<>();
        List<CreditRecordMapEntity> filledScore = creditRecordDao.getFilledScore(userId, isDriver, several);
        for (CreditRecordMapEntity c :filledScore) {
            orderedMap.put(c.getMonth(),c.getFilledScore());
        }
        //过滤创建时间之前的数据
        Map<String, Object> filtered = new LinkedHashMap<>();
        for (Map.Entry<String, Object> entry : orderedMap.entrySet()) {
            String month = entry.getKey(); // 格式：yyyy-MM
            if (month.compareTo(format) >= 0) {
                filtered.put(month,entry.getValue());
            }
        }
        return orderedMap;
    }
}
