package com.starry.admin.common.apitest;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.starry.admin.modules.clerk.module.entity.PlayClerkCommodityEntity;
import com.starry.admin.modules.clerk.module.entity.PlayClerkLevelInfoEntity;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.service.IPlayClerkCommodityService;
import com.starry.admin.modules.clerk.service.IPlayClerkLevelInfoService;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.custom.mapper.PlayCustomGiftInfoMapper;
import com.starry.admin.modules.custom.module.entity.PlayCustomGiftInfoEntity;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomGiftInfoService;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.personnel.module.entity.PlayPersonnelGroupInfoEntity;
import com.starry.admin.modules.personnel.service.IPlayPersonnelGroupInfoService;
import com.starry.admin.modules.shop.mapper.PlayClerkGiftInfoMapper;
import com.starry.admin.modules.shop.module.entity.PlayClerkGiftInfoEntity;
import com.starry.admin.modules.shop.module.entity.PlayCommodityAndLevelInfoEntity;
import com.starry.admin.modules.shop.module.entity.PlayCommodityInfoEntity;
import com.starry.admin.modules.shop.module.entity.PlayGiftInfoEntity;
import com.starry.admin.modules.shop.service.IPlayClerkGiftInfoService;
import com.starry.admin.modules.shop.service.IPlayCommodityAndLevelInfoService;
import com.starry.admin.modules.shop.service.IPlayCommodityInfoService;
import com.starry.admin.modules.shop.service.IPlayGiftInfoService;
import com.starry.admin.modules.system.module.entity.SysTenantEntity;
import com.starry.admin.modules.system.module.entity.SysTenantPackageEntity;
import com.starry.admin.modules.system.module.entity.SysUserEntity;
import com.starry.admin.modules.system.service.ISysTenantPackageService;
import com.starry.admin.modules.system.service.ISysTenantService;
import com.starry.admin.modules.system.service.SysUserService;
import com.starry.admin.modules.weichat.service.WxTokenService;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.context.CustomSecurityContextHolder;
import com.starry.common.utils.IdUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Profile("apitest")
public class ApiTestDataSeeder implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(ApiTestDataSeeder.class);

    public static final String DEFAULT_PACKAGE_ID = "pkg-basic";
    public static final String DEFAULT_TENANT_ID = "tenant-apitest";
    public static final String DEFAULT_TENANT_KEY = "tenant-key-apitest";
    public static final String DEFAULT_TENANT_NAME = "API Test Tenant";
    public static final String DEFAULT_ADMIN_USER_ID = "user-apitest-admin";
    public static final String DEFAULT_ADMIN_USERNAME = "apitest-admin";
    public static final String DEFAULT_GROUP_ID = "group-basic";
    public static final String DEFAULT_CLERK_LEVEL_ID = "lvl-basic";
    public static final String DEFAULT_CLERK_ID = "clerk-apitest";
    public static final String DEFAULT_CLERK_OPEN_ID = "openid-clerk-apitest";
    public static final String DEFAULT_COMMODITY_PARENT_ID = "svc-parent";
    public static final String DEFAULT_COMMODITY_PARENT_NAME = "语音陪聊服务";
    public static final String DEFAULT_COMMODITY_ID = "svc-basic";
    public static final String DEFAULT_CLERK_COMMODITY_ID = "clerk-svc-basic";
    public static final String DEFAULT_CUSTOMER_ID = "customer-apitest";
    public static final String DEFAULT_GIFT_ID = "gift-basic";
    public static final String DEFAULT_GIFT_NAME = "API测试礼物";
    public static final BigDecimal DEFAULT_COMMODITY_PRICE = new BigDecimal("120.00");
    private static final String GIFT_TYPE_REGULAR = "1";
    private static final String GIFT_STATE_ACTIVE = "0";
    private static final BigDecimal DEFAULT_CUSTOMER_BALANCE = new BigDecimal("200.00");
    private static final BigDecimal DEFAULT_CUSTOMER_RECHARGE = DEFAULT_CUSTOMER_BALANCE;

    private final ISysTenantPackageService tenantPackageService;
    private final ISysTenantService tenantService;
    private final SysUserService sysUserService;
    private final IPlayPersonnelGroupInfoService personnelGroupInfoService;
    private final IPlayClerkLevelInfoService clerkLevelInfoService;
    private final IPlayClerkUserInfoService clerkUserInfoService;
    private final IPlayCommodityInfoService commodityInfoService;
    private final IPlayCommodityAndLevelInfoService commodityAndLevelInfoService;
    private final IPlayGiftInfoService giftInfoService;
    private final IPlayClerkCommodityService clerkCommodityService;
    private final IPlayClerkGiftInfoService playClerkGiftInfoService;
    private final IPlayCustomUserInfoService customUserInfoService;
    private final IPlayCustomGiftInfoService playCustomGiftInfoService;
    private final PlayClerkGiftInfoMapper playClerkGiftInfoMapper;
    private final PlayCustomGiftInfoMapper playCustomGiftInfoMapper;
    private final PasswordEncoder passwordEncoder;
    private final WxTokenService wxTokenService;

    public ApiTestDataSeeder(
            ISysTenantPackageService tenantPackageService,
            ISysTenantService tenantService,
            SysUserService sysUserService,
            IPlayPersonnelGroupInfoService personnelGroupInfoService,
            IPlayClerkLevelInfoService clerkLevelInfoService,
            IPlayClerkUserInfoService clerkUserInfoService,
            IPlayCommodityInfoService commodityInfoService,
            IPlayCommodityAndLevelInfoService commodityAndLevelInfoService,
            IPlayGiftInfoService giftInfoService,
            IPlayClerkCommodityService clerkCommodityService,
            IPlayClerkGiftInfoService playClerkGiftInfoService,
            IPlayCustomUserInfoService customUserInfoService,
            IPlayCustomGiftInfoService playCustomGiftInfoService,
            PlayClerkGiftInfoMapper playClerkGiftInfoMapper,
            PlayCustomGiftInfoMapper playCustomGiftInfoMapper,
            PasswordEncoder passwordEncoder,
            WxTokenService wxTokenService) {
        this.tenantPackageService = tenantPackageService;
        this.tenantService = tenantService;
        this.sysUserService = sysUserService;
        this.personnelGroupInfoService = personnelGroupInfoService;
        this.clerkLevelInfoService = clerkLevelInfoService;
        this.clerkUserInfoService = clerkUserInfoService;
        this.commodityInfoService = commodityInfoService;
        this.commodityAndLevelInfoService = commodityAndLevelInfoService;
        this.giftInfoService = giftInfoService;
        this.clerkCommodityService = clerkCommodityService;
        this.playClerkGiftInfoService = playClerkGiftInfoService;
        this.customUserInfoService = customUserInfoService;
        this.playCustomGiftInfoService = playCustomGiftInfoService;
        this.playClerkGiftInfoMapper = playClerkGiftInfoMapper;
        this.playCustomGiftInfoMapper = playCustomGiftInfoMapper;
        this.passwordEncoder = passwordEncoder;
        this.wxTokenService = wxTokenService;
    }

    @Override
    @Transactional
    public void run(String... args) {
        seedTenantPackage();
        seedTenant();

        String originalTenant = SecurityUtils.getTenantId();
        try {
            SecurityUtils.setTenantId(DEFAULT_TENANT_ID);
            seedAdminUser();
            seedPersonnelGroup();
            seedClerkLevel();
            PlayCommodityInfoEntity commodity = seedCommodityHierarchy();
            seedCommodityPricing(commodity);
            seedClerk();
            seedClerkCommodity();
            seedGift();
            resetGiftCounters();
            seedCustomer();
        } finally {
            if (Objects.nonNull(originalTenant)) {
                SecurityUtils.setTenantId(originalTenant);
            }
            CustomSecurityContextHolder.remove();
        }
    }

    private void seedTenantPackage() {
        long existing = tenantPackageService.count(Wrappers.<SysTenantPackageEntity>lambdaQuery()
                .eq(SysTenantPackageEntity::getPackageId, DEFAULT_PACKAGE_ID));
        if (existing > 0) {
            log.info("API test tenant package {} already exists", DEFAULT_PACKAGE_ID);
            return;
        }

        SysTenantPackageEntity entity = new SysTenantPackageEntity();
        entity.setPackageId(DEFAULT_PACKAGE_ID);
        entity.setPackageName("API测试基础套餐");
        entity.setStatus("0");
        entity.setMenuIds("[]");
        entity.setRemarks("Seeded for API integration tests");
        tenantPackageService.save(entity);
        log.info("Inserted API test tenant package {}", DEFAULT_PACKAGE_ID);
    }

    private void seedTenant() {
        SysTenantEntity tenant = tenantService.getById(DEFAULT_TENANT_ID);
        if (tenant != null) {
            log.info("API test tenant {} already exists", DEFAULT_TENANT_ID);
            return;
        }

        SysTenantEntity entity = new SysTenantEntity();
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setTenantName(DEFAULT_TENANT_NAME);
        entity.setTenantType("0");
        entity.setTenantStatus("0");
        entity.setTenantCode("apitest");
        entity.setTenantKey(DEFAULT_TENANT_KEY);
        entity.setPackageId(DEFAULT_PACKAGE_ID);
        entity.setTenantTime(new Date(System.currentTimeMillis() + 365L * 24 * 3600 * 1000));
        entity.setUserName(DEFAULT_ADMIN_USERNAME);
        entity.setUserPwd(passwordEncoder.encode("apitest-secret"));
        entity.setPhone("13800000000");
        entity.setEmail("apitest@example.com");
        entity.setAddress("API Test Street 1");
        tenantService.save(entity);
        log.info("Inserted API test tenant {}", DEFAULT_TENANT_ID);
    }

    private void seedAdminUser() {
        SysUserEntity existing = sysUserService.getById(DEFAULT_ADMIN_USER_ID);
        if (existing != null) {
            log.info("API test admin user {} already exists", DEFAULT_ADMIN_USER_ID);
            return;
        }

        SysUserEntity admin = new SysUserEntity();
        admin.setUserId(DEFAULT_ADMIN_USER_ID);
        admin.setUserCode(DEFAULT_ADMIN_USERNAME);
        admin.setPassWord(passwordEncoder.encode("apitest-secret"));
        admin.setRealName("API Test Admin");
        admin.setUserNickname("API Admin");
        admin.setStatus(0);
        admin.setUserType(1);
        admin.setTenantId(DEFAULT_TENANT_ID);
        admin.setMobile("13800000000");
        admin.setAddTime(LocalDateTime.now());
        admin.setSuperAdmin(Boolean.TRUE);
        sysUserService.save(admin);
        log.info("Inserted API test admin user {}", DEFAULT_ADMIN_USER_ID);
    }

    private void seedPersonnelGroup() {
        PlayPersonnelGroupInfoEntity group = personnelGroupInfoService.getById(DEFAULT_GROUP_ID);
        if (group != null) {
            log.info("API test personnel group {} already exists", DEFAULT_GROUP_ID);
            return;
        }

        PlayPersonnelGroupInfoEntity entity = new PlayPersonnelGroupInfoEntity();
        entity.setId(DEFAULT_GROUP_ID);
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setSysUserId(DEFAULT_ADMIN_USER_ID);
        entity.setSysUserCode(DEFAULT_ADMIN_USERNAME);
        entity.setGroupName("测试小组");
        entity.setLeaderName("API Admin");
        entity.setAddTime(LocalDateTime.now());
        personnelGroupInfoService.save(entity);
        log.info("Inserted API test personnel group {}", DEFAULT_GROUP_ID);
    }

    private void seedClerkLevel() {
        PlayClerkLevelInfoEntity level = clerkLevelInfoService.getById(DEFAULT_CLERK_LEVEL_ID);
        if (level != null) {
            log.info("API test clerk level {} already exists", DEFAULT_CLERK_LEVEL_ID);
            return;
        }

        PlayClerkLevelInfoEntity entity = new PlayClerkLevelInfoEntity();
        entity.setId(DEFAULT_CLERK_LEVEL_ID);
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setName("基础等级");
        entity.setLevel(1);
        entity.setFirstRegularRatio(60);
        entity.setNotFirstRegularRatio(50);
        entity.setFirstRandomRadio(55);
        entity.setNotFirstRandomRadio(45);
        entity.setFirstRewardRatio(40);
        entity.setNotFirstRewardRatio(35);
        entity.setOrderNumber(1L);
        clerkLevelInfoService.save(entity);
        log.info("Inserted API test clerk level {}", DEFAULT_CLERK_LEVEL_ID);
    }

    private PlayCommodityInfoEntity seedCommodityHierarchy() {
        PlayCommodityInfoEntity parent = commodityInfoService.getById(DEFAULT_COMMODITY_PARENT_ID);
        if (parent == null) {
            parent = new PlayCommodityInfoEntity();
            parent.setId(DEFAULT_COMMODITY_PARENT_ID);
            parent.setTenantId(DEFAULT_TENANT_ID);
            parent.setPId("00");
            parent.setItemType("service-category");
            parent.setItemName(DEFAULT_COMMODITY_PARENT_NAME);
            parent.setEnableStace("1");
            parent.setSort(1);
            commodityInfoService.save(parent);
            log.info("Inserted API test commodity parent {}", DEFAULT_COMMODITY_PARENT_ID);
        } else {
            boolean parentNeedsUpdate = false;
            if (!"00".equals(parent.getPId())) {
                parent.setPId("00");
                parentNeedsUpdate = true;
            }
            if (!"service-category".equals(parent.getItemType())) {
                parent.setItemType("service-category");
                parentNeedsUpdate = true;
            }
            if (!DEFAULT_TENANT_ID.equals(parent.getTenantId())) {
                parent.setTenantId(DEFAULT_TENANT_ID);
                parentNeedsUpdate = true;
            }
            if (!"1".equals(parent.getEnableStace())) {
                parent.setEnableStace("1");
                parentNeedsUpdate = true;
            }
            if (parentNeedsUpdate) {
                commodityInfoService.updateById(parent);
                log.info("Normalized API test commodity parent {}", DEFAULT_COMMODITY_PARENT_ID);
            }
        }

        PlayCommodityInfoEntity child = commodityInfoService.getById(DEFAULT_COMMODITY_ID);
        if (child != null) {
            boolean childNeedsUpdate = false;
            if (!DEFAULT_COMMODITY_PARENT_ID.equals(child.getPId())) {
                child.setPId(DEFAULT_COMMODITY_PARENT_ID);
                childNeedsUpdate = true;
            }
            if (!"service".equals(child.getItemType())) {
                child.setItemType("service");
                childNeedsUpdate = true;
            }
            if (!DEFAULT_TENANT_ID.equals(child.getTenantId())) {
                child.setTenantId(DEFAULT_TENANT_ID);
                childNeedsUpdate = true;
            }
            if (!"1".equals(child.getEnableStace())) {
                child.setEnableStace("1");
                childNeedsUpdate = true;
            }
            if (childNeedsUpdate) {
                commodityInfoService.updateById(child);
                log.info("Normalized API test commodity {}", DEFAULT_COMMODITY_ID);
            }
            log.info("API test commodity {} already exists", DEFAULT_COMMODITY_ID);
            return child;
        }

        child = new PlayCommodityInfoEntity();
        child.setId(DEFAULT_COMMODITY_ID);
        child.setTenantId(DEFAULT_TENANT_ID);
        child.setPId(DEFAULT_COMMODITY_PARENT_ID);
        child.setItemType("service");
        child.setItemName("60分钟语音陪聊");
        child.setServiceDuration("60min");
        child.setEnableStace("1");
        child.setSort(1);
        commodityInfoService.save(child);
        log.info("Inserted API test commodity {}", DEFAULT_COMMODITY_ID);
        return child;
    }

    private void seedCommodityPricing(PlayCommodityInfoEntity commodity) {
        if (commodity == null) {
            return;
        }
        PlayCommodityAndLevelInfoEntity existing = commodityAndLevelInfoService.lambdaQuery()
                .eq(PlayCommodityAndLevelInfoEntity::getCommodityId, commodity.getId())
                .eq(PlayCommodityAndLevelInfoEntity::getLevelId, DEFAULT_CLERK_LEVEL_ID)
                .one();
        if (existing != null) {
            log.info("API test commodity pricing for {} already exists", commodity.getId());
            return;
        }

        PlayCommodityAndLevelInfoEntity price = new PlayCommodityAndLevelInfoEntity();
        price.setId(IdUtils.getUuid());
        price.setTenantId(DEFAULT_TENANT_ID);
        price.setCommodityId(commodity.getId());
        price.setLevelId(DEFAULT_CLERK_LEVEL_ID);
        price.setPrice(DEFAULT_COMMODITY_PRICE);
        price.setSort(1L);
        commodityAndLevelInfoService.save(price);
        log.info("Inserted API test commodity pricing for {}", commodity.getId());
    }

    private void seedClerk() {
        PlayClerkUserInfoEntity clerk = clerkUserInfoService.getById(DEFAULT_CLERK_ID);
        String clerkToken = wxTokenService.createWxUserToken(DEFAULT_CLERK_ID);
        if (clerk != null) {
            clerkUserInfoService.updateTokenById(DEFAULT_CLERK_ID, clerkToken);
            log.info("API test clerk {} already exists", DEFAULT_CLERK_ID);
            return;
        }

        PlayClerkUserInfoEntity entity = new PlayClerkUserInfoEntity();
        entity.setId(DEFAULT_CLERK_ID);
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setSysUserId(DEFAULT_ADMIN_USER_ID);
        entity.setOpenid(DEFAULT_CLERK_OPEN_ID);
        entity.setNickname("小测官");
        entity.setGroupId(DEFAULT_GROUP_ID);
        entity.setLevelId(DEFAULT_CLERK_LEVEL_ID);
        entity.setFixingLevel("1");
        entity.setSex("2");
        entity.setPhone("13900000001");
        entity.setWeiChatCode("apitest-clerk");
        entity.setAvatar("https://example.com/avatar.png");
        entity.setAccountBalance(BigDecimal.ZERO);
        entity.setOnboardingState("1");
        entity.setListingState("1");
        entity.setDisplayState("1");
        entity.setOnlineState("1");
        entity.setRandomOrderState("1");
        entity.setClerkState("1");
        entity.setEntryTime(LocalDateTime.now());
        entity.setToken(clerkToken);
        clerkUserInfoService.save(entity);
        log.info("Inserted API test clerk {}", DEFAULT_CLERK_ID);
    }

    private void seedClerkCommodity() {
        PlayClerkCommodityEntity mapping = clerkCommodityService.getById(DEFAULT_CLERK_COMMODITY_ID);
        if (mapping != null) {
            log.info("API test clerk commodity {} already exists", DEFAULT_CLERK_COMMODITY_ID);
            return;
        }

        String commodityName = DEFAULT_COMMODITY_PARENT_NAME;
        PlayCommodityInfoEntity parent = commodityInfoService.getById(DEFAULT_COMMODITY_PARENT_ID);
        if (parent != null && parent.getItemName() != null) {
            commodityName = parent.getItemName();
        }

        PlayClerkCommodityEntity entity = new PlayClerkCommodityEntity();
        entity.setId(DEFAULT_CLERK_COMMODITY_ID);
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setClerkId(DEFAULT_CLERK_ID);
        entity.setCommodityId(DEFAULT_COMMODITY_ID);
        entity.setCommodityName(commodityName);
        entity.setEnablingState("1");
        entity.setSort(1);
        clerkCommodityService.save(entity);
        log.info("Inserted API test clerk commodity link {}", DEFAULT_CLERK_COMMODITY_ID);
    }

    private void seedGift() {
        PlayGiftInfoEntity gift = giftInfoService.getById(DEFAULT_GIFT_ID);
        if (gift != null) {
            log.info("API test gift {} already exists", DEFAULT_GIFT_ID);
            return;
        }

        PlayGiftInfoEntity entity = new PlayGiftInfoEntity();
        entity.setId(DEFAULT_GIFT_ID);
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setHistory("0");
        entity.setName(DEFAULT_GIFT_NAME);
        entity.setType(GIFT_TYPE_REGULAR);
        entity.setUrl("https://example.com/apitest/gift.png");
        entity.setPrice(new BigDecimal("15.00"));
        entity.setUnit("CNY");
        entity.setState(GIFT_STATE_ACTIVE);
        entity.setListingTime(LocalDateTime.now());
        entity.setRemark("Seeded gift for API tests");
        giftInfoService.save(entity);
        log.info("Inserted API test gift {}", DEFAULT_GIFT_ID);
    }

    private void resetGiftCounters() {
        int customerReset = playCustomGiftInfoMapper.resetGiftCount(DEFAULT_TENANT_ID, DEFAULT_CUSTOMER_ID, DEFAULT_GIFT_ID);
        if (customerReset == 0) {
            PlayCustomGiftInfoEntity entity = new PlayCustomGiftInfoEntity();
            entity.setId(IdUtils.getUuid());
            entity.setTenantId(DEFAULT_TENANT_ID);
            entity.setCustomId(DEFAULT_CUSTOMER_ID);
            entity.setGiffId(DEFAULT_GIFT_ID);
            entity.setGiffNumber(0L);
            try {
                playCustomGiftInfoService.save(entity);
            } catch (org.springframework.dao.DuplicateKeyException duplicateKeyException) {
                playCustomGiftInfoMapper.resetGiftCount(DEFAULT_TENANT_ID, DEFAULT_CUSTOMER_ID, DEFAULT_GIFT_ID);
            }
        }

        int clerkReset = playClerkGiftInfoMapper.resetGiftCount(DEFAULT_TENANT_ID, DEFAULT_CLERK_ID, DEFAULT_GIFT_ID);
        if (clerkReset == 0) {
            PlayClerkGiftInfoEntity entity = new PlayClerkGiftInfoEntity();
            entity.setId(IdUtils.getUuid());
            entity.setTenantId(DEFAULT_TENANT_ID);
            entity.setClerkId(DEFAULT_CLERK_ID);
            entity.setGiffId(DEFAULT_GIFT_ID);
            entity.setGiffNumber(0L);
            try {
                playClerkGiftInfoService.save(entity);
            } catch (org.springframework.dao.DuplicateKeyException duplicateKeyException) {
                playClerkGiftInfoMapper.resetGiftCount(DEFAULT_TENANT_ID, DEFAULT_CLERK_ID, DEFAULT_GIFT_ID);
            }
        }
    }

    private void seedCustomer() {
        PlayCustomUserInfoEntity customer = customUserInfoService.getById(DEFAULT_CUSTOMER_ID);
        String token = wxTokenService.createWxUserToken(DEFAULT_CUSTOMER_ID);
        if (customer != null) {
            customUserInfoService.updateTokenById(DEFAULT_CUSTOMER_ID, token);
            customUserInfoService.lambdaUpdate()
                    .set(PlayCustomUserInfoEntity::getAccountBalance, DEFAULT_CUSTOMER_BALANCE)
                    .set(PlayCustomUserInfoEntity::getAccumulatedRechargeAmount, DEFAULT_CUSTOMER_RECHARGE)
                    .set(PlayCustomUserInfoEntity::getAccumulatedConsumptionAmount, BigDecimal.ZERO)
                    .set(PlayCustomUserInfoEntity::getAccountState, "1")
                    .set(PlayCustomUserInfoEntity::getSubscribeState, "1")
                    .set(PlayCustomUserInfoEntity::getPurchaseState, "1")
                    .set(PlayCustomUserInfoEntity::getMobilePhoneState, "1")
                    .set(PlayCustomUserInfoEntity::getLastLoginTime, new Date())
                    .eq(PlayCustomUserInfoEntity::getId, DEFAULT_CUSTOMER_ID)
                    .update();
            log.info("API test customer {} already exists, state refreshed", DEFAULT_CUSTOMER_ID);
            return;
        }

        PlayCustomUserInfoEntity entity = new PlayCustomUserInfoEntity();
        entity.setId(DEFAULT_CUSTOMER_ID);
        entity.setTenantId(DEFAULT_TENANT_ID);
        entity.setOpenid("openid-customer-apitest");
        entity.setUnionid("unionid-customer-apitest");
        entity.setNickname("测试顾客");
        entity.setSex(1);
        entity.setPhone("13700000002");
        entity.setWeiChatCode("apitest-customer");
        entity.setAccountBalance(DEFAULT_CUSTOMER_BALANCE);
        entity.setAccumulatedRechargeAmount(DEFAULT_CUSTOMER_RECHARGE);
        entity.setAccumulatedConsumptionAmount(BigDecimal.ZERO);
        entity.setAccountState("1");
        entity.setSubscribeState("1");
        entity.setPurchaseState("1");
        entity.setMobilePhoneState("1");
        entity.setRegistrationTime(new Date());
        entity.setLastLoginTime(new Date());
        entity.setToken(token);
        customUserInfoService.save(entity);
        log.info("Inserted API test customer {}", DEFAULT_CUSTOMER_ID);
    }
}
