package com.hai.service.impl;

import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.BankNumberUtil;
import com.hai.config.HuaWeiSmsService;
import com.hai.dao.HighMerchantStoreAccountMapper;
import com.hai.entity.*;
import com.hai.enum_type.MerStoreAmountTypeEnum;
import com.hai.model.HighMerchantModel;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Service("merchantStoreAccountService")
public class HighMerchantStoreAccountServiceImpl implements HighMerchantStoreAccountService {

    @Resource
    private HighMerchantStoreAccountMapper merchantStoreAccountMapper;

    @Resource
    private HighMerchantService merchantService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighMerchantStoreAccountRecordService merchantStoreAccountRecordService;

    @Resource
    private SecUserLabelService userLabelService;

    @Resource
    private HuaWeiSmsService huaWeiSmsService;

    @Resource
    private UserCenter userCenter;

    @Override
    public void editStoreAccount(HighMerchantStoreAccount merchantStoreAccount) {
        if (merchantStoreAccount.getId() == null) {
            merchantStoreAccount.setAccountNo(BankNumberUtil.getBrankNumber("6"));
            merchantStoreAccount.setCreateTime(new Date());
            merchantStoreAccount.setUpdateTime(new Date());
            merchantStoreAccount.setStatus(1);
            merchantStoreAccountMapper.insert(merchantStoreAccount);
        } else {
            merchantStoreAccount.setUpdateTime(new Date());
            merchantStoreAccountMapper.updateByPrimaryKey(merchantStoreAccount);
        }
    }

    @Override
    public HighMerchantStoreAccount getStoreAccountDetail(Long storeId) {
        HighMerchantStoreAccountExample example = new HighMerchantStoreAccountExample();
        example.createCriteria().andStatusEqualTo(1).andStoreIdEqualTo(storeId);
        List<HighMerchantStoreAccount> list = merchantStoreAccountMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,isolation = Isolation.SERIALIZABLE,propagation= Propagation.REQUIRES_NEW)
    public void recharge(Long storeId, BigDecimal amount, Map<String, Object> otherParam) {
        // 查询门店
        HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(storeId);
        if (store == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的门店");
        }
        // 预存类型  0：非预存  1：预存
        if (!store.getPrestoreType().equals(1)) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "门店不属于预存类型");
        }
        // 查询商户
        HighMerchantModel merchant = merchantService.getMerchantById(store.getMerchantId());
        if (merchant == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        // 是否开通了账户
        HighMerchantStoreAccount account = getStoreAccountDetail(storeId);
        if (account == null) {
            account = new HighMerchantStoreAccount();
            account.setStoreId(storeId);
            account.setAmounts(new BigDecimal("0"));
        }
        // 变更前金额
        BigDecimal beforeAmount = account.getAmounts();
        // 计算金额
        account.setAmounts(account.getAmounts().add(amount));
        // 变更后金额
        BigDecimal afterAmount = account.getAmounts();

        if (!account.getAmountsEarlyWarning().equals(new BigDecimal("0"))
                && account.getAmounts().compareTo(account.getAmountsEarlyWarning()) == 1) {
            account.setAmountsEarlyWarningStatus(false);
        }
        editStoreAccount(account);

        HighMerchantStoreAccountRecord record = new HighMerchantStoreAccountRecord();
        record.setStoreAmountId(account.getId());
        record.setMerId(merchant.getId());
        record.setMerName(merchant.getMerchantName());
        record.setStoreId(store.getId());
        record.setStoreName(store.getStoreName());
        record.setAmount(amount);
        record.setBeforeAmount(beforeAmount);
        record.setAfterAmount(afterAmount);
        record.setType(MerStoreAmountTypeEnum.type1.getType());
        record.setSourceType(MapUtils.getInteger(otherParam, "sourceType"));
        record.setSourceId(MapUtils.getLong(otherParam, "sourceId"));
        record.setSourceContent(MapUtils.getString(otherParam, "sourceContent"));
        record.setOpUserId(MapUtils.getLong(otherParam, "opUserId"));
        record.setOpUserName(MapUtils.getString(otherParam, "opUserName"));
        merchantStoreAccountRecordService.editRecord(record);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,isolation = Isolation.SERIALIZABLE,propagation= Propagation.REQUIRES_NEW)
    public void consume(Long storeId, BigDecimal amount, Map<String, Object> otherParam) {
        // 查询门店
        HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(storeId);
        if (store == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的门店");
        }
        // 查询商户
        HighMerchantModel merchant = merchantService.getMerchantById(store.getMerchantId());
        if (merchant == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        // 是否开通了账户
        HighMerchantStoreAccount account = getStoreAccountDetail(storeId);
        if (account == null) {
            account = new HighMerchantStoreAccount();
            account.setStoreId(storeId);
            account.setAmounts(new BigDecimal("0"));
            editStoreAccount(account);
        }
/*        // 账户余额 是否小于 出账余额
        if (account.getAmounts().compareTo(amount) == -1) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "余额不足");
        }*/
        // 变更前金额
        BigDecimal beforeAmount = account.getAmounts();
        // 计算金额
        account.setAmounts(account.getAmounts().subtract(amount));
        // 变更后金额
        BigDecimal afterAmount = account.getAmounts();

        if (!account.getAmountsEarlyWarning().equals(new BigDecimal("0"))
                && account.getAmounts().compareTo(account.getAmountsEarlyWarning()) == -1) {
            account.setAmountsEarlyWarningStatus(true);

            List<Map<String, Object>> labelHfkjUserList = userLabelService.getUserByCompanyAndLabel(2L, 1L);
            for (Map<String, Object> labelUser : labelHfkjUserList) {
                // 发送短信
                huaWeiSmsService.sendGasPriceInsufficient(MapUtils.getString(labelUser, "telephone"), store.getStoreName());

            }

            List<Map<String, Object>> labelUserList = userLabelService.getUserByCompanyAndLabel(store.getCompanyId(), 1L);
            for (Map<String, Object> labelUser : labelUserList) {
                // 发送短信
                huaWeiSmsService.sendGasPriceInsufficient(MapUtils.getString(labelUser, "telephone"), store.getStoreName());
            }

        }
        editStoreAccount(account);

        HighMerchantStoreAccountRecord record = new HighMerchantStoreAccountRecord();
        record.setStoreAmountId(account.getId());
        record.setMerId(merchant.getId());
        record.setMerName(merchant.getMerchantName());
        record.setStoreId(store.getId());
        record.setStoreName(store.getStoreName());
        record.setAmount(amount);
        record.setBeforeAmount(beforeAmount);
        record.setAfterAmount(afterAmount);
        record.setType(MerStoreAmountTypeEnum.type2.getType());
        record.setSourceType(MapUtils.getInteger(otherParam, "sourceType"));
        record.setSourceId(MapUtils.getLong(otherParam, "sourceId"));
        record.setSourceContent(MapUtils.getString(otherParam, "sourceContent"));
        record.setOpUserId(MapUtils.getLong(otherParam, "opUserId"));
        record.setOpUserName(MapUtils.getString(otherParam, "opUserName"));
        merchantStoreAccountRecordService.editRecord(record);
    }
}
