package com.hai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.TelApiUtil;
import com.hai.dao.BsDistributionRebateMapper;
import com.hai.dao.BsDistributionUserRelMapper;
import com.hai.dao.HighUserMapper;
import com.hai.entity.*;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

@Service("bsDistributionUserRelService")
public class BsDistributionUserRelServiceImpl implements BsDistributionUserRelService {

    @Resource
    private BsDistributionUserRelMapper  bsDistributionUserRelMapper;

    @Resource
    private HighDiscountPackageService highDiscountPackageService;

    @Resource
    private BsDistributionRebateMapper bsDistributionRebateMapper;

    @Resource
    private HighUserService highUserService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private CommonService commonService;

    @Resource
    private HighUserMapper highUserMapper;

    @Override
    public void insertDistributionRebate(Long userId, Long popularizeUserId , String regionId) {

        HighUser user = highUserService.findByUserId(userId);
        HighUser pUser = highUserService.findByUserId(popularizeUserId);

        // 定义分销关联关系
        BsDistributionUserRel distributionUserRel = new BsDistributionUserRel();

        // 查询推广员信息
        Map<String, Object> map = new HashMap<>();
        map.put("userId" , popularizeUserId);

        BsDistributionUserRel popularizeUser = findDistributionUserRel(map);
        if (pUser != null) {
            if (pUser.getIsAgent() != null) {
                distributionUserRel.setAgentId(pUser.getId());
                distributionUserRel.setAgentName(pUser.getName());
            } else {
                if (popularizeUser != null) {
                    distributionUserRel.setAgentId(popularizeUser.getAgentId());
                    distributionUserRel.setAgentName(popularizeUser.getAgentName());
                }
                distributionUserRel.setPopularizeUserId(popularizeUserId);
                distributionUserRel.setPopularizeUserName(pUser.getName());
            }

            distributionUserRel.setUserId(userId);
            distributionUserRel.setUserName(user.getName());
            distributionUserRel.setPhone(TelApiUtil.phoneDesensitization(user.getPhone()));
            distributionUserRel.setCreateTime(new Date());
            distributionUserRel.setUpdateTime(new Date());
            distributionUserRel.setStatus(100);

            bsDistributionUserRelMapper.insert(distributionUserRel);

            new Thread(() -> {

                try {

                    SecRegion region = commonService.getParentByRegion(Long.valueOf(regionId));
                    BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());

                    // 查询注册有礼优惠券包
                    HighDiscountPackage discountPackage = highDiscountPackageService.getCallExclusive(3 , bsCompany.getId().intValue());
                    Map<String, Object> freeMap = new HashMap<>();
                    freeMap.put("discountPackageId", discountPackage.getId());
                    freeMap.put("userId", userId);
                    freeMap.put("userPhone", user.getPhone());
                    highDiscountPackageService.freeUserDiscountPackage(freeMap);

                    if (pUser.getIsAgent() == null) {
                        // 查询推广有礼优惠券包
                        HighDiscountPackage promoteDiscountPackage = highDiscountPackageService.getCallExclusive(4 , bsCompany.getId().intValue());
                        Map<String, Object> freeMap1 = new HashMap<>();
                        freeMap1.put("discountPackageId", promoteDiscountPackage.getId());
                        freeMap1.put("userId", pUser.getId());
                        freeMap1.put("userPhone", pUser.getPhone());
                        highDiscountPackageService.freeUserDiscountPackage(freeMap1);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }).start();
        }

    }

    @Override
    public List<BsDistributionUserRel> getDistributionUserRelList(Map<String, Object> map) {

        BsDistributionUserRelExample example = new BsDistributionUserRelExample();
        BsDistributionUserRelExample.Criteria criteria = example.createCriteria();


        if (MapUtils.getLong(map , "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map , "userId"));
        }

        if (MapUtils.getLong(map , "popularizeUserId") != null) {
            criteria.andPopularizeUserIdEqualTo(MapUtils.getLong(map , "popularizeUserId"));
        }

        return bsDistributionUserRelMapper.selectByExample(example);
    }

    @Override
    public BsDistributionUserRel findDistributionUserRel(Map<String, Object> map) {

        BsDistributionUserRelExample example = new BsDistributionUserRelExample();
        BsDistributionUserRelExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map , "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map , "userId"));
        }

        List<BsDistributionUserRel> list = bsDistributionUserRelMapper.selectByExample(example);

        if (list.size() > 0) {
            return list.get(0);
        }

        return null;
    }


    @Override
    public void distributionRebate(JSONObject object) {
        HighUser user = highUserService.findByUserId(object.getLong("userId"));
        // 查询下单用户上级推广员
        Map<String , Object> mapSuper = new HashMap<>();
        mapSuper.put("userId" , object.getLong("userId"));
        BsDistributionUserRel distributionUserRel = findDistributionUserRel(mapSuper);
        BsDistributionRebate distributionRebate = new BsDistributionRebate();
        // 上级推广员返利
        if (distributionUserRel != null) {
            distributionRebate.setAgentId(distributionUserRel.getAgentId());
            distributionRebate.setCreateTime(new Date());
            distributionRebate.setUpdateTime(new Date());
            distributionRebate.setStatus(100);
            distributionRebate.setType(1);
            distributionRebate.setUserName(user.getName());
            distributionRebate.setUserId(object.getLong("userId"));
            distributionRebate.setAgentId(distributionUserRel.getAgentId());
            distributionUserRel.setAgentName(distributionUserRel.getAgentName());
            distributionUserRel.setUserName(user.getName());
            distributionRebate.setPopularizeUserId(distributionUserRel.getPopularizeUserId());
            distributionRebate.setTitle(object.getString("title"));
            distributionRebate.setIntegralNum(object.getBigDecimal("integralNumFirst"));
            distributionRebate.setOrderNo(object.getString("orderNo"));
            distributionRebate.setExt1(object.getString("logoImg"));

            if (distributionUserRel.getPopularizeUserId() != null) {
                bsDistributionRebateMapper.insert(distributionRebate);
                // 上级返利
                highUserService.goldHandle(distributionUserRel.getPopularizeUserId(), object.getInteger("integralNumFirst"), 1, 4, object.getLong("userId") , user.getName() + "下单：获得返利" + object.getInteger("integralNumFirst"));

                // 查询下单用户顶级推广员
                Map<String , Object> mapTop = new HashMap<>();
                mapTop.put("userId" , distributionUserRel.getPopularizeUserId());
                BsDistributionUserRel distributionUserRelTop = findDistributionUserRel(mapTop);
                if (distributionUserRelTop != null) {
                    // 顶级推广员
                    if (distributionUserRelTop.getPopularizeUserId() != null) {
                        distributionRebate.setIntegralNum(object.getBigDecimal("integralNumSecond"));
                        distributionRebate.setPopularizeUserId(distributionUserRelTop.getPopularizeUserId());
                        distributionRebate.setType(2);
                        bsDistributionRebateMapper.insert(distributionRebate);
                        // 顶级返利
                        highUserService.goldHandle(distributionUserRelTop.getPopularizeUserId(), object.getInteger("integralNumSecond"), 1, 4, object.getLong("userId") , user.getName() + "下单：获得返利" + object.getInteger("integralNumSecond"));

                    }

                }
            }

        }

    }

    @Override
    public JSONObject userDistributionStatistics(Long userId) {

        JSONObject jsonObject = new JSONObject();

        BsDistributionUserRelExample example = new BsDistributionUserRelExample();
        BsDistributionUserRelExample.Criteria criteria = example.createCriteria();
        criteria.andPopularizeUserIdEqualTo(userId);

        Map<String, Object> map = bsDistributionRebateMapper.countDistribution(userId);

        jsonObject.put("inviteeNum" , bsDistributionUserRelMapper.countByExample(example));
        jsonObject.put("integralIncome" , map.get("sum"));
        jsonObject.put("orderCount" , map.get("count"));
        jsonObject.put("toDayIntegralNum" , bsDistributionRebateMapper.toDayIntegralNum(userId));


        return jsonObject;
    }

    @Override
    public List<BsDistributionRebate> getDistributionRebateList(Map<String, Object> map) throws Exception {
        BsDistributionRebateExample example = new BsDistributionRebateExample();
        BsDistributionRebateExample.Criteria criteria = example.createCriteria();


        if (MapUtils.getLong(map , "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map , "userId"));
        }

        if (MapUtils.getLong(map , "popularizeUserId") != null) {
            criteria.andPopularizeUserIdEqualTo(MapUtils.getLong(map , "popularizeUserId"));
        }

        List<BsDistributionRebate> list =  bsDistributionRebateMapper.selectByExample(example);

        for (BsDistributionRebate distributionRebate : list ) {
            distributionRebate.setExt3(DateUtil.date2String(distributionRebate.getCreateTime() , "MM月dd日 HH:mm"));
        }

        return list;
    }

    @Override
    public List<Map<String, Object>> getDistributionAgent() {
        return bsDistributionUserRelMapper.getDistributionAgent();
    }

    @Override
    public List<Map<String, Object>> getDistributionFirst(Long agentId) {
        return bsDistributionUserRelMapper.getDistributionFirst(agentId);
    }

    @Override
    public List<Map<String, Object>> getDistributionSecond(Long agentId, Long popularizeUserId) {
        return bsDistributionUserRelMapper.getDistributionSecond(agentId , popularizeUserId);
    }

    @Override
    public List<BsDistributionRebate> getDistributionIntegralList(Map<String, Object> map) {

        BsDistributionRebateExample example = new BsDistributionRebateExample();
        BsDistributionRebateExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getString(map, "title") != null) {
            criteria.andTitleLike("%" + MapUtils.getString(map, "title") + "%");
        }
        if (MapUtils.getInteger(map, "type") != null) {
            criteria.andTypeEqualTo(MapUtils.getInteger(map, "type"));
        }
        if (MapUtils.getString(map, "orderNo") != null) {
            criteria.andOrderNoEqualTo(MapUtils.getString(map, "orderNo"));
        }
        if (MapUtils.getLong(map, "agentId") != null) {
            criteria.andAgentIdEqualTo(MapUtils.getLong(map, "agentId"));
        }
        if (MapUtils.getLong(map, "popularizeUserId") != null) {
            criteria.andPopularizeUserIdEqualTo(MapUtils.getLong(map, "popularizeUserId"));
        }
        if (MapUtils.getString(map, "userName") != null) {
            criteria.andUserNameLike("%" + MapUtils.getString(map, "userName") + "%");
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "createTimeS")) && StringUtils.isNotBlank(MapUtils.getString(map, "createTimeE"))) {
            criteria.andCreateTimeBetween(
                    DateUtil.format(MapUtils.getString(map, "createTimeS"), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.format(MapUtils.getString(map, "createTimeE"), "yyyy-MM-dd HH:mm:ss"));
        }

        example.setOrderByClause("create_time desc");
        return bsDistributionRebateMapper.selectByExample(example);
    }

    @Override
    public List<HighUser> agentUserList() {

        HighUserExample example = new HighUserExample();
        example.createCriteria().andIsAgentEqualTo(true).andStatusEqualTo(1);

        return highUserMapper.selectByExample(example);
    }
}
