package org.dromara.payment.merchant.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.service.BaseService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.channel.domain.vo.BusChannelProductVo;
import org.dromara.payment.channel.mapper.BusChannelProductMapper;
import org.dromara.payment.merchant.domain.BusMerchant;
import org.dromara.payment.merchant.mapper.BusMerchantMapper;
import org.dromara.payment.sys.domain.SysSyd;
import org.dromara.payment.sys.mapper.SysSydMapper;
import org.dromara.payment.thirdPlatform.base.domain.SysThirdPlatform;
import org.dromara.payment.thirdPlatform.base.mapper.SysThirdPlatformMapper;
import org.dromara.payment.thirdPlatform.xinyujian.service.IXyjService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.dromara.payment.merchant.domain.bo.BusMerchantProductBo;
import org.dromara.payment.merchant.domain.vo.BusMerchantProductVo;
import org.dromara.payment.merchant.domain.BusMerchantProduct;
import org.dromara.payment.merchant.mapper.BusMerchantProductMapper;
import org.dromara.payment.merchant.service.IBusMerchantProductService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 商户产品表Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class BusMerchantProductServiceImpl extends BaseService implements IBusMerchantProductService {

    private static final Logger log = LoggerFactory.getLogger(BusMerchantProductServiceImpl.class);
    private final BusMerchantProductMapper baseMapper;

    private final BusChannelProductMapper busChannelProductMapper;

    private final BusMerchantMapper busMerchantMapper;

    private final IXyjService  xyjService;

    private final SysSydMapper sydMapper;

    private final SysThirdPlatformMapper thirdPlatformMapper;

    /**
     * 查询商户产品表
     */
    @Override
    public BusMerchantProductVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询商户产品表列表
     */
    @Override
    public TableDataInfo<BusMerchantProductVo> queryPageList(BusMerchantProductBo bo, PageQuery pageQuery) {

        if(bo.getBusType() == null){
            this.invalidationParamsException("业务类型不能为空");
        }

        if(bo.getMerId() == null){
            this.invalidationParamsException("企业ID不能为空");
        }


        QueryWrapper<BusMerchantProduct> lqw = Wrappers.query();
        lqw.eq("t1.bus_type",bo.getBusType());
        lqw.eq("t.mer_id",bo.getMerId());
        lqw.eq("t3.pro_status",1);
        lqw.eq("t1.pro_status",1);
        if(!LoginHelper.isSuperAdmin()){
            lqw.eq("t1.channel_id",LoginHelper.getBusId());
        }



        Page<BusMerchantProductVo> result = baseMapper.selBusMerProByTypeList(pageQuery.build(), lqw);
        result.getRecords().forEach(item->{
            item.setUnId(IdUtil.getSnowflakeNextId()+"");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询商户产品表列表
     */
    @Override
    public List<BusMerchantProductVo> queryList(BusMerchantProductBo bo) {
        QueryWrapper<BusMerchantProduct> lqw = Wrappers.query();
        lqw.eq("t.pro_status",1);
        lqw.eq("t3.pro_status",1);
        lqw.eq("t.bus_type",bo.getBusType());
        lqw.eq("t.mer_id",LoginHelper.getBusId());
        lqw.eq("t.syd_id",bo.getSydId());
        lqw.orderByDesc("t.create_time");
        List<BusMerchantProductVo> list = this.baseMapper.selBusMerProList(lqw);
        return list;
    }

    private LambdaQueryWrapper<BusMerchantProduct> buildQueryWrapper(BusMerchantProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusMerchantProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSydId() != null, BusMerchantProduct::getSydId, bo.getSydId());
        lqw.eq(StringUtils.isNotBlank(bo.getSydNo()), BusMerchantProduct::getSydNo, bo.getSydNo());
        lqw.eq(bo.getBusType() != null, BusMerchantProduct::getBusType, bo.getBusType());
        lqw.eq(StringUtils.isNotBlank(bo.getProNo()), BusMerchantProduct::getProNo, bo.getProNo());
        lqw.eq(bo.getProId() != null, BusMerchantProduct::getProId, bo.getProId());
        lqw.eq(StringUtils.isNotBlank(bo.getOpNo()), BusMerchantProduct::getOpNo, bo.getOpNo());
        lqw.eq(bo.getOpId() != null, BusMerchantProduct::getOpId, bo.getOpId());
        lqw.eq(bo.getCostServiceCharge() != null, BusMerchantProduct::getCostServiceCharge, bo.getCostServiceCharge());
        lqw.eq(bo.getServiceCharge() != null, BusMerchantProduct::getServiceCharge, bo.getServiceCharge());
        lqw.eq(bo.getChannelId() != null, BusMerchantProduct::getChannelId, bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelNo()), BusMerchantProduct::getChannelNo, bo.getChannelNo());
        lqw.eq(bo.getMerId() != null, BusMerchantProduct::getMerId, bo.getMerId());
        lqw.eq(StringUtils.isNotBlank(bo.getMerNo()), BusMerchantProduct::getMerNo, bo.getMerNo());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelCode()), BusMerchantProduct::getChannelCode, bo.getChannelCode());
        lqw.eq(bo.getChargeMode() != null, BusMerchantProduct::getChargeMode, bo.getChargeMode());
        lqw.eq(bo.getSettlementStyle() != null, BusMerchantProduct::getSettlementStyle, bo.getSettlementStyle());
        lqw.eq(bo.getMaxMonth() != null, BusMerchantProduct::getMaxMonth, bo.getMaxMonth());
        lqw.eq(bo.getInvoiceType() != null, BusMerchantProduct::getInvoiceType, bo.getInvoiceType());
        lqw.eq(StringUtils.isNotBlank(bo.getInvoiceItems()), BusMerchantProduct::getInvoiceItems, bo.getInvoiceItems());
        lqw.eq(bo.getProStatus() != null, BusMerchantProduct::getProStatus, bo.getProStatus());
        return lqw;
    }

    /**
     * 新增商户产品表
     */
    @Override
    @Transactional
    public Boolean insertByBo(JSONObject map) {

       String boListStr =  map.getString("boList");
       Long bus_type = map.getLong("busType");
       Long mer_id = map.getLong("merId");
       String merNo = map.getString("merNo");
       if(bus_type == null){
           this.invalidationParamsException("业务类型不能为空");
       }
       if(mer_id == null){
           this.invalidationParamsException("企业ID不能为空");
       }

        if(StringUtils.isEmpty(merNo)){
            this.invalidationParamsException("企业编码不能为空");
        }
       if(StringUtils.isEmpty(boListStr)){
           this.invalidationParamsException("请先配置产品");
       }
      boListStr =  map.getJSONArray("boList").toJSONString();
       Map paraMap = new HashMap();
       paraMap.put("channel_no", LoginHelper.getNo());
       paraMap.put("bus_type",bus_type);
       List<BusChannelProductVo> agentList = this.busChannelProductMapper.selectAgentProInfos(paraMap);
       if(agentList.size() == 0){
           this.invalidationParamsException("当前代理商未配置产品");
       }
       List<BusMerchantProductBo> voList = JSONUtil.toList(boListStr, BusMerchantProductBo.class);
       List<BusMerchantProduct> insertList = new ArrayList();
       for(BusMerchantProductBo vo :voList){
           SysSyd sysSyd = sydMapper.selectSysSydById(vo.getSydId());
           log.info("sydId:"+sysSyd.getId()+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
           SysThirdPlatform sysThirdPlatform = thirdPlatformMapper.selectThirdAppInfo(sysSyd.getId());
           log.info("sysThirdPlatform:"+sysThirdPlatform.getPlatformName());
           if (ObjectUtils.isNotEmpty(sysThirdPlatform)&&sysThirdPlatform.getPlatformName().equals("薪遇见")){
                BusMerchant busMerchant = busMerchantMapper.selectById(mer_id);
                xyjService.addMerchant(busMerchant,vo.getSydId());
            }
           BusChannelProductVo agentVo = agentList.stream().filter(t -> t.getProNo().equals(vo.getProNo())).findFirst().orElse(null);
           if(agentVo == null){
               this.invalidationParamsException("产品编码"+vo.getProNo()+"未配置");
           }
           vo.setSydId(agentVo.getSydId());
           vo.setSydNo(agentVo.getSydNo());
           vo.setProId(agentVo.getProId());
           vo.setOpId(agentVo.getOpId());
           vo.setOpNo(agentVo.getOpNo());
           vo.setMerId(mer_id);
           vo.setMerNo(merNo);
           vo.setChannelId(agentVo.getChannelId());
           vo.setChannelNo(agentVo.getChannelNo());
           vo.setMaxMonth(agentVo.getMaxMonth());
//           vo.setInvoiceItems(agentVo.getInvoiceItems());
           vo.setCostServiceCharge(agentVo.getServiceCharge());

//           ValidatorUtils.validate(vo, AddGroup.class);
           if(vo.getServiceCharge() != null && vo.getServiceCharge().compareTo(vo.getCostServiceCharge()) < 0){
               vo.setServiceCharge(vo.getCostServiceCharge());
           }
           vo.setBusType(bus_type);
           vo.setMerId(mer_id);
           if(vo.getId() != null){
               vo.setMdyServiceCharge(vo.getServiceCharge());
               vo.setServiceCharge(null);
               BusMerchantProduct update = MapstructUtils.convert(vo, BusMerchantProduct.class);
               insertList.add(update);
           }else{
               BusMerchantProduct add = MapstructUtils.convert(vo, BusMerchantProduct.class);
               insertList.add(add);
           }

       }
        this.baseMapper.insertOrUpdateBatch(insertList);
        return true;
    }

    /**
     * 修改商户产品表
     */
    @Override
    public Boolean updateByBo(BusMerchantProductBo bo) {
        BusMerchantProduct update = MapstructUtils.convert(bo, BusMerchantProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMerchantProduct entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商户产品表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
