package com.ruoyi.mall.service.impl;

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

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.MallMemberCoupon;
import com.ruoyi.mall.domain.MallSalesman;
import com.ruoyi.mall.domain.vo.*;
import com.ruoyi.mall.mapper.MallGoodsProductMapper;
import com.ruoyi.mall.mapper.MallOrderOrderMapper;
import com.ruoyi.mall.mapper.MallSalesmanMapper;
import com.ruoyi.mall.service.IMallCouponService;
import com.ruoyi.mall.service.IMallFeedbackService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.mapper.MallMemberUserMapper;
import com.ruoyi.mall.domain.MallMemberUser;
import com.ruoyi.mall.service.IMallMemberUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 会员Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-25
 */
@Service
public class MallMemberUserServiceImpl implements IMallMemberUserService
{
    @Resource
    private MallMemberUserMapper mallMemberUserMapper;

    @Resource
    private IMallCouponService couponService;

    @Resource
    private MallGoodsProductMapper mallGoodsProductMapper;

    @Resource
    private MallSalesmanMapper mallSalesmanMapper;

    /**
     * 小程序手机号密码登录
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult memberUserLogin(Map<String, Object> param){
        String phone = MapUtils.getString(param, "phone");
        String password = MapUtils.getString(param, "password");

        //通过手机号查询用户
        MallMemberUser mallMemberUser = mallMemberUserMapper.queryByPhone(phone);
        if (ObjectUtils.isNotEmpty(mallMemberUser)){
            if ("1".equals(mallMemberUser.getStatus())){
                return ApiResult.error("此账号已被冻结");
            }
            if (SecurityUtils.matchesPassword(password,mallMemberUser.getPassword())){
                // 登陆记录
                MallMemberLoginLog mallMemberLoginLog = new MallMemberLoginLog();
                mallMemberLoginLog.setUserId(mallMemberUser.getId().intValue());
                mallMemberLoginLog.setLoginAt(DateUtils.getTime());
                mallMemberUserMapper.insertLoginLog(mallMemberLoginLog);

                //登陆时间
                mallMemberUser.setLoginAt(DateUtils.getTime());

                // if (mallMemberUser.getSalesmanId() == null) {
                //     List<MallSalesman> salesmanList = mallSalesmanMapper.selectMallSalesmanUserNumList();
                //     if (salesmanList.size() > 0) {
                //         mallMemberLoginLog.setSalesmanId(salesmanList.get(0).getId());
                //     }
                // }

                mallMemberUserMapper.updateMallMemberUser(mallMemberUser);

                mallMemberUser.setPassword("");
                return ApiResult.ok("登陆成功").put("data",mallMemberUser);
            }
        }

        return ApiResult.error("账号或密码错误");
    }

    /**
     * 找回密码
     * @param param
     * @return
     */
    @Override
    public ApiResult resetPassword(Map<String, Object> param){
        String phone = MapUtils.getString(param, "phone");
        String newPassword = MapUtils.getString(param, "newPassword");

        MallMemberUser memberUser = mallMemberUserMapper.queryByPhone(phone);
        if (ObjectUtils.isNotEmpty(memberUser)){
            if ("1".equals(memberUser.getStatus())){
                return ApiResult.error("此账号已被冻结");
            }

            memberUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            return ApiResult.toAjax(mallMemberUserMapper.updateMallMemberUser(memberUser));
        }
        return ApiResult.error("此手机号未注册");
    }

    /**
     * 查询会员
     *
     * @param id 会员主键
     * @return 会员
     */
    @Override
    public MallMemberUser selectMallMemberUserById(Long id)
    {
        return mallMemberUserMapper.selectMallMemberUserById(id);
    }

    @Override
    public List<MallMemberUser> selectBossMemberUser() {
        return mallMemberUserMapper.selectBossMemberUser();
    }

    @Override
    public MallMemberUser queryByOpenid(String openid) {
        return mallMemberUserMapper.queryByOpenid(openid);
    }
    @Override
    public MallMemberUser queryByPhone(String phone) {
        return mallMemberUserMapper.queryByPhone(phone);
    }

    /**
     * 查询会员列表
     *
     * @param mallMemberUser 会员
     * @return 会员
     */
    @Override
    public List<MallMemberUser> selectMallMemberUserList(MallMemberUser mallMemberUser)
    {
        return mallMemberUserMapper.selectMallMemberUserList(mallMemberUser);
    }

    /**
     * 新增会员
     *
     * @param mallMemberUser 会员
     * @return 结果
     */
    @Override
    public int insertMallMemberUser(MallMemberUser mallMemberUser)
    {
        // 设置业务员绑定时间
        if (mallMemberUser.getSalesmanId() != null){
            mallMemberUser.setBindingAt(DateUtils.getTime());
        }
        mallMemberUser.setPassword(SecurityUtils.encryptPassword("123456"));
        mallMemberUser.setCreateAt(DateUtils.getTime());
        return mallMemberUserMapper.insertMallMemberUser(mallMemberUser);
    }


    /**
     * 修改会员
     *
     * @param mallMemberUser 会员
     * @return 结果
     */
    @Override
    public int updateMallMemberUser(MallMemberUser mallMemberUser)
    {
        MallMemberUser memberUser = mallMemberUserMapper.selectMallMemberUserById(mallMemberUser.getId());
        // 如果业务员id与原来的不相等，则重置绑定时间
        if (mallMemberUser.getSalesmanId() != null && (!mallMemberUser.getSalesmanId().equals(memberUser.getSalesmanId()))){
            mallMemberUser.setBindingAt(DateUtils.getTime());
        }

        return mallMemberUserMapper.updateMallMemberUser(mallMemberUser);
    }

    /**
     * 批量删除会员
     *
     * @param ids 需要删除的会员主键
     * @return 结果
     */
    @Override
    public int deleteMallMemberUserByIds(Long[] ids)
    {
        return mallMemberUserMapper.deleteMallMemberUserByIds(ids);
    }

    /**
     * 删除会员信息
     *
     * @param id 会员主键
     * @return 结果
     */
    @Override
    public int deleteMallMemberUserById(Long id)
    {
        return mallMemberUserMapper.deleteMallMemberUserById(id);
    }

    @Override
    public MemberUserVO selectMemberVOUserById(Long l) {
        return mallMemberUserMapper.selectMemberVOUserById(l);
    }

    @Override
    public int selectCollectCount(Map<String, Object> params) {
        return mallMemberUserMapper.selectCollectCount(params);
    }

    @Override
    public void insertMemberGoods(MemberCollectVO memberGoods) {
        mallMemberUserMapper.insertMemberGoods(memberGoods);
    }

    @Override
    public void deleteMemberGoodsByParam(Map<String, Object> params) {
        mallMemberUserMapper.deleteMemberGoodsByParam(params);
    }

    @Override
    public PageInfo<IndexGoodsVO> queryByUserId(Map<String, Object> params) {
        PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString()));

        List<IndexGoodsVO> list = mallMemberUserMapper.queryCollectByUserUserId(Long.parseLong(params.get("userId").toString()));
        if (list.size() > 0){
            for (IndexGoodsVO indexGoodsVO : list) {
                Long goodsId = indexGoodsVO.getId();
                //规格列表
                indexGoodsVO.setProList(mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(goodsId));
            }
        }
        PageInfo<IndexGoodsVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public ApiResult deleteCollectByGoodsIds(Map<String, Object> params) {
        List<Integer> ids = JSONObject.parseArray(params.get("ids").toString(), Integer.class);

        if (ids.size() > 0){
            return ApiResult.toAjax(mallMemberUserMapper.deleteCollectByGoodsIds(ids,MapUtils.getInteger(params,"userId")));
        }
        return ApiResult.ok();
    }

    @Override
    public PageInfo<IndexGoodsVO> queryFoodMarkByUserId(Map<String, Object> params) {
        PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()),Integer.parseInt(params.get("pageSize").toString()));

        List<IndexGoodsVO> list = mallMemberUserMapper.queryFoodMarkByUserUserId(Long.parseLong(params.get("userId").toString()));
        PageInfo<IndexGoodsVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void insertIntoFoodMarkBD(Map<String, Object> params) {
        MemberFootMarkVO foodMarkVO = new MemberFootMarkVO();
        foodMarkVO.setGoodsId(Long.parseLong(params.get("goodsId").toString()));
        foodMarkVO.setMemberId(Long.parseLong(params.get("userId").toString()));
        MemberFootMarkVO result = mallMemberUserMapper.selectFootMarkVOUserById(foodMarkVO);
        if (ObjectUtils.isNotEmpty(result)){
            result.setUpdateTime(DateUtils.getTime());
            mallMemberUserMapper.updateFootMarkVO(result);
        }else {
            foodMarkVO.setUpdateTime(DateUtils.getTime());
            mallMemberUserMapper.insetIntoFootMarkVO(foodMarkVO);
        }
    }

    @Override
    public MemberCollectVO selectIsCollectBy(MemberCollectVO collectVO) {

        return mallMemberUserMapper.selectIsCollectBy(collectVO);
    }

    @Override
    public Map<String, Object> checkUserCoupon(Long userId, String couponId) {
        return mallMemberUserMapper.checkUserCoupon(userId,couponId);
    }

    @Override
    public void insertUserCoupon(MallMemberCoupon memberCoupon) {
        mallMemberUserMapper.insertUserCoupon(memberCoupon);
    }

    @Override
    public List<MallMemberCoupon> getMyCoupons(Long userId) {
        return mallMemberUserMapper.getMyCoupons(userId);
    }

    @Override
    public List<MallMemberCoupon> getEnableCoupons(Map<String,Object> param) {
        return mallMemberUserMapper.getEnableCoupons(param);
    }

    @Override
    public Map<String, Object> checkCouponUsed(String couponId, Long userId) {
        return mallMemberUserMapper.checkCouponUsed(couponId,userId);
    }

    @Override
    public MallMemberCoupon checkCouponUsedNew(Long couponId, Long userId) {
        return mallMemberUserMapper.checkCouponUsedNew(couponId, userId);
    }

    @Override
    public void updateCouponUsed(String couponId, Long userId) {
        mallMemberUserMapper.updateCouponUsed(couponId,userId);
    }

    @Override
    public Map<String, Object> getMyRecordCount(Long userId) {
        int collectCount = mallMemberUserMapper.selectCollectCountByUserId(userId);
        int couponCount = mallMemberUserMapper.selectCouponCountByUserId(userId);
        int footCount = mallMemberUserMapper.selectFootCountByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("collectCount",collectCount);
        map.put("couponCount",couponCount);
        map.put("footCount",footCount);
        return map;
    }

    /**
     * 查询会员未下单天数（订单须付款）
     *
     * @param userId 会员主键
     * @return 会员
     */
    @Override
    public int queryNoOrderDaysByUserId(Long userId) {
        return mallMemberUserMapper.queryNoOrderDaysByUserId(userId);
    }

    /**
     * 业务员查询名下客户
     *
     * @param params salesmanId 业务员ID
     * @return 会员集合
     */
    @Override
    public List<Map<String, Object>> getSalesmanUserList(Map<String, Object> params) {
        return mallMemberUserMapper.getSalesmanUserList(params);
    }

    /**
     * 用户积分列表
     *
     * @param params userId 用户ID
     * @return 积分集合
     */
    @Override
    public List<Map<String, Object>> getUserIntegralList(Map<String, Object> params) {
        return mallMemberUserMapper.getUserIntegralList(params);
    }

    /**
     * 用户总积分
     *
     * @param params userId 用户ID
     * @return 用户总积分
     */
    @Override
    public BigDecimal getUserAllIntegral(Map<String, Object> params) {
        return mallMemberUserMapper.getUserAllIntegral(params);
    }
}
