package com.jeequan.jeepay.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.PackageInfo;
import com.jeequan.jeepay.db.entity.PackageOrder;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.db.entity.ProductInfo;
import com.jeequan.jeepay.service.mapper.PackageInfoMapper;
import com.jeequan.jeepay.service.mapper.PackageOrderMapper;
import com.jeequan.jeepay.service.mapper.PayInterfaceDefineMapper;
import com.jeequan.jeepay.service.mapper.ProductInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 产品信息表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2022-03-12
 */
@Service
public class ProductInfoService extends ServiceImpl<ProductInfoMapper, ProductInfo> {

    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private PackageOrderMapper packageOrderMapper;

    @Autowired
    private PackageInfoMapper packageInfoMapper;
    @Autowired
    private PayInterfaceDefineMapper payInterfaceDefineMapper;


    public List<ProductInfo> list(String apiCode) {
        return lambdaQuery().eq(ProductInfo::getApiCode, apiCode).list();
    }

    //产品中心列表
    @Transactional(rollbackFor = Exception.class)
    public List<ProductInfo> getProductList(String productName, Integer state, Integer productType) {
        return productInfoMapper.getProductList(productName, state, productType);
    }

    //删除产品
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(String productId) {
        // 当前产品是否存在
        ProductInfo productInfo = getById(productId);
        if (productInfo == null) {
            throw new BizException("该产品不存在");
        }
        productInfo = new ProductInfo();
        productInfo.setProductState(2);//2-已删除
        productInfo.setUpdatedAt(new Date());
        productInfo.setProductId(productId);
        productInfoMapper.updateById(productInfo);
    }

    //回显产品详情
    public ProductInfo getDetailById(String productId) {
        ProductInfo resultInfo = productInfoMapper.getDetailById(productId);
        List<ProductInfo> productInfoList = new ArrayList<>();
        List<PackageInfo> packageInfoList = new ArrayList<>();
        List<PayInterfaceDefine> payInterfaceDefineList = new ArrayList<>();
        StringBuilder productIdsName = new StringBuilder();
        StringBuilder packageIdsName = new StringBuilder();
        StringBuilder payInterfaceCodesName = new StringBuilder();

        outerProduct:
        if (StringUtils.isNotEmpty(resultInfo.getProductIds())) {
            // 关联产品不为空，组装关联的产品信息
            String[] productIdSplit = resultInfo.getProductIds().split(",");
            if (productIdSplit.length == 0) break outerProduct;
            List<String> productIds = Arrays.asList(productIdSplit);

            // 使用 LambdaQueryWrapper 进行查询
            LambdaQueryWrapper<ProductInfo> productQueryWrapper = Wrappers.lambdaQuery(ProductInfo.class)
                    .in(ProductInfo::getProductId, productIds);
            List<ProductInfo> associatedProducts = productInfoMapper.selectList(productQueryWrapper);

            for (ProductInfo productInfo : associatedProducts) {
                ProductInfo productInfoModel = new ProductInfo();
                productInfoModel.setProductId(productInfo.getProductId());
                productInfoModel.setProductName(productInfo.getProductName());
                productInfoModel.setProductUrl(productInfo.getProductUrl());
                productInfoList.add(productInfoModel);
                productIdsName.append(productInfo.getProductName()).append(",");
            }
            resultInfo.setProductIdsName(productIdsName.toString());
        }

        outerPackage:
        if (StringUtils.isNotEmpty(resultInfo.getPackageIds())) {
            // 关联方案不为空，组装关联的方案信息
            String[] packageIdSplit = resultInfo.getPackageIds().split(",");
            if (packageIdSplit.length == 0) break outerPackage;
            List<String> packageIds = Arrays.asList(packageIdSplit);

            // 使用 LambdaQueryWrapper 进行查询
            LambdaQueryWrapper<PackageInfo> packageQueryWrapper = Wrappers.lambdaQuery(PackageInfo.class)
                    .in(PackageInfo::getPackageId, packageIds);
            List<PackageInfo> associatedPackages = packageInfoMapper.selectList(packageQueryWrapper);

            for (PackageInfo packageInfo : associatedPackages) {
                PackageInfo packageInfoModel = new PackageInfo();
                packageInfoModel.setPackageId(packageInfo.getPackageId());
                packageInfoModel.setName(packageInfo.getName());
                packageInfoModel.setPackageUrl(packageInfo.getPackageUrl());
                packageInfoList.add(packageInfoModel);
                packageIdsName.append(packageInfo.getName()).append(",");
            }
            resultInfo.setPackageIdsName(packageIdsName.toString());
        }

        outerPayInterface:
        if (StringUtils.isNotEmpty(resultInfo.getPayInterfaceCodes())) {
            // 关联通道配置不为空，组装关联的通道配置信息
            String[] codeSplit = resultInfo.getPayInterfaceCodes().split(",");
            if (codeSplit.length == 0) break outerPayInterface;
            List<String> payInterfaceCodes = Arrays.asList(codeSplit);

            // 使用 LambdaQueryWrapper 进行查询
            LambdaQueryWrapper<PayInterfaceDefine> payInterfaceQueryWrapper = Wrappers.lambdaQuery(PayInterfaceDefine.class)
                    .in(PayInterfaceDefine::getIfCode, payInterfaceCodes);
            List<PayInterfaceDefine> associatedPayInterfaces = payInterfaceDefineMapper.selectList(payInterfaceQueryWrapper);

            for (PayInterfaceDefine payInterfaceDefine : associatedPayInterfaces) {
                PayInterfaceDefine payInterfaceDefineModel = new PayInterfaceDefine();
                payInterfaceDefineModel.setIfCode(payInterfaceDefine.getIfCode());
                payInterfaceDefineModel.setIfName(payInterfaceDefine.getIfName());
                payInterfaceDefineList.add(payInterfaceDefineModel);
                payInterfaceCodesName.append(payInterfaceDefine.getIfName()).append(",");
            }
            resultInfo.setPayInterfaceCodesName(payInterfaceCodesName.toString());
        }

        resultInfo.setProductInfoRelevancyList(productInfoList);
        resultInfo.setPackageInfoRelevancyList(packageInfoList);
        resultInfo.setPayInterRelevancyList(payInterfaceDefineList);

        return resultInfo;
    }

    //审核
    @Transactional(rollbackFor = Exception.class)
    public void checkProduct(PackageOrder app) {
        //如果是审核通过则添加审核时间
        if (PackageOrder.STATE_SUCCESS.equals(app.getState())) {
            PackageOrder detail = packageOrderMapper.getDetail(app.getId());
            if (detail.getCostRule() != null) {
                JSONObject costRule = (JSONObject) detail.getCostRule().get(0);
                costRule.put("autoTime", new Date());
                app.setCostRule(detail.getCostRule());
            }
        }
        if (app.getPracPrice() == null) {
            app.setPracPrice(BigDecimal.valueOf(0));
        }
        LambdaUpdateWrapper<PackageOrder> update = new LambdaUpdateWrapper<>();
        update.eq(PackageOrder::getId, app.getId());//传入审核id
        packageOrderMapper.update(app, update);
    }

    //产品开通
    @Transactional(rollbackFor = Exception.class)
    public void startProduct(PackageOrder app) {
        JSONArray costRule = app.getCostRule();
        //先判断是否需要审核
        if (StringUtils.isNotEmpty(app.getProductId())) {
            ProductInfo productInfo = productInfoMapper.selectById(app.getProductId());
            if (ProductInfo.PRODUCT_STATE_AUTO_AUDIT.equals(productInfo.getAudit())) {
                app.setState(PackageOrder.STATE_SUCCESS);
                //不用审核则默认给审核通过时间
                for (Object object : costRule) {
                    JSONObject costRuleData = (JSONObject) object;
                    costRuleData.put("autoTime", new Date());
                }
            } else {
                app.setState(PackageOrder.STATE_AUDITING);//1-审核中
            }
        } else if (StringUtils.isNotEmpty(app.getPackageId())) {
            PackageInfo packageInfo = packageInfoMapper.selectById(app.getPackageId());
            if (PackageInfo.PACKAGE_STATE_AUTO_AUDIT.equals(packageInfo.getAudit())) {
                app.setState(PackageOrder.STATE_SUCCESS);
                //不用审核则默认给审核通过时间
                for (Object object : costRule) {
                    JSONObject costRuleData = (JSONObject) object;
                    costRuleData.put("autoTime", new Date());
                }
            } else {
                app.setState(PackageOrder.STATE_AUDITING);//1-审核中
            }
        } else {
            throw new BizException("产品id或者方案id不能为空！");
        }
        //随机生成id
        app.setId(DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        packageOrderMapper.insert(app);
    }

    public Page<ProductInfo> getMgrProductList(Page<ProductInfo> page, ProductInfo productInfo) {
        return productInfoMapper.getMgrProductList(page, productInfo);
    }

}
