package com.hai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.dao.HighGoldRecMapper;
import com.hai.dao.HighUserMapper;
import com.hai.entity.*;
import com.hai.enum_type.OilCardBindStatusEnum;
import com.hai.enum_type.UserCardType;
import com.hai.model.HighUserModel;
import com.hai.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Sum1Dream
 */
@Service("highUserServiceImpl")
public class HighUserServiceImpl implements HighUserService {

    @Resource
    private HighUserMapper highUserMapper;

    @Resource
    private HighGoldRecService highGoldRecService;

    @Resource
    private HighUserCouponService highUserCouponService;

    @Resource
    private OutRechargeOrderService outRechargeOrderService;

    @Resource
    private HighUserCardService highUserCardService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighUserPayPasswordService highUserPayPasswordService;

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighGoldRecMapper highGoldRecMapper;

    @Resource
    private HighOilCardService oilCardService;

    @Resource
    private BsDistributionUserRelService distributionUserRelService;

    @Override
    public List<HighUser> getListUser(Map<String, String> map) {
        HighUserExample example = new HighUserExample();
        HighUserExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(map.get("phone"))) {
            criteria.andPhoneLike("%" + map.get("phone") + "%");
        }
        if (StringUtils.isNotBlank(map.get("name"))) {
            criteria.andNameLike("%" + map.get("name") + "%");
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            criteria.andStatusEqualTo(Integer.valueOf(map.get("status")));
        }
        if (StringUtils.isNotBlank(map.get("ext4"))) {
            criteria.andExt4EqualTo(String.valueOf(map.get("ext4")));
        }
        if (StringUtils.isNotBlank(map.get("regTimeStart")) && StringUtils.isNotBlank(map.get("regTimeEnd"))) {
            criteria.andRegTimeBetween(
                    DateUtil.format(map.get("regTimeStart") , "yyyy-MM-dd HH:mm:ss") ,
                    DateUtil.format(map.get("regTimeEnd") , "yyyy-MM-dd HH:mm:ss"));
        }

        return highUserMapper.selectByExample(example);

    }

    @Override
    public HighUser findByUserId(Long userId) {
        return highUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public HighUser getDetailDataByUser(Long userId) {
        HighUser user = highUserMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return  null;
        }
        user.setUnusedCouponNum(highUserCouponService.getCouponList(userId, 1).size()); //未使用卡卷数量
        user.setUnpaid(highOrderService.countOrderByUserId(userId , 1));
        user.setOrderPayNum(highOrderService.countOrderByUserId(userId , 2));
        user.setWhetherCheckNum(highOrderService.whetherCheck(userId , 3));
        user.setRechargeOrderNum(outRechargeOrderService.rechargeOrderNum(userId));
        user.setUnusedDiscount(highOrderService.countUnusedDiscountByUserId(userId , 1));
        user.setIsSetPayPwd(highUserPayPasswordService.isSetPayPwd(userId));
        user.setIsSetHltCard(highUserCardService.isBindHtlCard(userId));
        user.setHltCardNo(highUserCardService.getUserHtlCardNo(userId));

        // 查询油卡
        List<HighUserCard> oilCardList = highUserCardService.getListByUser(userId, 2);
        if (oilCardList.size() > 0) {
            user.setIsSetOilCard(true);
            // 查询油卡
            HighOilCard oilCard = oilCardService.getOilCardByCardNo(oilCardList.get(0).getCardNo());
            if (oilCard != null) {
                Map<String, Object> oilCardMap = new HashMap<>();
                oilCardMap.put("cardNo", oilCard.getCardNo());
                oilCardMap.put("amount", oilCard.getAmount());
                user.setOilCard(oilCardMap);
            }
        } else {
            user.setIsSetOilCard(false);
        }

        return user;
    }

    @Override
    public HighUser findByOpenId(String openId) {
        HighUserExample example = new HighUserExample();
        example.createCriteria().andOpenIdEqualTo(openId).andStatusEqualTo(1);
        List<HighUser> list = highUserMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public HighUser findByOpenIdH5(String openId) {
        HighUserExample example = new HighUserExample();
        example.createCriteria().andOpenIdH5EqualTo(openId).andStatusEqualTo(1);
        List<HighUser> list = highUserMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public HighUser findByUnionId(String unionId) {
        HighUserExample example = new HighUserExample();
        example.createCriteria().andUnionIdEqualTo(unionId).andStatusEqualTo(1);
        List<HighUser> list = highUserMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public HighUser findByPhone(String phone) {
        HighUserExample example = new HighUserExample();
        example.createCriteria().andPhoneEqualTo(phone).andStatusEqualTo(1);
        List<HighUser> list = highUserMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public HighUser bindUserPhone(String phone, HttpServletRequest request) throws Exception {
        // 用户
        SessionObject sessionObject = userCenter.getSessionObject(request);
        HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
        HighUser highUser = findByUserId(userInfoModel.getHighUser().getId());
        if (highUser == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "未找到用户");
        }
        if (StringUtils.isNotBlank(highUser.getPhone())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已绑定手机号，请勿重复绑定");
        }

        // 查询手机号是否被绑定
        HighUser user = findByPhone(phone);
        if (user != null) {
            if (StringUtils.isNotBlank(user.getOpenId())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "手机号已被绑定");
            }
            highUser.setStatus(0);
            highUserMapper.updateByPrimaryKey(highUser);

            user.setGold(user.getGold() + highUser.getGold());
            user.setHeaderImg(highUser.getHeaderImg());
            user.setName(highUser.getName());
            user.setOpenId(highUser.getOpenId());
            user.setUnionId(highUser.getUnionId());

            // 用户信息完整状态
            // 0：完整
            // 1：需要填写用户信息
            // 2：需要填写手机
            if (user.getInfoCompleteStatus() == 2) {
                user.setInfoCompleteStatus(0);
            }
            highUserMapper.updateByPrimaryKey(user);
            return user;
        }
        highUser.setPhone(phone);
        highUserMapper.updateByPrimaryKey(highUser);
        return highUser;
    }

    @Override
    public void updateUser(HighUser highUser) {
        highUserMapper.updateByPrimaryKeySelective(highUser);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void insertUser(HighUser highUser , Long popularizeUserId , String regionId) {
        highUserMapper.insert(highUser);

        if (highUser.getPhone() != null) {
            HighOilCard oilCard = oilCardService.getOilCardByPhone(highUser.getPhone());
            if (oilCard != null && oilCard.getBindStatus().equals(OilCardBindStatusEnum.status0.getStatus())) {
                highUserCardService.bindCard(UserCardType.type2.getType(), oilCard.getCardNo(), highUser.getId());
            }
        }

        // 绑定推广关联关系
        distributionUserRelService.insertDistributionRebate(highUser.getId() ,  popularizeUserId , regionId);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void goldHandle(Long userId, Integer goldNum, Integer goldType, Integer resType, Long resId , String remark) {
        // 查询用户信息
        HighUser user = highUserMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "");
        }

        // 金币类型：1收入，2支出
        if (goldType == 1) {
            user.setGold(user.getGold() + goldNum);

        } else  if (goldType == 2) {
            if (goldNum > user.getGold()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "积分数量不足");
            }
            user.setGold(user.getGold() - goldNum);

        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户积分处理异常");
        }
        highUserMapper.updateByPrimaryKey(user);

        HighGoldRec highGoldRec = new HighGoldRec();
        highGoldRec.setUserId(user.getId());
        highGoldRec.setGoldType(goldType.longValue());
        highGoldRec.setGold(goldNum);
        highGoldRec.setCreateTime(new Date());
        highGoldRec.setResType(resType);
        highGoldRec.setResId(resId);
        highGoldRec.setStatus(1);
        highGoldRec.setRemark(remark);
        if (goldNum > 0) {
            highGoldRecService.insertGoldRec(highGoldRec);
        }

    }

    @Override
    public Long countUser() {
        HighUserExample example = new HighUserExample();
        return highUserMapper.countByExample(example);
    }

    @Override
    public Boolean findGoldRepeat(Integer resType, Long resId) {
        HighGoldRecExample example = new HighGoldRecExample();
        example.createCriteria().andResIdEqualTo(resId).andResTypeEqualTo(resType);
        return highGoldRecMapper.selectByExample(example).size() == 0;
    }

    @Override
    public JSONObject userDistributionStatistics(Long userId) {

        JSONObject object = new JSONObject();


        return null;
    }
}
