package com.haha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.exception.BusinessException;
import com.haha.entity.ErpShop;
import com.haha.entity.Shop;
import com.haha.mapper.ErpShopMapper;
import com.haha.mapper.ShopMapper;
import com.haha.service.ErpShopService;
import com.qdb.sdk.QdbClient;
import com.qdb.sdk.QdbException;
import com.qdb.sdk.model.request.ShopQueryRequest;
import com.qdb.sdk.model.response.QdbResponse;
import com.qdb.sdk.model.response.ShopInfo;
import com.qdb.sdk.model.response.ShopPageResult;
import lombok.RequiredArgsConstructor;
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.time.LocalDateTime;
import java.util.List;

/**
 * ERP 店铺信息服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErpShopServiceImpl extends ServiceImpl<ErpShopMapper, ErpShop> implements ErpShopService {

    private final ShopMapper shopMapper;

    @Autowired(required = false)
    private QdbClient qdbClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncFromErp() {
        if (qdbClient == null) {
            throw new BusinessException(500, "QdbClient 未配置，无法同步ERP店铺数据");
        }

        int pageNo = 1;
        int pageSize = 50;
        boolean hasMore = true;
        int syncedCount = 0;

        while (hasMore) {
            ShopQueryRequest request = ShopQueryRequest.builder()
                    .pageIndex(pageNo)
                    .pageSize(pageSize)
                    .build();

            try {
                QdbResponse<ShopPageResult> response = qdbClient.getShopApi().queryShopInfo(request);
                ShopPageResult pageResult = response.getData();

                if (pageResult == null || pageResult.getData() == null || pageResult.getData().isEmpty()) {
                    hasMore = false;
                    break;
                }

                for (ShopInfo shopInfo : pageResult.getData()) {
                    upsertErpShop(shopInfo);
                    syncedCount++;
                }

                // 判断是否还有下一页
                Integer total = pageResult.getTotal();
                if (total != null && pageNo * pageSize >= total) {
                    hasMore = false;
                } else if (pageResult.getData().size() < pageSize) {
                    hasMore = false;
                } else {
                    pageNo++;
                }

            } catch (QdbException e) {
                log.error("同步ERP店铺失败: pageNo={}, error={}", pageNo, e.getMessage());
                throw new BusinessException(500, "ERP店铺同步失败: " + e.getMessage());
            }
        }

        log.info("ERP店铺同步完成: 共同步 {} 条", syncedCount);
    }

    @Override
    public List<ErpShop> listAll() {
        return lambdaQuery()
                .eq(ErpShop::getStatus, 1)
                .orderByAsc(ErpShop::getShopName)
                .list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindShop(Long shopId, Long erpShopId) {
        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessException(404, "门店不存在");
        }

        // 检查 ERP 店铺是否存在
        ErpShop erpShop = getOne(new LambdaQueryWrapper<ErpShop>()
                .eq(ErpShop::getErpShopId, erpShopId));
        if (erpShop == null) {
            throw new BusinessException(404, "ERP店铺不存在，请先同步ERP店铺数据");
        }

        // 检查是否已被其他门店绑定
        List<Shop> boundShops = shopMapper.selectList(new LambdaQueryWrapper<Shop>()
                .eq(Shop::getErpShopId, erpShopId));
        if (!boundShops.isEmpty() && !boundShops.get(0).getId().equals(shopId)) {
            throw new BusinessException(400, "该ERP店铺已绑定到门店: " + boundShops.get(0).getName());
        }

        shop.setErpShopId(erpShopId);
        shop.setUpdateTime(LocalDateTime.now());
        shopMapper.updateById(shop);

        log.info("门店绑定ERP店铺: shopId={}, shopName={}, erpShopId={}, erpShopName={}",
                shopId, shop.getName(), erpShopId, erpShop.getShopName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindShop(Long shopId) {
        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessException(404, "门店不存在");
        }

        shop.setErpShopId(null);
        shop.setUpdateTime(LocalDateTime.now());
        shopMapper.updateById(shop);

        log.info("门店解绑ERP店铺: shopId={}, shopName={}", shopId, shop.getName());
    }

    /**
     * 插入或更新 ERP 店铺记录（按 erp_shop_id 判断）
     */
    private void upsertErpShop(ShopInfo info) {
        ErpShop existing = getOne(new LambdaQueryWrapper<ErpShop>()
                .eq(ErpShop::getErpShopId, info.getShopId()));

        if (existing != null) {
            existing.setOutShopId(info.getOutShopId());
            existing.setShopName(info.getShopName());
            existing.setShopPlatformCode(info.getShopPlatformCode());
            existing.setNickName(info.getNickName());
            existing.setShopCode(info.getShopCode());
            existing.setPlatformShopId(info.getPlatformShopId());
            existing.setAccessTokenExpiredTime(info.getAccessTokenExpiredTime());
            existing.setServiceExpirationTime(info.getServiceExpirationTime());
            existing.setAuthorizationFlag(info.getAuthorizationFlag());
            existing.setStatus(info.getStatus() != null ? Integer.parseInt(info.getStatus()) : 1);
            existing.setUpdateTime(LocalDateTime.now());
            updateById(existing);
        } else {
            ErpShop erpShop = new ErpShop();
            erpShop.setErpShopId(info.getShopId());
            erpShop.setOutShopId(info.getOutShopId());
            erpShop.setShopName(info.getShopName());
            erpShop.setShopPlatformCode(info.getShopPlatformCode());
            erpShop.setNickName(info.getNickName());
            erpShop.setShopCode(info.getShopCode());
            erpShop.setPlatformShopId(info.getPlatformShopId());
            erpShop.setAccessTokenExpiredTime(info.getAccessTokenExpiredTime());
            erpShop.setServiceExpirationTime(info.getServiceExpirationTime());
            erpShop.setAuthorizationFlag(info.getAuthorizationFlag());
            erpShop.setStatus(info.getStatus() != null ? Integer.parseInt(info.getStatus()) : 1);
            erpShop.setCreateTime(LocalDateTime.now());
            erpShop.setUpdateTime(LocalDateTime.now());
            save(erpShop);
        }
    }
}
