package com.ruoyi.applet.contoller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyl.manager.oms.domain.Order;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.pojo.query.MemberQuery;
import com.cyl.manager.ums.pojo.vo.MemberDataStatisticsVO;
import com.cyl.manager.ums.pojo.vo.MemberExtendVo;
import com.cyl.manager.ums.service.MemberService;
import com.github.pagehelper.PageHelper;
import com.ruoyi.applet.pojo.dto.ApiQueryIIdDTO;
import com.ruoyi.applet.pojo.dto.ApiQueryIIdMyUserDTO;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SortUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.model.domain.AppBanner;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.domain.AppletAmountLog;
import com.ruoyi.model.domain.AppletUsers;
import com.ruoyi.model.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Api(description = "伴宠师-合伙人工作台内部流程")
@RestController
@RequestMapping("/applet/workOut")
public class ApiAppletHhrWorkOutController {

    //伴宠师-登录相关问题
    @Resource
    private IAApiAppletHhrWorkOutService apiAppletHhrWorkOutService;
    @Resource
    private IAppBannerService bannerService;
    @Resource
    private MemberService  service;
    @Autowired
    private MemberMapper memberMapper;
    @Resource
    private IAppUsersService appUsersService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private IAppletAmountLogService appletAmountLogService;


    //合伙人工作台 - 绑定用户基础信息
    @ApiOperation("合伙人工作台 - 绑定用户基础信息")
    @GetMapping("/hhrInfo/{appUserId}")
    public AjaxResult HhrInfo(@PathVariable("appUserId") Long appUserId){
        return  apiAppletHhrWorkOutService.HhrInfo(appUserId);
    }



    //合伙人工作台 - 绑定二维码
    @ApiOperation("合伙人工作台 - 绑定二维码")
    @GetMapping("/hhrCode/{appUserId}")
    public AjaxResult HhrCode(@PathVariable("appUserId") Long appUserId){
        return  apiAppletHhrWorkOutService.HhrCode(appUserId);
    }


//    //合伙人工作台 - 我的用户列表 0 未下单 1已下单
//    @ApiOperation("合伙人工作台 - 我的用户列表 0 未下单 1已下单")
//    @PostMapping("/hhrMyUserList")
//    public AjaxResult HhrMyUserList(@RequestBody ApiQueryIIdMyUserDTO dto, Pageable page){
//        return  apiAppletHhrWorkOutService.HhrMyUserList(dto.getAppUserId(),dto.getState(),page);
//    }



    @ApiOperation("合伙人工作台 - 我的用户列表 0 未下单 1已下单")
    @PostMapping("/hhrMyUserList")
    public ResponseEntity<Page<MemberExtendVo>> HhrMyUserList(@RequestBody ApiQueryIIdMyUserDTO dto, Pageable page) {

        //用户标识不能为空
        if (dto.getAppUserId() == null) {
            return ResponseEntity.ok(new PageImpl<>(new ArrayList<>()));
        }
        //根据用户标识查询用户信息
        AppUsers appUsers = appUsersService.selectAppUsersByUserId(dto.getAppUserId());


        if (StringUtils.isEmpty(appUsers.getInvitationCode())){
            return ResponseEntity.ok(new PageImpl<>(new ArrayList<>()));
        }

//        MemberQuery query = new MemberQuery();
//        query.setInviteCode(appUsers.getInvitationCode());
//        List<Member> list = service.selectList(query, page);


        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(), SortUtil.sort2string(page.getSort(),"id desc"));
        }

        List<Member> list = memberMapper.selectList(Wrappers.<Member>lambdaQuery()
                .eq(Member::getInviteCode, appUsers.getInvitationCode()));

        List<MemberExtendVo> memberExtendVoList = new ArrayList<>();
        list.forEach(member -> {
            MemberExtendVo memberExtendVo = new MemberExtendVo();
            BeanUtils.copyProperties(member, memberExtendVo);
            MemberDataStatisticsVO mds = service.viewStatistics(member.getId());

            if (mds.getOrderCount() == 0 && dto.getState() != 0
            || mds.getOrderCount() > 0 && dto.getState() == 0){
                return;
            }

            BeanUtils.copyProperties(mds, memberExtendVo);

            memberExtendVo.setPhoneHidden(service.getPhoneDecrypted(memberExtendVo.getPhoneEncrypted()));

            //查询最近下单时间
            Order order = orderMapper.selectOne(Wrappers.<Order>lambdaQuery()
                    .select(Order::getCreateTime)
                    .eq(Order::getMemberId, member.getId())
                    .orderByDesc(Order::getCreateTime)
                    .last("limit 1"));
            memberExtendVo.setOrderTime(order.getCreateTime());

            //查询累计报酬
            List<AppletAmountLog> amountLogs = appletAmountLogService.lambdaQuery()
                            .select(AppletAmountLog::getAmount)
                            .eq(AppletAmountLog::getUserId, appUsers.getUserId())
                            .eq(AppletAmountLog::getFormId, member.getId())
                            .eq(AppletAmountLog::getType, 0)
                            .eq(AppletAmountLog::getMoneyType, 0)
                            .list();

            // 统计金额总和
            BigDecimal totalAmount = amountLogs.stream()
                    .map(AppletAmountLog::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            memberExtendVo.setUserAmount(totalAmount);

            memberExtendVoList.add(memberExtendVo);
        });

//        if(dto.getState() == 0){
//            //得到list中orderAmount为0的集合
//            for (MemberExtendVo memberExtendVo : memberExtendVoList) {
//                if (memberExtendVo.getOrderAmount().compareTo(BigDecimal.ZERO) != 0) {
//                    memberExtendVoList.remove(memberExtendVo);
//                }
//
//            }
//        }else{
//            for (MemberExtendVo memberExtendVo : memberExtendVoList) {
//                if (memberExtendVo.getOrderAmount().compareTo(BigDecimal.ZERO) == 0) {
//                    memberExtendVoList.remove(memberExtendVo);
//                }
//            }
//        }


        return ResponseEntity.ok(new PageImpl<>(memberExtendVoList, page, ((com.github.pagehelper.Page)list).getTotal()));
    }



    //合伙人工作台 - 根据用户标识查询用户下单详细信息
    @ApiOperation("合伙人工作台 - 根据用户标识查询用户下单详细信息")
    @GetMapping("/hhrMyUserGetById/{appUserId}")
    public AjaxResult HhrMyUserGetById(@PathVariable("appUserId") Long appUserId){
        return  apiAppletHhrWorkOutService.HhrMyUserGetById(appUserId);
    }

    //获取bannerList
    @ApiOperation("合伙人工作台 - 获取bannerList")
    @GetMapping("/bannerList")
    public AjaxResult bannerList(){
        List<AppBanner> bannerList = bannerService.getBannerList();
        return  AjaxResult.success(bannerList);
    }










}
