package com.ruoyi.xq.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.WxTransLog;
import com.ruoyi.xq.dto.admin.account.WxTransLogAdminVo;
import com.ruoyi.xq.dto.app.account.WxTransLogListVo;
import com.ruoyi.xq.dto.app.account.WxTransLogQuery;
import com.ruoyi.xq.dto.common.user.MinUser;
import com.ruoyi.xq.enums.account.WxTransLogCateEnum;
import com.ruoyi.xq.enums.common.SystemConfigEnum;
import com.ruoyi.xq.enums.image.ImagesEnums;
import com.ruoyi.xq.manager.SystemConfigManager;
import com.ruoyi.xq.mapper.WxTransLogMapper;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.service.WxTransLogService;
import com.ruoyi.xq.util.PageConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 微信交换记录Service业务层处理
 *
 * @author 77
 * @date 2024-03-25
 */
@Service
public class WxTransLogServiceImpl extends ServiceImpl<WxTransLogMapper,WxTransLog> implements WxTransLogService {
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfigManager systemConfigManager;

    @Override
    public Page<WxTransLogListVo> pageApp(PageQuery pageQuery, WxTransLogQuery query) {
        Page<WxTransLog> page = this.page(pageQuery.build(), Wrappers.lambdaQuery(WxTransLog.class)
                .eq(WxTransLog::getUserId, query.getUserId()).orderByDesc(WxTransLog::getCreateTime));
        List<WxTransLog> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return PageConvert.convertEmpty(page);
        }
        String cosDomain = systemConfigManager.getSystemConfig(SystemConfigEnum.COS_DOMAIN);
        List<Long> userIdList = records.stream().map(WxTransLog::getTarUserId).filter(Objects::nonNull).collect(Collectors.toList());
        List<User> users = userService.listByIds(userIdList);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        List<WxTransLogListVo> vo = new ArrayList<>();
        for (WxTransLog record : records) {
            WxTransLogListVo res = new WxTransLogListVo();
            res.setUserId(record.getUserId());
            res.setUsercode(record.getUsercode());
            res.setCateId(record.getCateId());
            res.setTitle(record.getCateName());
            res.setContent(record.getRemark());
            res.setCreateTime(record.getCreateTime());
            res.setChangeValue(record.getChangeValue());
            if(WxTransLogCateEnum.CONSUMER.getCode().equals(record.getCateId())){
                User user = userMap.get(record.getTarUserId());
                if(user != null){
                    res.setSourceUserId(user.getId());
                    res.setSourceNickname(user.getNickname());
                    res.setSourceImg(user.getAvatar());
                }
            }else if(WxTransLogCateEnum.VIP_GIVE.getCode().equals(record.getCateId())){
                res.setSourceImg(cosDomain + ImagesEnums.VIP_LOG.getPath());
            }else if(WxTransLogCateEnum.ORDER.getCode().equals(record.getCateId())){
                res.setSourceImg(cosDomain + ImagesEnums.CONSUMER_LOG.getPath());
            }else if(WxTransLogCateEnum.SYSTEM.getCode().equals(record.getCateId())){
                res.setSourceImg(cosDomain + ImagesEnums.SYSTEM_LOG.getPath());
            }
            if(res.getSourceImg() == null){
                res.setSourceImg(cosDomain + ImagesEnums.LOGO_LOG.getPath());
            }
            vo.add(res);
        }
        return PageConvert.convert(page,vo);
    }

    @Override
    public Page<WxTransLogAdminVo> pageAdmin(PageQuery pageQuery, WxTransLogAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(), bo);
    }

    @Override
    public void consumerSaveLog(Long sponsorUserId, String traceId, User receiveUser) {
        MinUser minUser = userService.getMinUserById(sponsorUserId);
        WxTransLog wxTransLog = new WxTransLog();
        wxTransLog.setUserId(minUser.getId());
        wxTransLog.setUsercode(minUser.getUsercode());
        wxTransLog.setTraceId(traceId);
        wxTransLog.setCateId(WxTransLogCateEnum.CONSUMER.getCode());
        wxTransLog.setCateName(WxTransLogCateEnum.CONSUMER.getText());
        wxTransLog.setRemark(String.format("对%s[%s]使用一次微信交换", receiveUser.getNickname(), receiveUser.getUsercode()));
        wxTransLog.setChangeValue(-1L);
        wxTransLog.setTarUserJson(JSON.toJSONString(receiveUser));
        wxTransLog.setTarUserId(receiveUser.getId());
        wxTransLog.setTarUsercode(receiveUser.getUsercode());
        this.save(wxTransLog);
    }

    @Override
    public void saveLog(Long userId, Integer wxTransNum, WxTransLogCateEnum cateEnum, String traceId, String remark) {
        MinUser minUser = userService.getMinUserById(userId);
        WxTransLog wxTransLog = new WxTransLog();
        wxTransLog.setUserId(minUser.getId());
        wxTransLog.setUsercode(minUser.getUsercode());
        wxTransLog.setTraceId(traceId);
        wxTransLog.setCateId(cateEnum.getCode());
        wxTransLog.setCateName(cateEnum.getText());
        wxTransLog.setRemark(cateEnum.getText());
        if(StringUtils.isNotBlank(remark)){
            wxTransLog.setRemark(remark);
        }
        wxTransLog.setChangeValue(Long.valueOf(wxTransNum));
        this.save(wxTransLog);
    }

    @Override
    public void saveLogAdmin(User user, Integer wxTransNum, String traceId) {
        WxTransLog wxTransLog = new WxTransLog();
        wxTransLog.setUserId(user.getId());
        wxTransLog.setUsercode(user.getUsercode());
        wxTransLog.setTraceId(traceId);
        wxTransLog.setCateId(WxTransLogCateEnum.SYSTEM.getCode());
        wxTransLog.setCateName(WxTransLogCateEnum.SYSTEM.getText());
        String a = wxTransNum>0?"新增":"减小";
        String remark = String.format("系统调账%s%s个微信交换", a, Math.abs(wxTransNum));
        wxTransLog.setRemark(remark);
        wxTransLog.setChangeValue(Long.valueOf(wxTransNum));
        this.save(wxTransLog);
    }
}
