/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.distribution.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.yami.shop.bean.distribution.UserShoppingDataDto;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.IdUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.OrderMapper;
import com.yami.shop.distribution.api.param.DistributionUserParam;
import com.yami.shop.distribution.comment.model.DistributionAuditingSet;
import com.yami.shop.distribution.comment.model.DistributionRecruitSet;
import com.yami.shop.distribution.comment.model.DistributionUser;
import com.yami.shop.distribution.comment.service.DistributionAuditingSetService;
import com.yami.shop.distribution.comment.service.DistributionRecruitSetService;
import com.yami.shop.distribution.comment.service.DistributionUserService;
import com.yami.shop.distribution.comment.vo.DistributionAuditingInfoVO;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.security.comment.service.AppConnectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;

/**
 * 分销邀请接口
 */
@Slf4j
@RestController
@RequestMapping("/p/distribution/register")
@Api(tags = "分销员注册接口")
@AllArgsConstructor
public class DistributionRegisterController {

    private final DistributionUserService distributionUserService;

    private final DistributionAuditingSetService distributionAuditingSetService;

    private final OrderMapper orderMapper;

    private final AppConnectService appConnectService;

    private final IdUtil idUtil;

    private final DistributionRecruitSetService distributionRecruitSetService;

    @GetMapping("/condition")
    @ApiOperation(value = "成为分销员所需要填写的信息")
    public ResponseEntity<DistributionAuditingInfoVO> getDistributionAuditingInfoVO(){
        DistributionAuditingSet distributionAuditingSet = distributionAuditingSetService.getByShopId();
        return ResponseEntity.ok(distributionAuditingSet.getAuditingInfo());
    }



    /**
     * 成为分销员
     */
    @PostMapping("/addDistributionUser")
    @ApiOperation(value = "申请成为分销员", notes = "申请成为分销员，返回分销员状态 0 待审核 1 正常")
    public ResponseEntity<Integer> addDistributionUser(@Valid @RequestBody DistributionUserParam distributionUserParam) {

        log.debug(Json.toJsonString(distributionUserParam));
        Long shopId = Constant.PLATFORM_SHOP_ID;
        DistributionRecruitSet distributionRecruitSet = distributionRecruitSetService.getByShopId();
        if (distributionRecruitSet.getState() == 0) {
            throw new GlobalException("推广计划已关闭");
        }
        // 店铺分销员审核设置
        DistributionAuditingSet distributionAuditingSet = distributionAuditingSetService.getByShopId();
        //判断传入的资料是否齐全
        DistributionAuditingInfoVO distributionAuditingInfoVO =distributionAuditingSet.getAuditingInfo();
        if(distributionAuditingInfoVO == null){
            throw new GlobalException("分销设置异常");
        }

        if(distributionAuditingInfoVO.getIdentityCardNumber()){
            if(!StrUtil.isNotBlank(distributionUserParam.getIdentityCardNumber())){
                throw new GlobalException("申请填写信息不全,需要身份证号");
            }
        }
        if(distributionAuditingInfoVO.getIdentityCardPic()){
            if(!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicBack())||!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicFront())||!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicHold())){
                throw new GlobalException("申请填写信息不全,需要身份证照片");
            }
        }
        if(distributionAuditingInfoVO.getRealName()){
            if(!StrUtil.isNotBlank(distributionUserParam.getRealName())){
                throw new GlobalException("申请填写信息不全,需要真实姓名");
            }
        }
        YamiUser user = SecurityUtils.getUser();
        String userId = user.getUserId();

        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, shopId);

        if (distributionUser != null) {
            if (distributionUser.getState() == 0) {
                throw new GlobalException("你已经提交过审核了,请耐心等待");
            }else if(distributionUser.getState() == -1){
                throw new GlobalException("封禁中不可申请,请联系管理员");
            }else if(distributionUser.getState() == 2){
                throw new GlobalException("已清退不可申请,请联系管理员");
            }else if (distributionUser.getState() == 1) {
                throw new GlobalException("你的审核已经通过,无需再次审核");
            }
        }


        distributionUser = new DistributionUser();
        distributionUser.setUserId(userId);
        distributionUser.setShopId(shopId);


        if (StrUtil.isNotBlank(distributionUserParam.getSharerCardNo())) {
            DistributionUser parentUser = distributionUserService.getByCardNo(distributionUserParam.getSharerCardNo());
            if (parentUser == null) {
                throw new GlobalException("无法获取邀请人信息");
            }
            if (!Objects.equals(parentUser.getShopId(),shopId)) {
                throw new GlobalException("邀请人店铺信息有误");
            }
            if (Objects.equals(parentUser.getUserId(), userId)) {
                throw new GlobalException("自己无法邀请自己");
            }

            //设置上级id
            distributionUser.setParentId(parentUser.getDistributionUserId());


            //设置上级ids
            if (parentUser.getParentId() == null) {
                distributionUser.setParentIds(StringUtils.join(StrUtil.COMMA, parentUser.getDistributionUserId(), StrUtil.COMMA));
            } else {
                distributionUser.setParentIds(StringUtils.join(parentUser.getParentIds(), parentUser.getDistributionUserId(), StrUtil.COMMA));
            }

            distributionUser.setGrade(parentUser.getGrade() + 1);
        } else {
            distributionUser.setGrade(0);
        }



        if (distributionAuditingSet.getAutoCheck() == 1) {
            //判断是否需要购买置指定商品
            if (CollectionUtil.isNotEmpty(distributionAuditingSet.getAuditingConditions().getProdList()) ) {
                boolean has = false;
                for (Long prodId: distributionAuditingSet.getAuditingConditions().getProdList()) {
                    // 判断有没有没有购买过指定商品
                    if (orderMapper.hasBuySuccessProd(prodId,distributionUser.getUserId()) > 0) {
                       has = true;
                       break;
                    }
                }
                if (!has) {
                    throw new GlobalException("不符合申请条件，请联系客服进行申请");
                }
            }

            UserShoppingDataDto userShoppingDataDto = orderMapper.calculateUserInShopData(shopId, userId);

            //判断是否需要消费金额条件
            if (distributionAuditingSet.getAuditingConditions().getExpenseAmount() != null) {
                if (userShoppingDataDto.getSumOfConsumption() == null) {
                    userShoppingDataDto.setSumOfConsumption(0.0);
                }
                if (userShoppingDataDto.getSumOfConsumption() < distributionAuditingSet.getAuditingConditions().getExpenseAmount()) {
                    throw new GlobalException("消费金额不符合要求");
                }
            }
            //判断是否需要达到消费笔数条件
            if (distributionAuditingSet.getAuditingConditions().getExpenseNumber() != null) {
                if (userShoppingDataDto.getExpenseNumber() < distributionAuditingSet.getAuditingConditions().getExpenseNumber()) {
                    throw new GlobalException("消费笔数不符合要求");
                }
            }
            //判断是否关注公众号
//            if (distributionAuditingSet.getAuditingConditions().getIsFocus()) {
//                AppConnect appConnect = appConnectService.getByBizUserId(user.getBizUserId(), App.MP);
//
//                if (appConnect == null) {
//                    throw new GlobalException("请先关注公众号");
//                }
//            }
            distributionUser.setState(1);
            distributionUser.setBindTime(new Date());
        } else {
            // 待审核
            distributionUser.setState(0);
        }

        //设置信息
        distributionUser.setUserMobile(distributionUserParam.getUserMobile());
        distributionUser.setRealName(distributionUserParam.getRealName());
        distributionUser.setIdentityCardNumber(distributionUserParam.getIdentityCardNumber());
        distributionUser.setIdentityCardPicFront(distributionUserParam.getIdentityCardPicFront());
        distributionUser.setIdentityCardPicHold(distributionUserParam.getIdentityCardPicHold());
        distributionUser.setIdentityCardPicBack(distributionUserParam.getIdentityCardPicBack());

        // level从1开始
        distributionUser.setLevel(1);
        //设置用户信息字段
        distributionUser.setNickName(user.getName());
        distributionUser.setPic(user.getPic());
        // 设置用户卡号
        distributionUser.setCardNo(idUtil.nextShortId());


        distributionUserService.registerDistributionUser(distributionUser);

        // 清除缓存
        distributionUserService.removeCacheByUserIdAndShopId(distributionUser.getUserId(),distributionUser.getShopId());
        distributionUserService.removeCacheByCardNo(distributionUser.getCardNo());
        return ResponseEntity.ok(distributionUser.getState());
    }

}
