package com.mcwl.web.controller.memberCenter;

import cn.hutool.core.bean.BeanUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.AjaxResult;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.PageDomain;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.memberCenter.domain.*;
import com.mcwl.memberCenter.domain.vo.MemberConsumeVO;
import com.mcwl.memberCenter.domain.vo.MemberVo;
import com.mcwl.memberCenter.domain.vo.RechargeRecordVO;
import com.mcwl.memberCenter.enums.PromotionEnum;
import com.mcwl.memberCenter.service.*;
import com.mcwl.memberCenter.domain.dto.RechargePointsDto;
import com.mcwl.memberCenter.domain.dto.UserMemberDto;
import com.mcwl.system.service.ISysUserService;
import com.mcwl.memberCenter.domain.vo.PointsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jboss.marshalling.SimpleDataInput;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 会员中心
 */
@RestController
@RequestMapping("member")
@RequiredArgsConstructor
@Api(tags = "会员中心")
public class MemberController {

    private final MemberService memberService;

    private final ISysUserService sysUserService;

    private final MemberConsumeService memberConsumeService;

    private final MemberBenefitService memberBenefitService;

    private final MemberLevelService memberLevelService;

    private final MemberPromotionService memberPromotionService;

    /**
     * 创建用户会员
     *
     * @param userMemberDto 参数
     * @return 用户会员
     */
    @PostMapping("createMember")
    public R<Member> createMemberCenter(@RequestBody @Valid UserMemberDto userMemberDto) {
        Long userId = userMemberDto.getUserId();
        Long memberLevelId = userMemberDto.getMemberLevelId();
        String paymentMethod = userMemberDto.getPaymentMethod();
        Long promotionId = userMemberDto.getPromotionId();

        SysUser sysUser = sysUserService.selectUserById(userId);
        if (!Optional.ofNullable(sysUser).isPresent()) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "用户不存在");
        }

        MemberLevel memberLevel = memberLevelService.getById(memberLevelId);
        if (!Optional.ofNullable(memberLevel).isPresent()) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "会员等级不存在");
        }

        Member member = memberService.createUserMember(userId, memberLevelId, paymentMethod, promotionId);
        if (!Optional.ofNullable(member).isPresent()) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "创建会员失败");
        }

        return R.ok(member);
    }


    /**
     * 获取用户有效会员的会员
     */
    @ApiOperation(value = "获取用户有效会员的会员")
    @GetMapping("getValidMemberById")
    public R<List<MemberVo>> getUseUserMember(@Valid @NotNull(message = "用户id不能为空") Long userId) {

        return R.ok(memberService.getValidMemberById(userId));
    }


    /**
     * 获取积分消费记录
     *
     * @return 获取积分消费记录
     */
    @PostMapping("getConsumePoints")
    @ApiOperation(value = "获取积分消费记录")
    public TableDataInfo getConsumePoints(@Valid @RequestBody PageDomain pageDomain) {

        return memberConsumeService.getConsumePoints(pageDomain);
    }

    /**
     * 获取积分充值记录
     */
    @PostMapping("getRechargePoints")
    @ApiOperation(value = "获取积分充值记录")
    public TableDataInfo getRechargePoints(@Valid @RequestBody PageDomain pageDomain) {

        return memberService.getRechargePoints(pageDomain);
    }


    /**
     * 会员积分充值
     */
    @PostMapping("rechargePoints")
    @ApiOperation(value = "会员积分充值")
    public R<Object> rechargePoints(@RequestBody @Valid RechargePointsDto rechargePointsDto) {
        Long userId = rechargePointsDto.getUserId();
        Double amount = rechargePointsDto.getAmount();

        SysUser sysUser = sysUserService.selectUserById(userId);
        if (!Optional.ofNullable(sysUser).isPresent()) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "用户不存在");
        }

        Member member = memberService.rechargePoints(userId, amount * 100);

        // 返回充值积分
        if (!Optional.ofNullable(member).isPresent()) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "充值积分失败");
        }

        return R.ok();
    }


    /**
     * 消费积分
     */
    @GetMapping("consumePoints/{consumePoints}")
    @ApiOperation(value = "消费积分")
    public R<Object> consumePoints(@PathVariable Double consumePoints) {

        if (consumePoints == null || consumePoints <= 0) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "消费积分不能为空或小于0");
        }

        memberService.consumePoints(consumePoints);
        return R.ok();

    }


    /**
     * 根据会员等级和活动计算支付金额
     */
    @GetMapping("calculatePayment")
    @ApiOperation(value = "根据会员等级和活动计算支付金额")
    public R<Double> calculatePayment(@Valid @NotNull(message = "请选择会员") Long memberLevelId, @RequestParam(required = false) Long promotionId) {

        // 获取当前用户
        Long userId = SecurityUtils.getUserId();
        MemberPromotion memberPromotion = memberPromotionService.lambdaQuery()
                .eq(MemberPromotion::getUserId, userId)
                .eq(Objects.nonNull(promotionId), MemberPromotion::getPromotionId, promotionId)
                .eq(MemberPromotion::getStatus, PromotionEnum.PARTICIPATE)
                .one();

        if (Objects.nonNull(promotionId) && Objects.isNull(memberPromotion)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "未参与活动或已过期");
        }

        MemberLevel memberLevel = memberLevelService.getById(memberLevelId);
        Double unitPrice = memberLevel.getUnitPrice();
        unitPrice = memberService.calculatePayment(unitPrice, promotionId);
        return R.ok(unitPrice);
    }

    /**
     * 是否是会员
     */
    @GetMapping("isMember")
    @ApiOperation(value = "是否是会员")
    public R<Map<String, String>> isMember() {
        Long userId = SecurityUtils.getUserId();
        Map<String, String> map = new HashMap<>();
        Member member = memberService.getUseUserMemberByUserId(userId);
        if (Optional.ofNullable(member).isPresent()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = member.getStartDate();
            Date endDate = member.getEndDate();
            map.put("result", "1");
            map.put("startDate", sdf.format(startDate));
            map.put("endDate", sdf.format(endDate));
            return R.ok(map);
        }
        map.put("result", "0");

        return R.ok(map);
    }

}
