package com.hfkj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.saas.SaasActivityService;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.dao.BsBankActivityRosterMapper;
import com.hfkj.entity.*;
import com.hfkj.service.*;
import com.hfkj.sysenum.PlatformTypeEnum;
import org.apache.commons.collections4.ListUtils;
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 java.util.*;

/**
 * @className: BsBankActivityRosterServiceImpl
 * @author: HuRui
 * @date: 2023/5/18
 **/
@Service("bankActivityRosterService")
public class BsBankActivityRosterServiceImpl implements BsBankActivityRosterService {
    @Resource
    private CommonService commonService;
    @Resource
    private BsBankActivityRosterMapper bsBankActivityRosterMapper;
    @Resource
    private BsBankActivityService bankActivityService;
    @Resource
    private BsBankActivityRosterRateService bankActivityRosterRateService;
    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private SaasActivityService saasActivityService;

    @Override
    public void editData(BsBankActivityRoster bankActivityRoster) {
        if (bankActivityRoster.getId() == null) {
            bankActivityRoster.setUpdateTime(new Date());
            bankActivityRoster.setCreateTime(new Date());
            bsBankActivityRosterMapper.insert(bankActivityRoster);
        } else {
            bankActivityRoster.setUpdateTime(new Date());
            bsBankActivityRosterMapper.updateByPrimaryKey(bankActivityRoster);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void enrollActivity(Long bankActivityId, Long merId, String branchBankNo) throws Exception {
        // 查询报名
        BsBankActivityRoster roster = getActivityRoster(bankActivityId, merId);
        if (roster != null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请勿重复报名");
        }
        // 查询活动
        BsBankActivity activity = bankActivityService.getBankActivityById(bankActivityId);
        if (activity == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的活动");
        }
        // 查询平台
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNo(merId, PlatformTypeEnum.type1);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        // 客户经理
        String refereeId = commonService.getDictionaryCodeName("ACTIVITY_BRANCH_BANK_NO", branchBankNo);
        if (StringUtils.isBlank(refereeId)) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该支行暂无法报名");
        }
        // 渠道报名
        saasActivityService.customerRegisterActivity(activity.getActivityNo().toString(), branchBankNo, refereeId, Arrays.asList(merPlatform.getCupNo()));

        BsBankActivityRoster bankActivityRoster = new BsBankActivityRoster();
        bankActivityRoster.setBankActivityId(bankActivityId);
        bankActivityRoster.setMerId(merId);
        bankActivityRoster.setPlatformNo(merPlatform.getPlatformNo());
        bankActivityRoster.setCupNo(merPlatform.getCupNo());
        bankActivityRoster.setStatus(1);
        editData(bankActivityRoster);

        // 延迟1秒
        Thread.sleep(1000);

        // 查询渠道费率
        JSONArray rates = saasActivityService.queryCustomerRates(activity.getActivityNo().toString(), merPlatform.getCupNo());
        for (Object obj : rates) {
            JSONObject rate = (JSONObject) obj;
            BsBankActivityRosterRate rosterRate = new BsBankActivityRosterRate();
            rosterRate.setBankActivityId(bankActivityId);
            rosterRate.setBankActivityRosterId(bankActivityRoster.getId());
            rosterRate.setMerId(bankActivityRoster.getMerId());
            rosterRate.setPlatformNo(bankActivityRoster.getPlatformNo());
            rosterRate.setCupNo(bankActivityRoster.getCupNo());
            rosterRate.setWelfareRatesId(rate.getLong("welfareRatesId"));
            rosterRate.setStartTime(rate.getDate("start"));
            rosterRate.setEndTime(rate.getDate("end"));
            rosterRate.setRates(rate.getString("rates"));
            rosterRate.setStatus(2);
            bankActivityRosterRateService.editData(rosterRate);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void configRosterRate(Long bankActivityId, Long merId, List<BsBankActivityRosterRate> bankActivityRosterRateList) throws Exception {
        BsBankActivity activity = bankActivityService.getBankActivityById(bankActivityId);
        if (activity == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        BsMerPlatformNo platformNo = merPlatformNoService.getPlatformNo(merId, PlatformTypeEnum.type1);
        if (platformNo == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        for (BsBankActivityRosterRate rosterRate : bankActivityRosterRateList) {
            BsBankActivityRosterRate rate = bankActivityRosterRateService.getRosterRateById(rosterRate.getId());
            if (rate == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            rate.setPreferentialRates(rosterRate.getPreferentialRates());
            rate.setStatus(1);
            bankActivityRosterRateService.editData(rate);
        }

        Map<String, Object> rate;
        List<Map<String,Object>> rates = new ArrayList<>();
        for (BsBankActivityRosterRate obj : bankActivityRosterRateList) {
            rate = new HashMap<>();
            rate.put("welfareRatesId", obj.getWelfareRatesId());
            rate.put("discountedRates", obj.getPreferentialRates());
            rates.add(rate);
        }

        saasActivityService.customerRatesUpdate(activity.getActivityNo().toString(), platformNo.getCupNo(), rates);
    }

    @Override
    public List<BsBankActivityRoster> getActivityRosterList(Map<String, Object> param) {
        BsBankActivityRosterExample example = new BsBankActivityRosterExample();
        example.createCriteria();
        return bsBankActivityRosterMapper.selectByExample(example);
    }

    @Override
    public BsBankActivityRoster getActivityRoster(Long bankActivityId, Long merId) {
        BsBankActivityRosterExample example = new BsBankActivityRosterExample();
        example.createCriteria().andBankActivityIdEqualTo(bankActivityId).andMerIdEqualTo(merId);
        List<BsBankActivityRoster> list = bsBankActivityRosterMapper.selectByExample(example);
        if (list.size() > 0) {
            BsBankActivityRoster roster = list.get(0);
            roster.setBankActivityRosterRateList(bankActivityRosterRateService.getListByRosterId(roster.getId()));
            return roster;
        }
        return null;
    }
}
