package com.fzm.mall.server.admin.finance_center.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.chain.FzmChain;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.finance_center.entity.dto.*;
import com.fzm.mall.server.admin.finance_center.entity.vo.BaseIntegralDetailVO;
import com.fzm.mall.server.admin.finance_center.entity.vo.IntegralDetailVO;
import com.fzm.mall.server.admin.finance_center.entity.vo.IntegralListVO;
import com.fzm.mall.server.admin.finance_center.enums.status.AssetsFlowStatusEnum;
import com.fzm.mall.server.admin.finance_center.enums.status.IsDelStatusEnum;
import com.fzm.mall.server.admin.finance_center.enums.status.MerchantIntegralStatusEnum;
import com.fzm.mall.server.admin.finance_center.enums.type.AssetsFlowTypeEnum;
import com.fzm.mall.server.admin.finance_center.enums.type.MerchantIntegralTypeEnum;
import com.fzm.mall.server.admin.finance_center.mapper.MerchantIntegralMapper;
import com.fzm.mall.server.admin.finance_center.model.MerchantAssets;
import com.fzm.mall.server.admin.finance_center.model.MerchantAssetsFlow;
import com.fzm.mall.server.admin.finance_center.model.MerchantIntegral;
import com.fzm.mall.server.admin.finance_center.service.IMerchantAssetsService;
import com.fzm.mall.server.admin.finance_center.service.IMerchantIntegralService;
import com.fzm.mall.server.admin.home_page.model.Merchant;
import com.fzm.mall.server.admin.home_page.service.IMerchantService;
import com.fzm.mall.server.admin.mq.MsgProducer;
import com.fzm.mall.server.admin.mq.enums.QueueTTLTypeEnum;
import com.fzm.mall.server.admin.user_center.model.User;
import com.fzm.mall.server.admin.user_center.service.IUserService;
import com.fzm.mall.server.admin.util.ExcelUtil;
import com.fzm.mall.server.admin.util.UUIDUtil;
import lombok.RequiredArgsConstructor;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author wangp
 * @date 2021/4/27 15:53
 * @description 服务实现类
 * @since JDK 1.8
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MerchantIntegralServiceImpl extends ServiceImpl<MerchantIntegralMapper, MerchantIntegral> implements IMerchantIntegralService {
    private final DozerBeanMapper beanMapper;
    private final IMerchantService merchantService;
    private final FzmChain fzmChain;
    private final IUserService userService;
    private final MsgProducer producer;
    private final IMerchantAssetsService merchantAssetsService;

    @Override
    public void issueMerchantIntegral(MerchantIntegralDTO dto, String merchantId) {
        Merchant merchant = merchantService.getByMerchantId(merchantId);
        String addr = merchant.getTokenIssueAddr();

        //判断是否发行过
        if (fzmChain.coinExist(dto.getLabel())) {
            throw new MyException(MallResponseError.COIN_EXIST_ERROR);
        }

        MerchantIntegral integral = beanMapper.map(dto, MerchantIntegral.class);
        integral.setMerchantId(merchantId);
        integral.setBalanceNum(integral.getIssueNum());
        integral.setIssueAddr(addr);
        integral.setType(MerchantIntegralTypeEnum.MERCHANT.getType());
        integral.setStatus(MerchantIntegralStatusEnum.ISSUING.getStatus());
        integral.setIsDel(IsDelStatusEnum.NO.getStatus());

        if (!save(integral)) {
            throw new MyException(MallResponseError.SAVE_ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("coin", dto.getLabel());
        map.put("amount", dto.getIssueNum().intValue());
        map.put("tokenAddr", addr);
        map.put("merchantId", merchantId);

        //异步发行token
        producer.sendTTL(map, QueueTTLTypeEnum.ISSUE_MERCHANT_INTEGRAL_TTL, 5 * 1000);
    }

    @Override
    public IntegralDetailVO queryByMerchantId(String merchantId) {
        MerchantIntegral integral = baseMapper.queryByMerchantId(merchantId);

        /*LambdaQueryWrapper<MerchantIntegral> qw = new LambdaQueryWrapper<>();
        qw
                .eq(MerchantIntegral::getMerchantId, merchantId)
                .eq(MerchantIntegral::getIsDel, IsDelStatusEnum.NO.getStatus());
        MerchantIntegral integral = getOne(qw);*/

        if (integral == null)
            return null;

        IntegralDetailVO vo = beanMapper.map(integral, IntegralDetailVO.class);
        vo.setAccount(integral.getIssueAddr());
        return vo;
    }

    @Override
    public IPage<IntegralListVO> page(String merchantId, String label, String merchantName, Integer status, Integer pageNum, Integer pageSize) {
        IPage<IntegralListVO> page = new Page<>(pageNum, pageSize);
        return baseMapper.page(page, label, merchantName, status);
    }

    @Override
    public void setRatio(IntegralExchangeRatioDTO dto) {
        UpdateWrapper<MerchantIntegral> uw = new UpdateWrapper<>();
        uw.lambda()
                .set(MerchantIntegral::getMerchantRatio, dto.getMerchantRatio())
                .set(MerchantIntegral::getBaseRatio, dto.getBaseRatio())
                .eq(MerchantIntegral::getLabel, dto.getLabel())
                .eq(MerchantIntegral::getIsDel, IsDelStatusEnum.NO.getStatus());
        if (!update(uw)) {
            throw new MyException(MallResponseError.UPDATE_ERROR);
        }
    }

    @Override
    public void check(IntegralCheckDTO checkDTO) {
        Integer status = MerchantIntegralStatusEnum.ABLE.getStatus();
        String label = checkDTO.getLabel();

        MerchantIntegral integral = baseMapper.queryByLabel(label);

        integral.setStatus(checkDTO.getStatus());
        integral.setFailReason(checkDTO.getFailReason());
        updateById(integral);

        if (checkDTO.getStatus().equals(status)) {
            //商户资产
            MerchantAssets merchantAssets = new MerchantAssets(
                    integral.getMerchantId(),
                    integral.getIssueAddr(),
                    label,
                    integral.getIssueNum()
            );
            //更新商户资产
            merchantAssetsService.save(merchantAssets);
        }
    }

    @Override
    public void disable(IntegralDisableDTO disableDTO) {
        UpdateWrapper<MerchantIntegral> uw = new UpdateWrapper<>();
        uw.lambda()
                .set(MerchantIntegral::getStatus, disableDTO.getStatus())
                .eq(MerchantIntegral::getLabel, disableDTO.getLabel())
                .eq(MerchantIntegral::getIsDel, IsDelStatusEnum.NO.getStatus());
        if (!update(uw)) {
            throw new MyException(MallResponseError.UPDATE_ERROR);
        }
    }

    @Override
    public void merchantTransSingle(TransferAccountsDTO dto, String merchantId, boolean isBase) {
        Merchant merchant = merchantService.getByMerchantId(merchantId);
        String tokenIssueAddr = merchant.getTokenIssueAddr();
        String issueAddrKey = merchant.getIssueAddrKey();

        MerchantAssets merchantAssets = merchantAssetsService.queryByMerchantIdAndCoin(merchantId, isBase);
        String label = merchantAssets.getCoin();
        BigDecimal balanceNum = merchantAssets.getAmount();

        String phone = dto.getPhone();
        BigDecimal amount = dto.getAmount();
        String userAddr = "";
        String uid = "";

        if (balanceNum.compareTo(amount) == -1) {
            throw new MyException(MallResponseError.BALANCE_NOT_ENOUGH_ERROR);
        }

        User user = userService.queryByPhone(phone);
        if (user == null) {
            throw new MyException(MallResponseError.USER_NOT_EXIST_OR_LOCKING);
        } else {
            userAddr = user.getAddress();
            uid = user.getUid();
        }

        //发出转账请求，获得交易hash
        String hash = fzmChain.tranTokenHash(tokenIssueAddr, issueAddrKey, userAddr, amount, label);

        //轮询确认，异步执行
        Map<String, Object> map = new HashMap<>();
        map.put("hash", hash);
        map.put("tokenIssueAddr", tokenIssueAddr);
        map.put("userAddr", userAddr);
        map.put("amount", amount);
        map.put("label", label);
        map.put("merchantId", merchantId);
        map.put("uid", uid);

        //异步发行token
        producer.sendTTL(map, QueueTTLTypeEnum.MERCHANT_INTEGRAL_TRAN_TTL, 5 * 1000);
    }

    @Override
    public void merchantTransBatch(String path, String merchantId, boolean isBase) {
        MerchantAssets merchantAssets = merchantAssetsService.queryByMerchantIdAndCoin(merchantId, isBase);

        List<Map<String, String>> maps = ExcelUtil.analysisExcel(path);
        BigDecimal amountAll = BigDecimal.ZERO;

        System.err.println("maps:" + maps);

        for (Map<String, String> map : maps) {
            String phone = map.get("phone");
            BigDecimal amount = new BigDecimal(map.get("amount"));
            User user = userService.queryByPhone(phone);
            if (user == null) {
                throw new MyException(MallResponseError.USER_NOT_EXIST_OR_LOCKING);
            }
            amountAll = amountAll.add(amount);
        }

        if (merchantAssets.getAmount().compareTo(amountAll) == -1) {
            throw new MyException(MallResponseError.BALANCE_NOT_ENOUGH_ERROR);
        }


        for (Map<String, String> map : maps) {
            System.err.println("map:" + map);

            String phone = map.get("phone");
            BigDecimal amount = new BigDecimal(map.get("amount"));
            TransferAccountsDTO dto = new TransferAccountsDTO(phone, amount);
            merchantTransSingle(dto, merchantId, isBase);
        }
    }

    @Override
    public void updateStatusByMerchantId(String merchantId, Integer status, String errMsg) {
        UpdateWrapper<MerchantIntegral> uw = new UpdateWrapper<>();
        uw.lambda()
                .set(MerchantIntegral::getStatus, status)
                .set(MerchantIntegral::getErrMsg, errMsg)
                .eq(MerchantIntegral::getMerchantId, merchantId)
                .eq(MerchantIntegral::getIsDel, IsDelStatusEnum.NO.getStatus())
                .notIn(MerchantIntegral::getStatus, 2, 4);
        update(uw);
    }

    @Override
    public MerchantIntegral queryByMerchantIdAndLabel(String label, String merchantId) {
        return baseMapper.queryByMerchantIdAndLabel(label, merchantId);

//        LambdaQueryWrapper<MerchantIntegral> qw = new LambdaQueryWrapper<>();
//        qw
//                .eq(MerchantIntegral::getLabel, label)
//                .eq(MerchantIntegral::getMerchantId, merchantId)
//                .eq(MerchantIntegral::getIsDel, IsDelStatusEnum.NO.getStatus());
//        return getOne(qw);
    }

    @Override
    public BaseIntegralDetailVO platformBaseIntegralDetail(String label, String merchantId, BigDecimal price) {
//        MerchantIntegral integral = queryByMerchantIdAndLabel(label, merchantId);
        MerchantAssets merchantAssets = merchantAssetsService.queryByMerchantIdAndCoin(merchantId, label);

        if (merchantAssets == null)
            return null;

        BaseIntegralDetailVO vo = new BaseIntegralDetailVO();
        vo.setLabel(label);
        vo.setName("平台基础积分");
        vo.setAccount(merchantAssets.getAccount());
        vo.setBalanceNum(merchantAssets.getAmount());
        vo.setPrice(price);

        return vo;
    }
}
