package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.bcx.BcxPerformanceReport;
import com.zbkj.common.model.bcx.BcxProductBenefits;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.UserProductBenefitsRequest;
import com.zbkj.common.request.UserProductBenefitsSaveRequest;
import com.zbkj.common.response.BcxPerformanceReportResponse;
import com.zbkj.common.response.UserProductBenefitsResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.vo.DateLimitUtilVo;
import com.zbkj.service.dao.BcxProductBenefitsDao;
import com.zbkj.service.service.BcxProductBenefitsService;
import com.zbkj.service.service.ProductService;
import com.zbkj.service.service.UserService;
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 org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * description：福利配置表 服务接口
 * author：linchunpeng
 * date：2024/1/26
 */
@Service
public class BcxProductBenefitsServiceImpl extends ServiceImpl<BcxProductBenefitsDao, BcxProductBenefits> implements BcxProductBenefitsService {

    @Resource
    private BcxProductBenefitsDao dao;
    @Resource
    private ProductService productService;
    @Autowired
    private UserService userService;

    /**
     * 根据商品id，查询授权的企业列表
     */
    @Override
    public List<BcxProductBenefits> findListByProductId(Integer productId) {
        LambdaQueryWrapper<BcxProductBenefits> lqw = Wrappers.lambdaQuery();
        lqw.eq(BcxProductBenefits::getProductId, productId);
        Date nowTime = new Date();
        lqw.and(wrapper -> wrapper.le(BcxProductBenefits::getAuthStartTime, nowTime).or().isNull(BcxProductBenefits::getAuthStartTime));
        lqw.and(wrapper -> wrapper.ge(BcxProductBenefits::getAuthEndTime, nowTime).or().isNull(BcxProductBenefits::getAuthEndTime));
        return dao.selectList(lqw);
    }

    /**
     * 根据企业id，查询授权的商品列表
     */
    @Override
    public List<BcxProductBenefits> findListByCompanyId(String companyId) {
        LambdaQueryWrapper<BcxProductBenefits> lqw = Wrappers.lambdaQuery();
        lqw.eq(BcxProductBenefits::getCompanyId, companyId);
        Date nowTime = new Date();
        lqw.and(wrapper -> wrapper.le(BcxProductBenefits::getAuthStartTime, nowTime).or().isNull(BcxProductBenefits::getAuthStartTime));
        lqw.and(wrapper -> wrapper.ge(BcxProductBenefits::getAuthEndTime, nowTime).or().isNull(BcxProductBenefits::getAuthEndTime));
        return dao.selectList(lqw);
    }


   /**
    * description：根据分销商，查询分销商品列表
    * author：linchunpeng
    * date：2024/5/10
    */
    @Override
    public PageInfo<UserProductBenefitsResponse> getPage(UserProductBenefitsRequest request,
                                                         PageParamRequest pageRequest) {
        User user = userService.getInfo();
        List<UserProductBenefitsResponse> result = new ArrayList<>();
        Page<BcxProductBenefits> page = PageHelper.startPage(pageRequest.getPage(), pageRequest.getLimit());
        if (user.getUserType() == 1 && user.getIsPromoter() && user.getSpreadUid() == 0) {
            //企业账号、有分销、最顶级
            HashMap<String, Object> map = CollUtil.newHashMap();
            if (StrUtil.isNotBlank(request.getProductName())) {
                map.put("productName", request.getProductName());
            }
            result = dao.selectByFxs(map);
            if (CollectionUtil.isNotEmpty(result)) {
                for (UserProductBenefitsResponse response : result) {
                    response.setBrokerageTotal(productService.getBrokerageTotal(response.getProductId()));
                }
            }
        }
        return CommonPage.copyPageInfo(page, result);
    }

    /**
     * description：分佣配置保存
     * author：linchunpeng
     * date：2024/5/10
     */
    @Override
    @Transactional
    public Boolean saveConfig(UserProductBenefitsSaveRequest request) {
        if (StringUtils.isBlank(request.getId())) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("配置id 不能为空"));
        }
        if (request.getIsEnableConfig() == null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("是否启用单独配置 不能为空"));
        }
        if (request.getBrokerage() == null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("分销员比例 不能为空"));
        }
        User user = userService.getInfo();
        BcxProductBenefits bcxProductBenefits = this.getById(request.getId());
        if (bcxProductBenefits == null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("分销商品 不存在"));
        }
        if (!bcxProductBenefits.getCompanyId().equals(user.getAccount())) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("无权限修改此分享商品"));
        }
        Integer brokerageTotal = productService.getBrokerageTotal(bcxProductBenefits.getProductId());
        if (request.getBrokerage() > brokerageTotal) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("分销员比例 不能大于总比例"));
        }
        bcxProductBenefits.setIsEnableConfig(request.getIsEnableConfig());
        bcxProductBenefits.setBrokerage(request.getBrokerage());
        this.updateById(bcxProductBenefits);
        return true;
    }
}