package com.bizzan.bitrade.controller;

import static com.bizzan.bitrade.constant.SysConstant.SESSION_MEMBER;
import static com.bizzan.bitrade.entity.QMember.member;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.bizzan.bitrade.constant.PageModel;
import com.bizzan.bitrade.controller.screen.ContractRewardRecordScreen;
import com.bizzan.bitrade.controller.screen.MemberScreen;
import com.bizzan.bitrade.entity.ContractRewardRecord;
import com.bizzan.bitrade.entity.Member;
import com.bizzan.bitrade.entity.MemberWeightUpper;
import com.bizzan.bitrade.entity.QContractRewardRecord;
import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.service.ContractRewardRecordService;
import com.bizzan.bitrade.service.MemberService;
import com.bizzan.bitrade.service.MemberWeightUpperService;
import com.bizzan.bitrade.util.DateUtil;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.util.PredicateUtils;
import com.bizzan.bitrade.vo.RewardSetVo;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value = "AgentController" , tags = "代理商接口(从用户模块转移)")
@RestController
@Slf4j
public class AgentController extends BaseController {

    @Autowired
    private MemberService memberService;
	@Autowired
    private ContractRewardRecordService contractRewardRecordService;
    @Resource
    private MemberWeightUpperService memberWeightUpperService;
	
    @ApiOperation(value="获取下级成员列表", notes="获取下级成员列表")
	@PostMapping(value = "/member/list")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult memberList(
            PageModel pageModel,
            MemberScreen screen,
            @SessionAttribute(SESSION_MEMBER) AuthMember user) {
        // 检查用户是否是代理商
        Member checkMember = memberService.findOne(user.getId());
        if(!checkMember.getSuperPartner().equals("1")) {
            return error("您不是代理商！");
        }
        Predicate predicate = getMemberPredicate(screen, user.getId());
        Page<Member> all = memberService.findAll(predicate, pageModel.getPageable());
        return success(all);
    }
	private Predicate getMemberPredicate(MemberScreen screen, Long userId) {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();
        if (screen.getStatus() != null) {
            booleanExpressions.add(member.certifiedBusinessStatus.eq(screen.getStatus()));
        }
        if (screen.getStartTime() != null) {
            booleanExpressions.add(member.registrationTime.goe(screen.getStartTime()));
        }
        if (screen.getEndTime() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(screen.getEndTime());
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            booleanExpressions.add(member.registrationTime.lt(calendar.getTime()));
        }

        if (!StringUtils.isEmpty(screen.getAccount())) {
            booleanExpressions.add(member.username.like("%" + screen.getAccount() + "%")
                    .or(member.mobilePhone.like(screen.getAccount() + "%"))
                    .or(member.email.like(screen.getAccount() + "%"))
                    .or(member.id.eq(Long.valueOf(screen.getAccount())))
                    .or(member.realName.like("%" + screen.getAccount() + "%")));
        }
        // 筛选过滤出我邀请的人
        booleanExpressions.add(member.inviterId.eq(userId));
        if (screen.getCommonStatus() != null) {
            booleanExpressions.add(member.status.eq(screen.getCommonStatus()));
        }
        return PredicateUtils.getPredicate(booleanExpressions);
    }
	
	@ApiOperation(value="获取返佣记录", notes="获取返佣记录")
	@PostMapping(value = "/reward")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult pageQuery(
            PageModel pageModel,
            ContractRewardRecordScreen screen,
            @SessionAttribute(SESSION_MEMBER) AuthMember user) {

        Member checkMember = memberService.findOne(user.getId());
        if(!checkMember.getSuperPartner().equals("1")) {
            return error("您不是代理商！");
        }

        if (pageModel.getDirection() == null && pageModel.getProperty() == null) {
            ArrayList<Sort.Direction> directions = new ArrayList<>();
            directions.add(Sort.Direction.DESC);
            pageModel.setDirection(directions);
            List<String> property = new ArrayList<>();
            property.add("createTime");
            pageModel.setProperty(property);
        }
        //获取查询条件
        Predicate predicate = getPredicate(screen,checkMember.getId());

        Page<ContractRewardRecord> results = contractRewardRecordService.findAll(predicate, pageModel.getPageable());

        return success(results);
    }
	
	private Predicate getPredicate(ContractRewardRecordScreen screen,Long id) {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();
        QContractRewardRecord qContractRewardRecord = QContractRewardRecord.contractRewardRecord;
        booleanExpressions.add((qContractRewardRecord.member.id.eq(id)));
        if(screen.getMemberId()!=null) {
            booleanExpressions.add((qContractRewardRecord.fromMember.id.eq(screen.getMemberId())));
        }
        if (screen.getStartTime() != null) {
            booleanExpressions.add(qContractRewardRecord.createTime.goe(screen.getStartTime()));
        }
        if (screen.getEndTime() != null){
            booleanExpressions.add(qContractRewardRecord.createTime.lt(DateUtil.dateAddDay(screen.getEndTime(),1)));
        }
        if (screen.getType() != null) {
            booleanExpressions.add(qContractRewardRecord.type.eq(screen.getType()));
        }
        return PredicateUtils.getPredicate(booleanExpressions);
    }
	
	@ApiOperation(value="设置返佣比率", notes="设置返佣比率")
    @ApiImplicitParams(value = {
    		@ApiImplicitParam(name = "id",value = "用户ID",required = true,paramType = "form",dataType = "int"),
    		@ApiImplicitParam(name = "rate",value = "比率",required = true,paramType = "form",dataType = "int"),
    		@ApiImplicitParam(name = "wcRate",value = "杯比率",required = true,paramType = "form",dataType = "int")
    })
	@PostMapping(value = "/reward/set")
    public MessageResult set(
            @SessionAttribute(SESSION_MEMBER) AuthMember user,
            @RequestParam("id") Long memberId,
            @RequestParam("rate") Integer rate,
            Integer wcRate
            ) {
        if(memberId == null){
            return error("设置用户的id不能为空！");
        }
        if(rate == null){
            return error("设置用户的比例不能为空！");
        }
        if(rate.intValue() < 0 || rate.intValue() > 100){
            return error("设置用户的比例不能为小于0%或超过100%！");
        }
        if(wcRate != null 
        		&& (wcRate.intValue()!=0&&wcRate.intValue()!=2&&wcRate.intValue()!=4&&wcRate.intValue()!=6&&wcRate.intValue()!=8)){
            return error("设置用户的比例不合法！");
        }
        Member checkMember = memberService.findOne(user.getId());
        if(!"1".equals(checkMember.getSuperPartner())) {
            return error("您不是代理商！");
        }
        Member setMember = memberService.findOne(memberId);
        MemberWeightUpper upperMemberId = memberWeightUpperService.findMemberWeightUpperByMemberId(setMember.getInviterId());
        
        /*Member upperMember = memberService.findOne(setMember.getInviterId());
        if("1".equals(upperMember.getSuperPartner())){
            if (rate.intValue() >= 100) {
                return error("设置比例应小于此用户上级推荐人的比例！");
            }
        }else {*/
        if (rate.intValue() >= upperMemberId.getRate().intValue()) {
            return error("设置比例应小于此用户上级推荐人的比例！");
        }
        if(wcRate != null && (upperMemberId.getWcRate()==null || wcRate.intValue() >= upperMemberId.getWcRate().intValue())) {
        	return error("设置比例应小于此用户上级推荐人的比例！");
        }
        //}
        
        
        List<MemberWeightUpper> lowMemberWeightUpper = memberWeightUpperService.findAllByUpper(memberId);
        for (MemberWeightUpper memberWeightUpper:lowMemberWeightUpper) {
            if(rate.intValue() <= memberWeightUpper.getRate().intValue()){
                return error("设置比例应大于此用户后面直推人的比例！");
            }
            
            if(wcRate != null && memberWeightUpper.getWcRate()!=null && wcRate.intValue() <= memberWeightUpper.getWcRate().intValue()) {
            	return error("设置比例应大于此用户后面直推人的比例！");
            }
        }
        MemberWeightUpper memberWeightUpper = memberWeightUpperService.findMemberWeightUpperByMemberId(memberId);
        if(memberWeightUpper.getAllUppers().indexOf(String.valueOf(user.getId()))<0)
        	return error("illegal operation");
        log.info("memberWeightUpper.getUpper()={}", memberWeightUpper.getUpper());
        /*if(memberWeightUpper.getUpper()!=null) {
	        List<Member> allByIds = memberService.findAllByIds(memberWeightUpper.getUpper());
	        Optional<Member> firstSuperPartner = allByIds.stream().filter(e -> "1".equals(e.getSuperPartner())).findFirst();
	        if(firstSuperPartner.isPresent()){
	            if (!firstSuperPartner.get().getId().equals(checkMember.getId())){
	                return error("不能设置下级代理商的直推用户！");
	            }
	        }
        }*/
        memberWeightUpper.setRate(rate);
        memberWeightUpper.setWcRate(wcRate);
        memberWeightUpperService.save(memberWeightUpper);
        return success();
    }
	
	@ApiOperation(value="获取代理商信息", notes="获取代理商信息")
	@PostMapping(value = "info")
    public MessageResult agentInfo(
            @SessionAttribute(SESSION_MEMBER) AuthMember user) {
    	Member member = memberService.findOne(user.getId());
    	log.info("contractRewardRecordService={}, id={}", contractRewardRecordService,member.getId());
    	Double total_reward = contractRewardRecordService.findRewardSum(member.getId());
    	log.info("total_reward={}", total_reward);
    	if(total_reward!=null)
    		member.setUsdtBalance(total_reward);
    	else
    		member.setUsdtBalance(0);
    	MessageResult result = MessageResult.success();
    	result.setData(member);
    	return result;
    }
	
	@ApiOperation(value="获取返佣设置列表", notes="获取返佣设置列表")
	@PostMapping(value = "/reward/set/list")
    public MessageResult setList(
            @SessionAttribute(SESSION_MEMBER) AuthMember user) {
		Member checkMember = memberService.findOne(user.getId());
        if(!checkMember.getSuperPartner().equals("1")) {
            return error("您不是代理商！");
        }
        RewardSetVo vo = contractRewardRecordService.findOneLevelRewardSetVo(user.getId());
        return success(vo.getChildren());
	}
}
