package com.fs.store.service.impl;

import java.math.BigDecimal;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.fs.common.utils.DateUtils;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStoreOrderItem;
import com.fs.store.domain.FsUserBill;
import com.fs.store.dto.FsStoreCartDTO;
import com.fs.store.enums.BillDetailEnum;
import com.fs.store.mapper.FsStoreOrderMapper;
import com.fs.store.mapper.FsStoreProductAttrValueMapper;
import com.fs.store.mapper.FsUserTuiMoneyRankMapper;
import com.fs.store.service.IFsUserBillService;
import com.fs.store.vo.FsUserListVO;
import com.fs.store.vo.FsUserVO;
import com.fs.store.vo.FsCompanyUserListQueryVO;
import com.fs.store.vo.FsUserShareVO;
import com.fs.store.vo.FsUserTuiVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.store.mapper.FsUserMapper;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import org.springframework.transaction.annotation.Transactional;

import static com.fs.store.enums.BillDetailEnum.CATEGORY_1;
import static com.fs.store.enums.BillDetailEnum.CATEGORY_3;

/**
 * 用户Service业务层处理
 *
 * @author fs
 * @date 2022-03-15
 */
@Service
public class FsUserServiceImpl implements IFsUserService
{
    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private FsStoreProductAttrValueMapper storeProductAttrValueMapper;

    @Autowired
    private IFsUserBillService billService;
    @Autowired
    private FsStoreOrderMapper storeOrderMapper;

    Logger logger =  LoggerFactory.getLogger(FsUserServiceImpl.class);
    /**
     * 查询用户
     *
     * @param userId 用户ID
     * @return 用户
     */
    @Override
    public FsUser selectFsUserById(Long userId)
    {
        return fsUserMapper.selectFsUserById(userId);
    }


    @Override
    public FsUserVO selectFsUserByUserId(Long userId) {
        return fsUserMapper.selectFsUserByUserId(userId);
    }

    /**
     * 查询用户列表
     *
     * @param fsUser 用户
     * @return 用户
     */
    @Override
    public List<FsUser> selectFsUserList(FsUser fsUser)
    {
        return fsUserMapper.selectFsUserList(fsUser);
    }


    @Override
    public List<FsUserListVO> selectFsUserVOList(FsUser fsUser) {
        return fsUserMapper.selectFsUserVOList(fsUser);
    }

    /**
     * 新增用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    public int insertFsUser(FsUser fsUser)
    {
        fsUser.setCreateTime(DateUtils.getNowDate());
        return fsUserMapper.insertFsUser(fsUser);
    }

    /**
     * 修改用户
     *
     * @param fsUser 用户
     * @return 结果
     */
    @Override
    public int updateFsUser(FsUser fsUser)
    {
        fsUser.setUpdateTime(DateUtils.getNowDate());
        return fsUserMapper.updateFsUser(fsUser);
    }

    /**
     * 批量删除用户
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteFsUserByIds(Long[] userIds)
    {
        return fsUserMapper.deleteFsUserByIds(userIds);
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteFsUserById(Long userId)
    {
        return fsUserMapper.deleteFsUserById(userId);
    }

    @Override
    public int decIntegral(Long uid, double usedIntegral) {
        return fsUserMapper.decIntegral(uid,usedIntegral);
    }

    @Override
    public int incPayCount(Long userId) {
        return fsUserMapper.incPayCount(userId);
    }

    @Override
    public FsUser selectFsUserByPhone(String phone) {
        return fsUserMapper.selectFsUserByPhone(phone);
    }

    @Override
    public List<FsCompanyUserListQueryVO> selectFsCompanyUserListQuery(FsUser fsUser) {
        return fsUserMapper.selectFsCompanyUserListQuery(fsUser);
    }

    @Override
    public List<FsUserTuiVO> selectFsUserTuiList(String userId) {
        return fsUserMapper.selectFsUserTuiList(userId);
    }

    @Override
    public Long selectFsUserCount(int type,Long companyId) {
        return fsUserMapper.selectFsUserCount(type,companyId);
    }

    @Override
    @Transactional
    public void     addTuiMoney(FsStoreOrder order , List<FsStoreOrderItem> items) {
        //更新推荐人
//        FsUser user= fsUserMapper.selectFsUserById(order.getUserId());
//        if(user.getSpreadUserId()==null||user.getSpreadUserId()==0){
//            FsUser userMap=new FsUser();
//            userMap.setUserId(user.getUserId());
//            userMap.setSpreadUserId(order.getTuiUserId());
//            userMap.setIsPromoter(1);
//            fsUserMapper.updateFsUser(userMap);
//        }
        //获取一级二级佣金
        BigDecimal brokerage=BigDecimal.ZERO;
        BigDecimal brokerageTwo=BigDecimal.ZERO;
        BigDecimal brokerageThree=BigDecimal.ZERO;
        try {
            for(FsStoreOrderItem item: items){
                FsStoreCartDTO cartDTO= JSONUtil.toBean(item.getJsonInfo(),FsStoreCartDTO.class);
                if(cartDTO.getBrokerage()!=null){
                    brokerage=brokerage.add(cartDTO.getBrokerage().multiply(new BigDecimal(cartDTO.getNum().toString())));
                }
                if(cartDTO.getBrokerageTwo()!=null){
                    brokerageTwo=brokerageTwo.add(cartDTO.getBrokerageTwo().multiply(new BigDecimal(cartDTO.getNum().toString())));
                }
                if(cartDTO.getBrokerageThree()!=null){
                    brokerageThree= brokerageThree.add(cartDTO.getBrokerageThree().multiply(new BigDecimal(cartDTO.getNum().toString()))) ;
                }
            }
            //返佣金
            FsUser tuiUser=null;
            //如果推广员是自己，一级拿佣金
            FsUser user= fsUserMapper.selectFsUserById(order.getUserId());
            if(user.getIsPromoter().equals(1)){
                logger.info("拿一级佣金："+user.getUserId());
                tuiUser=user;
            }
            else{
                tuiUser= fsUserMapper.selectFsUserById(order.getTuiUserId());
                logger.info("else拿一级佣金："+tuiUser.getUserId());
            }
            //一级
            if(tuiUser!=null&&tuiUser.getIsPromoter()==1){
                if(brokerage.compareTo(BigDecimal.ZERO)==1){
                    FsUser tuiUserMap=new FsUser();
                    tuiUserMap.setUserId(tuiUser.getUserId());
                    tuiUserMap.setBrokeragePrice(tuiUser.getBrokeragePrice().add(brokerage));
                    fsUserMapper.updateFsUser(tuiUserMap);
                    logger.info("拿一级佣金："+tuiUserMap.getUserId()+":"+brokerage);
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerage.doubleValue(),tuiUserMap.getBrokeragePrice().doubleValue(),"订单返佣金",order.getId().toString(),order.getUserId());
                }
            }
            //二级返
            if(tuiUser!=null){
                FsUser tuiUserTwo= fsUserMapper.selectFsUserById(tuiUser.getSpreadUserId());
                if(tuiUserTwo!=null&&tuiUserTwo.getIsPromoter()==1){
                    if(brokerageTwo.compareTo(BigDecimal.ZERO)==1){
                        FsUser tuiUserTwoMap=new FsUser();
                        tuiUserTwoMap.setUserId(tuiUserTwo.getUserId());
                        tuiUserTwoMap.setBrokeragePrice(tuiUserTwo.getBrokeragePrice().add(brokerageTwo));
                        fsUserMapper.updateFsUser(tuiUserTwoMap);
                        logger.info("拿二级佣金："+tuiUserTwoMap.getUserId()+":"+brokerageTwo);
                        billService.addBill(tuiUserTwoMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerageTwo.doubleValue(),tuiUserTwoMap.getBrokeragePrice().doubleValue(),"订单返佣金",order.getId().toString(),tuiUser.getUserId());
                    }
                    //三级
                    FsUser tuiUserThree= fsUserMapper.selectFsUserById(tuiUserTwo.getSpreadUserId());
                    if(tuiUserThree!=null&&tuiUserThree.getIsPromoter()==1){
                        if(brokerageThree.compareTo(BigDecimal.ZERO)==1){
                            FsUser tuiUserThreeMap=new FsUser();
                            tuiUserThreeMap.setUserId(tuiUserThree.getUserId());
                            tuiUserThreeMap.setBrokeragePrice(tuiUserThree.getBrokeragePrice().add(brokerageThree));
                            fsUserMapper.updateFsUser(tuiUserThreeMap);
                            logger.info("拿三级佣金："+tuiUserThreeMap.getUserId()+":"+brokerageThree);
                            billService.addBill(tuiUserThreeMap.getUserId(), CATEGORY_3.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),brokerageThree.doubleValue(),tuiUserThreeMap.getBrokeragePrice().doubleValue(),"订单返佣金",order.getId().toString(),tuiUser.getUserId());
                        }

                    }
                }

            }


        }
        catch (Exception e){

        }
    }

    @Override
    @Transactional
    public void subTuiMoney(FsStoreOrder order) {
        FsUserBill map=new FsUserBill();
        map.setCategory(CATEGORY_3.getValue());
        map.setBusinessId(order.getId().toString());
        map.setBillType(1);
        List<FsUserBill> list=billService.selectFsUserBillList(map);
        if(list!=null&&list.size()>0){
            for(FsUserBill bill:list){
                FsUser tuiUser= fsUserMapper.selectFsUserByIdForUpdate(bill.getUserId());
                if(tuiUser!=null){
                    FsUser tuiUserMap=new FsUser();
                    tuiUserMap.setUserId(tuiUser.getUserId());
                    tuiUserMap.setBrokeragePrice(tuiUser.getBrokeragePrice().subtract(new BigDecimal(bill.getNumber())));
                    fsUserMapper.updateFsUser(tuiUserMap);
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),0,BillDetailEnum.TYPE_6.getDesc(),bill.getNumber().doubleValue(),tuiUserMap.getBrokeragePrice().doubleValue(),"订单退佣金",order.getId().toString(),bill.getTuiUserId());
                }
            }
        }

    }

    @Override
    @Transactional
    public void addMoney(FsStoreOrder order) {
        FsUserBill map=new FsUserBill();
        map.setCategory(CATEGORY_3.getValue());
        map.setBusinessId(order.getId().toString());
        map.setBillType(1);
        List<FsUserBill> list=billService.selectFsUserBillList(map);
        if(list!=null&&list.size()>0){
            for(FsUserBill bill:list){
                FsUser tuiUser= fsUserMapper.selectFsUserByIdForUpdate(bill.getUserId());
                if(tuiUser!=null){
                    FsUser tuiUserMap=new FsUser();
                    tuiUserMap.setUserId(tuiUser.getUserId());
                    tuiUserMap.setNowMoney(tuiUser.getNowMoney().add(new BigDecimal(bill.getNumber())));
                    tuiUserMap.setBrokeragePrice(tuiUser.getBrokeragePrice().subtract(new BigDecimal(bill.getNumber())));
                    fsUserMapper.updateFsUser(tuiUserMap);
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_3.getValue(),0,BillDetailEnum.TYPE_6.getDesc(),bill.getNumber().doubleValue(),tuiUserMap.getBrokeragePrice().doubleValue(),"订单分佣金",order.getId().toString(),bill.getTuiUserId());
                    billService.addBill(tuiUserMap.getUserId(), CATEGORY_1.getValue(),1,BillDetailEnum.TYPE_5.getDesc(),bill.getNumber().doubleValue(),tuiUserMap.getNowMoney().doubleValue(),"订单分佣金",order.getId().toString(),bill.getTuiUserId());
                }
            }
        }
        FsStoreOrder orderMap=new FsStoreOrder();
        orderMap.setId(order.getId());
        orderMap.setTuiUserMoneyStatus(1);
        storeOrderMapper.updateFsStoreOrder(orderMap);
    }

    @Override
    public FsUser selectFsUserByMaOpenId(String openid) {
        return fsUserMapper.selectFsUserByMaOpenId(openid);
    }

    @Override
    public FsUser selectFsUserByMpOpenId(String openid) {
        return fsUserMapper.selectFsUserByMpOpenId(openid);
    }

    @Override
    public FsUser selectFsUserByUnionId(String unionId) {
        return fsUserMapper.selectFsUserByUnionId(unionId);
    }

    @Override
    public FsUser selectFsUserByUserCode(String userCode) {
        return fsUserMapper.selectFsUserByUserCode(userCode);
    }
    @Autowired
    FsUserTuiMoneyRankMapper fsUserTuiMoneyRankMapper;

    @Override
    public List<FsUserShareVO> selectFsUserShareList(String userId,Integer type) {
        if (type==null||type==0){
            type=3;
        }
        return fsUserTuiMoneyRankMapper.selectFsUserShareList(type);
    }


}
