package com.github.wxiaoqi.security.admin.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.constant.MemberRightType;
import com.github.wxiaoqi.security.admin.dto.MemberLevelRightsDTO;
import com.github.wxiaoqi.security.admin.dto.BaseMemberLevelFindDTO;
import com.github.wxiaoqi.security.admin.dto.BaseMemberLevelPageDTO;
import com.github.wxiaoqi.security.admin.entity.BaseMemberLevel;
import com.github.wxiaoqi.security.admin.mapper.BaseMemberLevelMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.activity.feign.ActivityFeign;
import com.xxfc.platform.universal.feign.ThirdFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员等级设置
 *
 * @author hezhen
 * @email 18178966185@163.com
 * @date 2020-06-24 09:12:21
 */
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class BaseMemberLevelBiz extends BaseBiz<BaseMemberLevelMapper, BaseMemberLevel> {

    @Autowired
    private BaseUserMemberBiz baseUserMemberBiz;

    @Autowired
    private ThirdFeign thirdFeign;


    @Autowired
    private ActivityFeign activityFeign;



    private static final String MEMBERMODEL_TYPE = "MEMBER_RIGHTS";
    private static final String MEMBERMODEL_CODE = "DA_YUN";



    public ObjectRestResponse<PageDataVO> selectList(BaseMemberLevelFindDTO userMemberLevelDTO) {
        Integer page=userMemberLevelDTO.getPage()==null?1:userMemberLevelDTO.getPage();
        Integer limit=userMemberLevelDTO.getLimit()==null?10:userMemberLevelDTO.getLimit();

        return  ObjectRestResponse.succ(PageDataVO.pageInfo(page, limit, ()->getList(userMemberLevelDTO)));
    }
    public  List<BaseMemberLevel> getList(BaseMemberLevelFindDTO userMemberLevelDTO){
        Example memberLevelExample = new Example(BaseMemberLevel.class);
        memberLevelExample.setOrderByClause("level asc");
        Example.Criteria criteria = memberLevelExample.createCriteria();
        criteria.andEqualTo("isDel", 0);
        if (userMemberLevelDTO.getLevelIds() != null && userMemberLevelDTO.getLevelIds().size() > 0){
            criteria.andIn("id",userMemberLevelDTO.getLevelIds());
        }
        return  mapper.selectByExample(memberLevelExample);
    }

    public BaseMemberLevel getMinDiscount(String appId){
        BaseMemberLevelFindDTO userMemberLevelDTO =new BaseMemberLevelFindDTO();
        userMemberLevelDTO.setAppId(appId);
        List<BaseMemberLevel> list=getList(userMemberLevelDTO);
        BaseMemberLevel baseUserMemberLevel=new BaseMemberLevel();
        if (list.size() > 0){
            baseUserMemberLevel=list.stream().filter(o -> o.getDiscount() > 0).min(Comparator.comparing(BaseMemberLevel::getDiscount)).get();
        }
        return   baseUserMemberLevel;
    }


    public BaseMemberLevel getUserMemberLevelDetailById(Integer id) {
        BaseMemberLevel userMemberLevel = mapper.selectByPrimaryKey(id);
        Integer maxLevel = getMaxLevel();
        userMemberLevel.setMaxLevel(maxLevel);
        return userMemberLevel;
    }


    private List<Long> getCouponIds(List<BaseMemberLevel> memberLevels) {
        return memberLevels.stream()
                .map(BaseMemberLevel::getMemberRights)
                .flatMap(List::stream)
                .filter(x -> Objects.equals(x.getType(), MemberRightType.COUNPON.getType()))
                .map(MemberLevelRightsDTO::getRights)
                .map(MemberLevelRightsDTO.MemberRights::getCoupons)
                .flatMap(List::stream)
                .filter(Objects::nonNull)
                .map(MemberLevelRightsDTO.Coupon::getId).collect(Collectors.toList());
    }



    public void saveOrUpdateBaseUserMemberLevel(BaseMemberLevel baseMemberLevel) {
        List<MemberLevelRightsDTO> memberRights = baseMemberLevel.getMemberRights();
        for (MemberLevelRightsDTO memberRight : memberRights) {
            //同步会员权益
            if (Objects.nonNull(baseMemberLevel.getId())) {
                if (Objects.nonNull(memberRight.getSysn()) && memberRight.getSysn()) {
                    //baseUserMemberBiz.sysnUserMemberLevelRights(baseMemberLevel.getId(), memberRight, baseMemberLevel.getAppId());
                }
            }
            memberRight.setSysn(null);
        }
        baseMemberLevel.setRights(JSON.toJSONString(memberRights));
        if (Objects.nonNull(baseMemberLevel.getId())) {
            baseMemberLevel.setUpdTime(Instant.now().toEpochMilli());
            mapper.updateByPrimaryKeySelective(baseMemberLevel);
        } else {
            baseMemberLevel.setCrtTime(Instant.now().toEpochMilli());
            mapper.insertSelective(baseMemberLevel);
        }
    }

    public void deleteUserMemberLevelById(Integer id, Integer changeLevel) {
        //1.根据id删除
        //1.1 根据id查询
        BaseMemberLevel baseUserMemberLevel = mapper.selectByPrimaryKey(id);
        //1.2 删除
        baseUserMemberLevel.setIsDel(1);
        mapper.updateByPrimaryKeySelective(baseUserMemberLevel);

        //2.同步会员等级操作
        changeLevel = baseUserMemberLevel.getLevel() + changeLevel;


        if (changeLevel == 0 ){
            //baseUserMemberBiz.sysnBaseUserMember(baseUserMemberLevel.getLevel() ,0,"",changeLevel,appId);
        }else {
            //2.1 根据level查询
            BaseMemberLevel memberLevel = mapper.selectByLevel(changeLevel);

            //2.2 同步会员
            //baseUserMemberBiz.sysnBaseUserMember(baseUserMemberLevel.getId(),memberLevel);
        }



        //3.更改比当前数据level大的数据，-1
        mapper.updateUserMemberLevel(baseUserMemberLevel.getLevel());

    }

    public Integer getMaxLevel() {
        Integer maxLevel = mapper.selectMaxLevel();
        maxLevel = maxLevel == null ? 0 : maxLevel;
        return maxLevel;
    }


    /*public JSONObject getLevelInfo(BaseUserMember userMember){
        BaseUserMemberVo userMemberVo = baseUserMemberBiz.getUserMemberByUserId(userMember.getUserId());
        JSONObject jsonObject=new JSONObject();
        Integer level=0;
        if (userMemberVo != null){
            BaseMemberLevel memberLevel = selectById(userMemberVo.getMemberLevel());
            Integer levelId=0;
            if (memberLevel != null ){
                levelId=memberLevel.getLevel()==null?0:memberLevel.getLevel();
            }
            jsonObject.put("currentMember",memberLevel);
            level=levelId+1;
        }else {
            level=1;
        }
        BaseMemberLevel nextMember=mapper.selectByLevel(level);
        BaseMemberLevel maxMember=mapper.selectByLevel(getMaxLevel());
        if (nextMember  == null){
            nextMember=maxMember;
        }
        jsonObject.put("nextMember",nextMember);
        jsonObject.put("maxMember",maxMember);
        UsersPurse usersPurse = usersPurseBiz.getUserPurseByUserId(userMember.getUserId());
        BigDecimal totalBuy=BigDecimal.ZERO;
        if (usersPurse != null ){
            totalBuy=usersPurse.getTotalBuy();
        }
        jsonObject.put("totalBuy",totalBuy);
        jsonObject.put("percentage",totalBuy.divide(nextMember.getMoney(),2).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP));

        return jsonObject;

    }*/

    public  List<BaseMemberLevel> getAll(BaseMemberLevel baseUserMemberLevel){
        return  selectList(baseUserMemberLevel);
    }

    public BaseMemberLevel getNextLevel(BaseMemberLevel baseUserMemberLevel){
        return  mapper.getNextLevel(baseUserMemberLevel.getMoney(),baseUserMemberLevel.getLevel());
    }

    public BaseMemberLevel getMemberLevel(Integer levelId, String levelIds){
        if (org.apache.commons.lang3.StringUtils.isNotBlank(levelIds)){
            BaseMemberLevel userMemberLevel=selectById(levelId);
            if (userMemberLevel != null ){
                int[] ints = Arrays.stream(levelIds.split(",")).mapToInt(s -> Integer.parseInt(s)).toArray();
                Arrays.sort(ints);
                List<Integer> aList =Arrays.stream(ints).boxed().collect(Collectors.toList());
                BaseMemberLevelFindDTO userMemberLevelDTO =new BaseMemberLevelFindDTO();
                userMemberLevelDTO.setLevelIds(aList);
                List<BaseMemberLevel> list = getList(userMemberLevelDTO);
                if (list != null && list .size() >0){
                    BaseMemberLevel userMemberLevel1=null;
                     for (BaseMemberLevel baseUserMemberLevel:list){
                         if (baseUserMemberLevel.getLevel() >  userMemberLevel.getLevel()){
                             userMemberLevel1=baseUserMemberLevel;
                             break;
                         }
                     }
                     return  userMemberLevel1;
                }
            }
        }
           return  null;
    }


    public  List<BaseMemberLevel>  getListByLevelId(Integer levelId){
        return  mapper.getListByLevelId(levelId);
    }
}