package com.izouma.jiashanxia.service;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.jiashanxia.domain.*;
import com.izouma.jiashanxia.domain.Package;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.AuthorityName;
import com.izouma.jiashanxia.enums.OrderInfoStatus;
import com.izouma.jiashanxia.enums.PayMethod;
import com.izouma.jiashanxia.enums.PackageType;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.*;
import com.izouma.jiashanxia.security.Authority;
import com.izouma.jiashanxia.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;


@Service
@AllArgsConstructor
public class PackageService {

    private PackageRepo        packageRepo;
    private PackageGoodsRepo   packageGoodsRepo;
    private UserPackageService userPackageService;
    private CompanyRepo        companyRepo;
    private UserRepo           userRepo;
    private OrderInfoRepo      orderInfoRepo;

    public Page<Package> all(PageQuery pageQuery) {
        return packageRepo.findAll(JpaUtils.toSpecification(pageQuery, Package.class), JpaUtils.toPageRequest(pageQuery));
    }

    /*
    开通团队套餐
     */
    public void openTeamSet(Long userId, Long packageId) {

        Package set = packageRepo.findById(packageId).orElseThrow(new BusinessException("无套餐"));
        if (!PackageType.TEAM.equals(set.getType())) {
            throw new BusinessException("不是团队套餐");
        }
        // 新建订单
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String localTime = df.format(LocalDateTime.now());
        String num = String.format("%05d", orderInfoRepo.orderNum() + 1);
        orderInfoRepo.save(OrderInfo.builder()
                .packageId(packageId)
                .userId(userId)
                .payMethod(PayMethod.OFFLINE)
                .name(set.getName())
                .orderNumber(localTime + num)
                .num(1)
                .status(OrderInfoStatus.OFFLINE_PAID)
                .build());

        // 用户
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("无用户"));
        // 加入套餐商品
        List<PackageGoods> setGoodsList = packageGoodsRepo.findAllByPackageId(packageId);
        userPackageService.joinUserPackage(userId, setGoodsList, 1);

        // 新建公司
        Company company = companyRepo.findByUserId(userId);
        if (ObjectUtil.isEmpty(company)) {
            company = companyRepo.save(Company.builder()
                    .userId(userId)
                    .name("企业")
                    .amount(BigDecimal.ZERO)
                    .build());
        }

        // 团队创始人
        Set<Authority> authorities = user.getAuthorities();
        if (!authorities.contains(Authority.get(AuthorityName.ROLE_CREATOR))) {
            user.setCompanyId(company.getId());
            user.setTeamFounder(true);
            authorities.add(Authority.get(AuthorityName.ROLE_CREATOR));
            user.setAuthorities(authorities);
            user.setVip(true);
            userRepo.save(user);
        }
    }

    /*
    充值
    冲谁头上
     */
    public void recharge(Long userId, Long packageId, Integer num) {
        Package set = packageRepo.findById(packageId).orElseThrow(new BusinessException("无套餐"));
        if (!PackageType.TEAM.equals(set.getType())) {
            throw new BusinessException("不是团队套餐");
        }
        // 新建订单
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String localTime = df.format(LocalDateTime.now());
        String orderNumber = String.format("%05d", orderInfoRepo.orderNum() + 1);
        orderInfoRepo.save(OrderInfo.builder()
                .packageId(packageId)
                .userId(userId)
                .payMethod(PayMethod.OFFLINE)
                .name(set.getName())
                .orderNumber(localTime + orderNumber)
                .status(OrderInfoStatus.OFFLINE_PAID)
                .num(num)
                .build());

        // 加入套餐商品
        List<PackageGoods> setGoodsList = packageGoodsRepo.findAllByPackageId(packageId);
        userPackageService.joinUserPackage(userId, setGoodsList, num);
    }

}
