package com.rj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rj.dto.hxr.HxrLbUserSelectResponse;
import com.rj.entity.LbUser;
import com.rj.mapper.LbUserMapper;
import com.rj.service.HxrAdminUserService;
import com.rj.service.ILbUserService;
import com.rj.tenant.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class LbUserServiceImpl extends ServiceImpl<LbUserMapper, LbUser> implements ILbUserService {

    private static final DateTimeFormatter DATETIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private HxrAdminUserService hxrAdminUserService;

    @Override
    public Map<String, Object> add(LbUser entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null) {
                result.put("success", false);
                result.put("message", "id不能为空");
                return result;
            }
            if (entity.getTenantId() == null || entity.getTenantId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return result;
            }
            entity.setTenantId(entity.getTenantId().trim());
            if (this.getById(entity.getId()) != null) {
                result.put("success", false);
                result.put("message", "该用户 id 已存在");
                return result;
            }

            applyDefaults(entity);
            LocalDateTime now = LocalDateTime.now();
            if (entity.getCreatedAt() == null) {
                entity.setCreatedAt(now);
            }
            if (entity.getUpdatedAt() == null) {
                entity.setUpdatedAt(now);
            }

            boolean ok = this.save(entity);
            result.put("success", ok);
            result.put("message", ok ? "新增成功" : "新增失败");
            if (ok) {
                result.put("data", this.getById(entity.getId()));
            }
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "新增异常：" + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> update(LbUser entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null) {
                result.put("success", false);
                result.put("message", "id不能为空");
                return result;
            }
            if (this.getById(entity.getId()) == null) {
                result.put("success", false);
                result.put("message", "记录不存在");
                return result;
            }

            entity.setUpdatedAt(LocalDateTime.now());
            boolean ok = this.updateById(entity);
            result.put("success", ok);
            result.put("message", ok ? "编辑成功" : "编辑失败");
            if (ok) {
                result.put("data", this.getById(entity.getId()));
            }
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "编辑异常：" + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> deleteById(Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = this.removeById(id);
            result.put("success", ok);
            result.put("message", ok ? "删除成功" : "删除失败");
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> pageQuery(
            Integer current,
            Integer size,
            String tenantId,
            Long pid,
            String username,
            String nickname,
            String mobile,
            String invite,
            Integer status,
            Integer isVip,
            Integer isResell,
            Integer level,
            String pname,
            String joinTimeStart,
            String joinTimeEnd,
            String updatedAtStart,
            String updatedAtEnd) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (current == null || current < 1) {
                current = 1;
            }
            if (size == null || size < 1) {
                size = 10;
            }

            LambdaQueryWrapper<LbUser> w = new LambdaQueryWrapper<>();
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                w.eq(LbUser::getTenantId, tenantId.trim());
            }
            if (pid != null) {
                w.eq(LbUser::getPid, pid);
            }
            if (username != null && !username.trim().isEmpty()) {
                w.like(LbUser::getUsername, username.trim());
            }
            if (nickname != null && !nickname.trim().isEmpty()) {
                w.like(LbUser::getNickname, nickname.trim());
            }
            if (mobile != null && !mobile.trim().isEmpty()) {
                w.like(LbUser::getMobile, mobile.trim());
            }
            if (invite != null && !invite.trim().isEmpty()) {
                w.eq(LbUser::getInvite, invite.trim());
            }
            if (status != null) {
                w.eq(LbUser::getStatus, status);
            }
            if (isVip != null) {
                w.eq(LbUser::getIsVip, isVip);
            }
            if (isResell != null) {
                w.eq(LbUser::getIsResell, isResell);
            }
            if (level != null) {
                w.eq(LbUser::getLevel, level);
            }
            if (pname != null && !pname.trim().isEmpty()) {
                w.like(LbUser::getPname, pname.trim());
            }

            LocalDateTime joinStart = parseDateTime(joinTimeStart);
            if (joinTimeStart != null && !joinTimeStart.trim().isEmpty() && joinStart == null) {
                result.put("success", false);
                result.put("message", "joinTimeStart 格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                return result;
            }
            LocalDateTime joinEnd = parseDateTime(joinTimeEnd);
            if (joinTimeEnd != null && !joinTimeEnd.trim().isEmpty() && joinEnd == null) {
                result.put("success", false);
                result.put("message", "joinTimeEnd 格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                return result;
            }
            if (joinStart != null) {
                w.ge(LbUser::getJoinTime, joinStart);
            }
            if (joinEnd != null) {
                w.le(LbUser::getJoinTime, joinEnd);
            }

            LocalDateTime updatedStart = parseDateTime(updatedAtStart);
            if (updatedAtStart != null && !updatedAtStart.trim().isEmpty() && updatedStart == null) {
                result.put("success", false);
                result.put("message", "updatedAtStart 格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                return result;
            }
            LocalDateTime updatedEnd = parseDateTime(updatedAtEnd);
            if (updatedAtEnd != null && !updatedAtEnd.trim().isEmpty() && updatedEnd == null) {
                result.put("success", false);
                result.put("message", "updatedAtEnd 格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                return result;
            }
            if (updatedStart != null) {
                w.ge(LbUser::getUpdatedAt, updatedStart);
            }
            if (updatedEnd != null) {
                w.le(LbUser::getUpdatedAt, updatedEnd);
            }

            w.orderByDesc(LbUser::getUpdatedAt).orderByDesc(LbUser::getId);

            Page<LbUser> page = this.page(new Page<>(current, size), w);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", page.getRecords());
            result.put("total", page.getTotal());
            result.put("current", page.getCurrent());
            result.put("size", page.getSize());
            result.put("pages", page.getPages());
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return result;
        }
    }

    private static void applyDefaults(LbUser entity) {
        if (entity.getLevel() == null) {
            entity.setLevel(0);
        }
        if (entity.getMoney() == null) {
            entity.setMoney(BigDecimal.ZERO);
        }
        if (entity.getCoupon() == null) {
            entity.setCoupon(BigDecimal.ZERO);
        }
        if (entity.getSelfBonus() == null) {
            entity.setSelfBonus(BigDecimal.ZERO);
        }
        if (entity.getShareBonus() == null) {
            entity.setShareBonus(BigDecimal.ZERO);
        }
        if (entity.getScore() == null) {
            entity.setScore(0);
        }
        if (entity.getStatus() == null) {
            entity.setStatus(1);
        }
        if (entity.getIsVip() == null) {
            entity.setIsVip(0);
        }
        if (entity.getMaxOrder() == null) {
            entity.setMaxOrder(0);
        }
        if (entity.getIsResell() == null) {
            entity.setIsResell(0);
        }
        if (entity.getYesterdaySellCount() == null) {
            entity.setYesterdaySellCount(0);
        }
        if (entity.getTodayBuyCount() == null) {
            entity.setTodayBuyCount(0);
        }
        if (entity.getTodayBuyTotal() == null) {
            entity.setTodayBuyTotal(BigDecimal.ZERO);
        }
        if (entity.getTodaySellTotal() == null) {
            entity.setTodaySellTotal(BigDecimal.ZERO);
        }
        if (entity.getPoor() == null) {
            entity.setPoor(0);
        }
    }

    private static LocalDateTime parseDateTime(String text) {
        if (text == null || text.trim().isEmpty()) {
            return null;
        }
        try {
            return LocalDateTime.parse(text.trim(), DATETIME_FMT);
        } catch (DateTimeParseException e) {
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> syncFromHxrAdmin(String tenantId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tenantId == null || tenantId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return result;
            }

            String tid = tenantId.trim();
            String previousTenantId = TenantContextHolder.getTenantId();
            TenantContextHolder.setTenantId(tid);
            try {
                HxrLbUserSelectResponse firstBody = null;
                int page = 1;
                int totalSynced = 0;
                while (true) {
                    Optional<HxrLbUserSelectResponse> opt = hxrAdminUserService.fetchUserSelectPage(page);
                    if (opt.isEmpty()) {
                        if (page == 1) {
                            result.put("success", false);
                            result.put("message", "未拉取到用户（请检查 hxr.admin cookie/phpsid、网络或后台返回）");
                            result.put("synced", 0);
                            return result;
                        }
                        result.put("success", false);
                        result.put("message", "第 " + page + " 页拉取失败，已成功同步前 "
                                + (page - 1) + " 页共 " + totalSynced + " 条");
                        result.put("synced", totalSynced);
                        if (firstBody != null) {
                            result.put("remoteCount", firstBody.count());
                        }
                        result.put("pages", page - 1);
                        return result;
                    }

                    HxrLbUserSelectResponse body = opt.get();
                    if (firstBody == null) {
                        firstBody = body;
                    }
                    List<LbUser> rows = body.data();
                    if (rows == null || rows.isEmpty()) {
                        break;
                    }

                    List<LbUser> entities = new ArrayList<>(rows.size());
                    for (LbUser row : rows) {
                        if (row.getId() == null) {
                            continue;
                        }
                        row.setTenantId(tid);
                        applyDefaults(row);
                        entities.add(row);
                    }

                    int upserted = upsertBatch(entities);
                    if (upserted < 0) {
                        result.put("success", false);
                        result.put("message", "第 " + page + " 页保存失败，已成功同步前 "
                                + (page - 1) + " 页共 " + totalSynced + " 条");
                        result.put("synced", totalSynced);
                        result.put("remoteCount", firstBody.count());
                        result.put("pages", page - 1);
                        return result;
                    }
                    totalSynced += upserted;

                    if (rows.size() < HxrAdminUserService.USER_SELECT_PAGE_SIZE) {
                        break;
                    }
                    page++;
                }

                result.put("success", true);
                result.put("message", totalSynced == 0 ? "接口成功，无用户数据" : "同步完成");
                result.put("synced", totalSynced);
                result.put("remoteCount", firstBody != null ? firstBody.count() : 0);
                result.put("pages", page);
                return result;
            } finally {
                if (previousTenantId != null) {
                    TenantContextHolder.setTenantId(previousTenantId);
                } else {
                    TenantContextHolder.clear();
                }
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "同步异常：" + e.getMessage());
            result.put("synced", 0);
            log.error("syncFromHxrAdmin failed", e);
            return result;
        }
    }

    /**
     * @return 实际 upsert 条数；无有效 id 时返回 0；失败返回 -1
     */
    private int upsertBatch(List<LbUser> entities) {
        if (entities == null || entities.isEmpty()) {
            return 0;
        }
        Map<Long, LbUser> deduped = new LinkedHashMap<>();
        for (LbUser entity : entities) {
            if (entity.getId() != null) {
                deduped.put(entity.getId(), entity);
            }
        }
        if (deduped.isEmpty()) {
            return 0;
        }
        List<LbUser> rows = new ArrayList<>(deduped.values());
        try {
            baseMapper.upsertBatch(rows);
            return rows.size();
        } catch (Exception e) {
            log.error("lb_user upsertBatch failed, size={}", rows.size(), e);
            return -1;
        }
    }
}
