package com.xhpc.activity.service.impl;

import com.xhpc.activity.domain.*;
import com.xhpc.activity.enums.ActivityTypeEnum;
import com.xhpc.activity.mapper.XhpcActivityCashMapper;
import com.xhpc.activity.mapper.XhpcActivityImgMapper;
import com.xhpc.activity.mapper.XhpcActivityRecordMapper;
import com.xhpc.activity.mapper.XhpcUserMapper;
import com.xhpc.activity.service.XhpcActivityCashService;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.web.service.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class XhpcActivityCashServiceImpl extends BaseService implements XhpcActivityCashService {


    @Resource
    XhpcActivityCashMapper cashMapper;

    @Resource
    XhpcActivityImgMapper imgMapper;

    @Resource
    XhpcActivityRecordMapper recordMapper;

    @Resource
    XhpcUserMapper userMapper;


    @Override
    public List<XhpcActivityCashDomain> getPage(Map<String, Object> params) {

        return cashMapper.selectByParams(params);
    }


    @Override
    public List<Map<String, Object>> getNameList(Map<String, Object> params) {
        return cashMapper.selectNameMapList(params);
    }

    @Override
    public XhpcActivityCashDomain getDomainByPk(Integer activityId) {
        XhpcActivityCashDomain domain = cashMapper.selectByPrimaryKey(activityId);
        List<XhpcActivityImgDomain> checkImgList = imgMapper.selectListByActivityId(activityId, ActivityTypeEnum.CASH.getCode());
        domain.setCheckImgList(checkImgList);
        return domain;
    }


    @Override
    public boolean insertDomain(XhpcActivityCashDomain domain) {

        cashMapper.insert(domain);
        for (XhpcActivityImgDomain imgDomain : domain.getCheckImgList()) {
            imgDomain.setActivityType(ActivityTypeEnum.CASH.getCode());
            imgDomain.setActivityId(domain.getActivityId());
            imgMapper.insert(imgDomain);
        }

        return true;
    }


    @Override
    public boolean updateDomain(XhpcActivityCashDomain domain) {
        cashMapper.updateByPrimaryKey(domain);

        imgMapper.deleteLogicByActivityId(domain.getActivityId(), ActivityTypeEnum.CASH.getCode());
        for (XhpcActivityImgDomain imgDomain : domain.getCheckImgList()) {
            imgDomain.setActivityType(ActivityTypeEnum.CASH.getCode());
            imgDomain.setActivityId(domain.getActivityId());
            imgMapper.insert(imgDomain);
        }
        return true;
    }


    @Override
    public boolean checkDomain(XhpcActivityCashDomain domain) {
        XhpcActivityCashDomain cashDomain = cashMapper.selectByPrimaryKey(domain.getActivityId());
        if (cashDomain == null) {
            throw new CustomException("活动不存在");
        }
        cashDomain.setStatus(domain.getStatus());
        cashDomain.setCheckBy(domain.getCheckBy());
        return cashMapper.checkByPrimaryKey(cashDomain) > 0;
    }


    @Override
    public boolean updateDomainStatus(XhpcActivityCashDomain domain) {
        return cashMapper.updateStatusByPrimaryKey(domain) > 0;
    }


    @Override
    public boolean deleteByPk(Integer activityId) {

        return cashMapper.deleteLogicByPrimaryKey(activityId) > 0;
    }


    @Override
    public List<Map<String, Object>> getUserList(Map<String, Object> params) {
        XhpcActivityCashDomain cashDomain = cashMapper.selectByPrimaryKey(Integer.parseInt(params.get("activityId").toString()));


        String appUserIds = "";
        if (cashDomain.getAppUserList() != null) {
            appUserIds = cashDomain.getAppUserList();
        }

        String comUserIds = "";
        if (cashDomain.getComUserList() != null) {
            comUserIds = cashDomain.getComUserList();
        }

        String bUserIds = "";
        if (cashDomain.getCusUserList() != null) {
            bUserIds = cashDomain.getCusUserList();
        }

        params.put("appUserIds", appUserIds);
        params.put("comUserIds", comUserIds);
        params.put("bUserIds", bUserIds);

        startPage();
        return cashMapper.selectUserListByParams(params);
    }


    // ---------- 红包领取 --------
    @Override
    public boolean insertReceiveDomain(XhpcActivityRecordDomain domain) {

        XhpcActivityCashDomain cashDomain = cashMapper.selectByPrimaryKey(domain.getActivityId());
        if (cashDomain == null) {
            throw new CustomException("活动不存在");
        }

        XhpcActivityRecordDomain recordDomain = recordMapper.selectByActivityAndUser(domain.getActivityType(),
                domain.getActivityId(), domain.getSource(), domain.getUserId());
        if (recordDomain != null) {
            throw new CustomException("您已参与该活动，请勿重复领取");
        }
        XhpcUserAccountStatementDomain accountStatementDomain = new XhpcUserAccountStatementDomain();
        BigDecimal amount = BigDecimal.ZERO;
        switch (domain.getSource()) {
            case 0:
                XhpcAppUserDomain appUser = userMapper.selectAppUserById(domain.getUserId());
                if (appUser == null) {
                    throw new CustomException("用户不存在");
                }
                amount = appUser.getBalance().add(cashDomain.getAmount());
                appUser.setBalance(amount);
                userMapper.updateAppUser(appUser);
                accountStatementDomain = addAccountStatement(appUser.getAppUserId(), cashDomain.getAmount(), amount, 0, appUser.getTenantId());
                break;
            case 2:
                XhpcCommunityPersonnelDomain comUser = userMapper.selectComUserById(domain.getUserId());
                if (comUser == null) {
                    throw new CustomException("用户不存在");
                }
                amount = comUser.getSurplusMoney().add(cashDomain.getAmount());
                comUser.setRedPacket(comUser.getRedPacket().add(cashDomain.getAmount()));
                comUser.setSurplusMoney(amount);
                userMapper.updateComUser(comUser);
                accountStatementDomain = addAccountStatement(comUser.getCommunityPersonnelId(), cashDomain.getAmount(), amount, 2, comUser.getTenantId());
                break;
            case 3:
                XhpcCustomersPersonnelDomain cusUser = userMapper.selectCusUserById(domain.getUserId());
                if (cusUser == null) {
                    throw new CustomException("用户不存在");
                }
                amount = cusUser.getSurplusMoney().add(cashDomain.getAmount());
                cusUser.setRedPacket(cusUser.getRedPacket().add(cashDomain.getAmount()));
                cusUser.setSurplusMoney(amount);
                userMapper.updateCusUser(cusUser);
                accountStatementDomain = addAccountStatement(cusUser.getCustomersPersonnelId(), cashDomain.getAmount(), amount, 3, cusUser.getTenantId());
                break;
            default:
                throw new CustomException("人员类型错误");
        }

        recordMapper.insert(domain);
        cashDomain.setReceiveCount(cashDomain.getReceiveCount() + 1);
        cashMapper.updateReceiveCountByActivityId(cashDomain);
        userMapper.insertStatement(accountStatementDomain);
        return true;
    }


    @Override
    public List<Map<String, Object>> getReceivePage(Map<String, Object> params) {
        params.put("activityType", ActivityTypeEnum.CASH.getCode());
        return recordMapper.selectByParams(params);
    }


    private XhpcActivityRecordDomain addRecord(XhpcActivityCashDomain cashDomain, Integer source, String userId) {
        XhpcActivityRecordDomain recordDomain = new XhpcActivityRecordDomain();
        recordDomain.setActivityType(ActivityTypeEnum.CASH.getCode());
        recordDomain.setActivityId(cashDomain.getActivityId());
        recordDomain.setAmount(cashDomain.getAmount());
        recordDomain.setSource(source);
        recordDomain.setUserId(userId);
        return recordDomain;
    }


    private XhpcUserAccountStatementDomain addAccountStatement(Long userId, BigDecimal amount, BigDecimal remainingSum, Integer source, String tenatnId) {
        XhpcUserAccountStatementDomain domain = new XhpcUserAccountStatementDomain();
        domain.setCreateBy("1");
        domain.setUpdateBy("1");
        domain.setType(4);
        domain.setStatus(0);

        domain.setUserId(userId);
        domain.setAmount(amount);
        domain.setRemainingSum(remainingSum);
        domain.setSource(source);
        domain.setTenantId(tenatnId);
        return domain;
    }
}
