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.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.PayInterfaceDefineMapper;
import com.jeequan.jeepay.service.mapper.ProductAppMapper;
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.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 ProductAppMapper productAppMapper;
    @Autowired private PackageInfoMapper packageInfoMapper;
    @Autowired private PayInterfaceDefineMapper payInterfaceDefineMapper;

    //产品中心列表
    @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);
    }

    //产品详情
    @Transactional(rollbackFor = Exception.class)
    public ProductInfo getProductById(String productId) {
        ProductInfo resultInfo = productInfoMapper.getProductById(productId);
        List<ProductInfo> productInfoList=new ArrayList<>();
        List<PackageInfo> packageInfoList=new ArrayList<>();
        List<PayInterfaceDefine> payInterfaceDefineList=new ArrayList<>();
        if (StringUtils.isNotEmpty(resultInfo.getProductIds())){
            //关联产品不为空，组装关联的产品信息
            String[] productIdSplit = resultInfo.getProductIds().split(",");
            for (String id : productIdSplit) {
                ProductInfo productInfo = productInfoMapper.selectById(id);
                if (productInfo != null){
                    ProductInfo productInfoModel =new ProductInfo();
                    productInfoModel.setProductId(productInfo.getProductId());
                    productInfoModel.setProductName(productInfo.getProductName());
                    productInfoModel.setProductUrl(productInfo.getProductUrl());
                    productInfoList.add(productInfoModel);
                }
            }
        }
        if (StringUtils.isNotEmpty(resultInfo.getPackageIds())){
            //关联方案不为空，组装关联的方案信息
            String[] packageIdSplit = resultInfo.getPackageIds().split(",");
            for (String id : packageIdSplit) {
                PackageInfo packageInfo = packageInfoMapper.selectById(id);
                if (packageInfo != null){
                    PackageInfo packageInfoModel =new PackageInfo();
                    packageInfoModel.setPackageId(packageInfo.getPackageId());
                    packageInfoModel.setName(packageInfo.getName());
                    packageInfoModel.setPackageUrl(packageInfo.getPackageUrl());
                    packageInfoList.add(packageInfoModel);
                }
            }
        }
        if (StringUtils.isNotEmpty(resultInfo.getPayInterfaceCodes())){
            //关联通道配置不为空，组装关联的通道配置信息
            String[] codeSplit = resultInfo.getPayInterfaceCodes().split(",");
            for (String code : codeSplit) {
                PayInterfaceDefine payInterfaceDefine = payInterfaceDefineMapper.selectById(code);
                if (payInterfaceDefine !=null){
                    PayInterfaceDefine payInterfaceDefineModel =new PayInterfaceDefine();
                    payInterfaceDefineModel.setIfCode(payInterfaceDefine.getIfCode());
                    payInterfaceDefineModel.setIfName(payInterfaceDefine.getIfName());
                    payInterfaceDefineList.add(payInterfaceDefineModel);
                }
            }
        }
        resultInfo.setProductInfoRelevancyList(productInfoList);
        resultInfo.setPackageInfoRelevancyList(packageInfoList);
        resultInfo.setPayInterRelevancyList(payInterfaceDefineList);

        return resultInfo;
    }

    //回显产品详情
    @Transactional(rollbackFor = Exception.class)
    public ProductInfo getDetailById(String productId) {
        ProductInfo productInfoById = productInfoMapper.getDetailById(productId);
        StringBuilder productIdsName= new StringBuilder();
        StringBuilder packageIdsName=new StringBuilder();
        StringBuilder payInterfaceCodesName=new StringBuilder();
        if (StringUtils.isNotEmpty(productInfoById.getProductIds())){
            //关联产品不为空，组装关联的产品信息
            String[] productIdSplit = productInfoById.getProductIds().split(",");
            for (String id : productIdSplit) {
                ProductInfo productInfo = productInfoMapper.selectById(id);
                if (productInfo != null){
                    productIdsName.append(productInfo.getProductName()).append(",");
                }
            }
            productInfoById.setProductIdsName(String.valueOf(productIdsName));
        }
        if (StringUtils.isNotEmpty(productInfoById.getPackageIds())){
            //关联方案不为空，组装关联的方案信息
            String[] packageIdSplit = productInfoById.getPackageIds().split(",");
            for (String id : packageIdSplit) {
                PackageInfo packageInfo = packageInfoMapper.selectById(id);
                if (packageInfo != null){
                    packageIdsName.append(packageInfo.getName()).append(",");
                }
            }
            productInfoById.setPackageIdsName(String.valueOf(packageIdsName));
        }
        if (StringUtils.isNotEmpty(productInfoById.getPayInterfaceCodes())){
            //关联通道配置不为空，组装关联的通道配置信息
            String[] codeSplit = productInfoById.getPayInterfaceCodes().split(",");
            for (String code : codeSplit) {
                PayInterfaceDefine payInterfaceDefine = payInterfaceDefineMapper.selectById(code);
                if (payInterfaceDefine != null){
                    payInterfaceCodesName.append(payInterfaceDefine.getIfName()).append(",");
                }
            }
            productInfoById.setPayInterfaceCodesName(String.valueOf(payInterfaceCodesName));
        }

        return productInfoById;
    }

    //审核列表
    @Transactional(rollbackFor = Exception.class)
    public IPage<ProductInfo> getProductCheckList(Page page, String productName,Integer state) {
        return productInfoMapper.getProductCheckList(page,productName,state);
    }

    //审核
    @Transactional(rollbackFor = Exception.class)
    public void checkProduct(PackageOrder app) {
        //如果是审核通过则添加审核时间
        if (app.getState().equals(3)){
            PackageOrder detail = productAppMapper.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
        productAppMapper.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_ON_AUDIT.equals(productInfo.getAudit())){
                app.setState(3);
                //不用审核则默认给审核通过时间
                for (Object object : costRule) {
                    JSONObject costRuleData =(JSONObject)object;
                    costRuleData.put("autoTime",new Date());
                }
            }else {
                app.setState(1);//1-审核中
            }
        }else if (StringUtils.isNotEmpty(app.getPackageId())){
            PackageInfo packageInfo = packageInfoMapper.selectById(app.getPackageId());
            if (PackageInfo.PACKAGE_STATE_ON_AUDIT.equals(packageInfo.getAudit())){
                app.setState(3);
                //不用审核则默认给审核通过时间
                for (Object object : costRule) {
                    JSONObject costRuleData =(JSONObject)object;
                    costRuleData.put("autoTime",new Date());
                }
            }else {
                app.setState(1);//1-审核中
            }
        }else {
            throw new BizException("产品id或者方案id不能为空！");
        }
        //随机生成id
        app.setId(DateUtil.format(new Date(), "yyMMdd")+ RandomUtil.randomNumbers(6));
        productAppMapper.insert(app);

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

}
