package com.ym.mec.biz.service.impl;

import ch.qos.logback.core.util.StringCollectionUtil;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityDto;
import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityStatDto;
import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityStatHead;
import com.ym.mec.biz.dal.dto.ReplacementPayDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.*;
import com.ym.mec.biz.dal.page.ReplacementInstrumentActivityQueryInfo;
import com.ym.mec.biz.dal.page.ReplacementInstrumentQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.common.service.IdGeneratorService;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;

import com.ym.mec.util.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<Integer, ReplacementInstrumentActivity> implements ReplacementInstrumentActivityService {

    @Autowired
    private ReplacementInstrumentActivityDao replacementInstrumentActivityDao;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private CooperationOrganDao cooperationOrganDao;
    @Autowired
    private SysUserCashAccountService sysUserCashAccountService;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private StudentPaymentRouteOrderService studentPaymentRouteOrderService;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private PayService payService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private SysUserCashAccountDetailService sysUserCashAccountDetailService;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private CooperationOrganService cooperationOrganService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private ReplacementInstrumentCooperationDao replacementInstrumentCooperationDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SysPaymentConfigService sysPaymentConfigService;
    @Autowired
    private SellOrderDao sellOrderDao;
    @Autowired
    private QuestionnaireTopicDao questionnaireTopicDao;
    @Autowired
    private QuestionnaireUserResultDao questionnaireUserResultDao;
    @Autowired
    private QuestionnaireQuestionDao questionnaireQuestionDao;
    @Autowired
    private QuestionnaireQuestionItemDao questionnaireQuestionItemDao;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public BaseDAO<Integer, ReplacementInstrumentActivity> getDAO() {
        return replacementInstrumentActivityDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object add(ReplacementInstrumentActivity replacementInstrumentActivity) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败，请重新登陆");
        }
        replacementInstrumentActivity.setGoodsId(replacementInstrumentActivity.getInstrumentsId());
        replacementInstrumentActivity.setUserId(sysUser.getId());
        //如果用户是43分部，那么修改用户信息
        if (sysUser.getOrganId() == 43) {
            CooperationOrgan cooperationOrgan = cooperationOrganService.get(replacementInstrumentActivity.getCooperationOrganId());
            if (cooperationOrgan != null) {
                sysUser.setOrganId(cooperationOrgan.getOrganId());
                sysUser.setUpdateTime(new Date());
                sysUserFeignService.updateSysUser(sysUser);
            }
        }
        ReplacementInstrumentCooperation replacementInstrumentCooperation = replacementInstrumentCooperationDao.get(replacementInstrumentActivity.getReplacementInstrumentCooperationId());
        //如果提交过调查问卷，那么覆盖之前的记录
        ReplacementInstrumentActivity activity = replacementInstrumentActivityDao.findByUserId(replacementInstrumentActivity.getCooperationOrganId(), sysUser.getId(), replacementInstrumentCooperation.getId());
        if (replacementInstrumentCooperation != null && replacementInstrumentCooperation.getOpenPay().equals(YesOrNoEnum.YES)) {
            replacementInstrumentActivity.setOpenFlag(1);
        }
        Boolean sendPush = false;
        if (activity != null) {
            if (!activity.getPayStatus().equals(0)) {
                throw new BizException("您已参与调查，谢谢参与！");
            }
            //覆盖之前的数据
            replacementInstrumentActivity.setId(activity.getId());
            replacementInstrumentActivityDao.update(replacementInstrumentActivity);
            if (replacementInstrumentActivity.getInstrumentsId() != null && (activity.getInstrumentsId() == null || activity.getInstrumentsId() == 0)) {
                sendPush = true;
            }
        } else {
            replacementInstrumentActivityDao.insert(replacementInstrumentActivity);
            sendPush = true;
        }
        //已开启缴费推送购买链接
        if (sendPush && replacementInstrumentActivity.getOpenFlag().equals(1) && replacementInstrumentActivity.getInstrumentsId() != null) {
            //换成商品列表中商品4.25
            Goods goods = goodsDao.get(replacementInstrumentActivity.getGoodsId());
            Map<Integer, String> userMap = new HashMap<>();
            Map<Integer, String> userPhoneMap = new HashMap<>();
            Integer userId = replacementInstrumentActivity.getUserId();
            String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");
            String pushUrl = baseApiUrl + "/#/questionGoodsSale?id=";
            userMap.put(userId, userId.toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userMap, null, 0, "5?" + pushUrl + replacementInstrumentActivity.getId(), "STUDENT", goods.getBrand(), "");

            userPhoneMap.put(replacementInstrumentActivity.getUserId(), replacementInstrumentActivity.getMobileNo());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userPhoneMap, null, 0, null, null, goods.getBrand(), HttpUtil.getSortUrl(pushUrl + replacementInstrumentActivity.getId()));
        }
        return replacementInstrumentActivity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object apply(ReplacementInstrumentActivityDto replacementInstrumentActivity) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败，请重新登陆");
        }
        replacementInstrumentActivity.setGoodsId(replacementInstrumentActivity.getInstrumentsId());
        replacementInstrumentActivity.setUserId(sysUser.getId());
        //如果用户是43分部，那么修改用户信息
        CooperationOrgan cooperationOrgan = cooperationOrganService.get(replacementInstrumentActivity.getCooperationOrganId());
        if (sysUser.getOrganId() == 43) {
            if (cooperationOrgan != null) {
                sysUser.setOrganId(cooperationOrgan.getOrganId());
                sysUser.setUpdateTime(new Date());
                sysUserFeignService.updateSysUser(sysUser);
            }
        }
        Integer topicId = replacementInstrumentActivity.getTopicId();
        ReplacementInstrumentCooperation replacementInstrumentCooperation = replacementInstrumentCooperationDao.get(replacementInstrumentActivity.getReplacementInstrumentCooperationId());
        //如果提交过调查问卷，那么覆盖之前的记录
        ReplacementInstrumentActivity activity = replacementInstrumentActivityDao.findByUserId(replacementInstrumentActivity.getCooperationOrganId(),
                sysUser.getId(),
                replacementInstrumentCooperation.getId());
        if (replacementInstrumentCooperation != null && replacementInstrumentCooperation.getOpenPay().equals(YesOrNoEnum.YES)) {
            replacementInstrumentActivity.setOpenFlag(1);
        }
        Boolean sendPush = false;
        List<QuestionnaireUserResult> questionnaireUserResultList = replacementInstrumentActivity.getQuestionnaireUserResultList();
        if (activity != null) {
            if (!activity.getPayStatus().equals(0)) {
                throw new BizException("您已参与调查，谢谢参与！");
            }
            //覆盖之前的数据
            replacementInstrumentActivity.setId(activity.getId());
            replacementInstrumentActivityDao.update(replacementInstrumentActivity);

            if (questionnaireUserResultList != null && questionnaireUserResultList.size() > 0) {
                //删除原来的问卷结果
                questionnaireUserResultDao.delByActiveIdAndUserId(activity.getReplacementInstrumentCooperationId(), sysUser.getId());
            }
            if (replacementInstrumentActivity.getInstrumentsId() != null && (activity.getInstrumentsId() == null || activity.getInstrumentsId() == 0)) {
                sendPush = true;
            }
        } else {
            replacementInstrumentActivityDao.insert(replacementInstrumentActivity);
            sendPush = true;
        }
        if (questionnaireUserResultList != null && questionnaireUserResultList.size() > 0) {
            for (QuestionnaireUserResult result : questionnaireUserResultList) {
                result.setUserId(sysUser.getId());
                result.setQuestionnaireTopicId(topicId);
                result.setActiveId(replacementInstrumentActivity.getReplacementInstrumentCooperationId());
                result.setActiveType(QuestionnaireActiveTypeEnum.REPLACEMENT);
            }
            //新增问卷结果
            questionnaireUserResultDao.batchInsert1(questionnaireUserResultList);
        }
        //已开启缴费推送购买链接
        if (sendPush && replacementInstrumentActivity.getOpenFlag().equals(1) && replacementInstrumentActivity.getInstrumentsId() != null) {
            //换成商品列表中商品4.25
            Goods goods = goodsDao.get(replacementInstrumentActivity.getGoodsId());
            Map<Integer, String> userMap = new HashMap<>();
            Map<Integer, String> userPhoneMap = new HashMap<>();
            Integer userId = replacementInstrumentActivity.getUserId();
            String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");
            String pushUrl = baseApiUrl + "/#/questionGoodsSale?id=";
            userMap.put(userId, userId.toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userMap, null, 0, "5?" + pushUrl + replacementInstrumentActivity.getId(), "STUDENT", goods.getBrand(), "");

            userPhoneMap.put(replacementInstrumentActivity.getUserId(), replacementInstrumentActivity.getMobileNo());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userPhoneMap, null, 0, null, null, goods.getBrand(), HttpUtil.getSortUrl(pushUrl + replacementInstrumentActivity.getId()));
        }
        return replacementInstrumentActivity;
    }


    @Override
    public ReplacementInstrumentActivity findByUserId(Integer cooperationOrganId, Integer userId, Integer cooperationId) {
        return replacementInstrumentActivityDao.findByUserId(cooperationOrganId, userId, cooperationId);
    }

    @Override
    public PageInfo<ReplacementInstrumentActivityStatDto> queryReplacementsStat(ReplacementInstrumentActivityQueryInfo queryInfo) {
        PageInfo<ReplacementInstrumentActivityStatDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        int count = replacementInstrumentActivityDao.countReplacements(params);

        if (queryInfo.getPage() == 1) {
            ReplacementInstrumentActivityStatHead head = replacementInstrumentActivityDao.countReplacementsInfo(queryInfo.getCooperationId());
            ReplacementInstrumentCooperation cooperation = replacementInstrumentCooperationDao.get(queryInfo.getCooperationId());
            CooperationOrgan cooperationOrgan = cooperationOrganDao.get(cooperation.getCooperationOrganId());
            QuestionnaireTopic questionnaireTopic = questionnaireTopicDao.get(cooperation.getTopicId());
            if (questionnaireTopic != null) {
                head.setTopicName(questionnaireTopic.getTitle());
            }
            head.setCooperationOrganName(cooperationOrgan.getName());
            pageInfo.setStatInfo(head);
        }

        pageInfo.setTotal(count);
        params.put("offset", pageInfo.getOffset());
        pageInfo.setRows(replacementInstrumentActivityDao.queryReplacements(params));
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map pay(ReplacementPayDto replacementPayDto) throws Exception {
        ReplacementInstrumentActivity replacementInstrumentActivity = replacementInstrumentActivityDao.getLock(replacementPayDto.getId());
        Integer userId = replacementInstrumentActivity.getUserId();

        if (replacementInstrumentActivity.getGoodsId() == null) {
            throw new BizException("数据维护中,请稍后支付");
        }

        //处理关闭订单
        if (replacementInstrumentActivity.getPayStatus().equals(1) && replacementPayDto.getRePay()) {
            StudentPaymentOrder oldOrder = studentPaymentOrderService.getUserReplacementIngOrder(userId, replacementInstrumentActivity.getId());
            if (oldOrder != null) {
                oldOrder.setStatus(DealStatusEnum.FAILED);
                oldOrder.setMemo("用户手动关闭");
                studentPaymentOrderService.callOrderCallBack(oldOrder);
            }
        }

        Goods goods = goodsDao.get(replacementInstrumentActivity.getInstrumentsId());
        BigDecimal orderAmount = goods.getGroupPurchasePrice();
        BigDecimal amount = replacementPayDto.getAmount(); //扣除余额之前的金额
        if (amount.compareTo(orderAmount) != 0) {
            throw new BizException("商品价格不符");
        }

        String channelType = "";
        Date nowDate = new Date();

        BigDecimal balance = BigDecimal.ZERO;
        if (replacementPayDto.getUseBalance() && amount.compareTo(BigDecimal.ZERO) > 0) {
            SysUserCashAccount userCashAccount = sysUserCashAccountService.getLocked(userId);
            if (userCashAccount == null) {
                throw new BizException("用户账户找不到");
            }
            if (userCashAccount.getBalance() != null && userCashAccount.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                balance = amount.compareTo(userCashAccount.getBalance()) >= 0 ? userCashAccount.getBalance() : amount;
                amount = amount.subtract(balance);
                sysUserCashAccountService.updateBalance(userId, balance.negate(), PlatformCashAccountDetailTypeEnum.PAY_FEE, "乐保购买");
            }
        }

        CooperationOrgan cooperationOrgan = cooperationOrganDao.get(replacementInstrumentActivity.getCooperationOrganId());

        String orderNo = idGeneratorService.generatorId("payment") + "";
        StudentPaymentOrder studentPaymentOrder = new StudentPaymentOrder();

        studentPaymentOrder.setPaymentChannel("BALANCE");
        studentPaymentOrder.setUserId(userId);
        studentPaymentOrder.setGroupType(GroupType.REPLACEMENT);
        studentPaymentOrder.setOrderNo(orderNo);
        studentPaymentOrder.setType(OrderTypeEnum.REPLACEMENT);
        studentPaymentOrder.setExpectAmount(orderAmount);
        studentPaymentOrder.setActualAmount(amount);
        studentPaymentOrder.setBalancePaymentAmount(balance);
        studentPaymentOrder.setStatus(DealStatusEnum.ING);
        studentPaymentOrder.setMusicGroupId(replacementInstrumentActivity.getId().toString());
        studentPaymentOrder.setRemitFee(BigDecimal.ZERO);
        studentPaymentOrder.setCourseRemitFee(BigDecimal.ZERO);
        studentPaymentOrder.setOrganId(cooperationOrgan.getOrganId());
        studentPaymentOrder.setRoutingOrganId(cooperationOrgan.getOrganId());
        studentPaymentOrder.setCreateTime(nowDate);
        studentPaymentOrder.setUpdateTime(nowDate);
        studentPaymentOrderService.insert(studentPaymentOrder);
        //修改支付状态
        replacementInstrumentActivity.setPayStatus(1);
        replacementInstrumentActivity.setUpdateTime(nowDate);
        replacementInstrumentActivityDao.update(replacementInstrumentActivity);

        studentPaymentOrder.setVersion(0);
        if (amount.compareTo(BigDecimal.ZERO) == 0) {
            studentPaymentRouteOrderService.addRouteOrder(orderNo, cooperationOrgan.getOrganId(), balance);
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("tradeState", "1");
            notifyMap.put("merOrderNo", studentPaymentOrder.getOrderNo());
            notifyMap.put("channelType", channelType);
            notifyMap.put("orderNo", "");
            studentPaymentOrderService.updateOrder(notifyMap);
            return notifyMap;
        }

        String orderSubject = "乐器置换";
        String receiver = "replacement";

        String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");

        Map payMap = payService.getPayMap(
                amount,
                balance,
                orderNo,
                baseApiUrl + "/api-student/studentOrder/notify",
                baseApiUrl + "/api-student/studentOrder/paymentResult?orderNo=" + orderNo,
                orderSubject,
                orderSubject,
                cooperationOrgan.getOrganId(),
                receiver
        );

        studentPaymentOrder.setOrganId(cooperationOrgan.getOrganId());
        studentPaymentOrder.setMerNos((String) payMap.get("routingMerNos"));
        studentPaymentOrder.setPaymentChannel((String) payMap.get("type"));
        studentPaymentOrder.setUpdateTime(nowDate);
        studentPaymentOrderService.update(studentPaymentOrder);
        return payMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean orderCallback(StudentPaymentOrder studentPaymentOrder) {
        Date nowDate = new Date();
        //更新订单信息
        studentPaymentOrder.setUpdateTime(nowDate);
        int updateCount = studentPaymentOrderService.update(studentPaymentOrder);
        if (updateCount <= 0) {
            throw new BizException("订单更新失败");
        }
        //更新维修单信息
        ReplacementInstrumentActivity replacementInstrumentActivity = replacementInstrumentActivityDao.getLock(Integer.parseInt(studentPaymentOrder.getMusicGroupId()));
        if (replacementInstrumentActivity == null) {
            throw new BizException("置换信息不存在");
        }

        Integer userId = studentPaymentOrder.getUserId();

        Map<Integer, String> map = new HashMap<>();
        map.put(userId, userId.toString());

        //支付成功
        if (studentPaymentOrder.getStatus() == DealStatusEnum.SUCCESS) {
            replacementInstrumentActivity.setPayStatus(2);
            replacementInstrumentActivity.setUpdateTime(nowDate);
            if (this.update(replacementInstrumentActivity) <= 0) {
                throw new BizException("置换信息更新失败");
            }

            //插入交易明细
            BigDecimal amount = studentPaymentOrder.getActualAmount();
            if (amount.compareTo(BigDecimal.ZERO) > 0) {
                SysUserCashAccount cashAccount = sysUserCashAccountService.get(userId);
                //充值
                SysUserCashAccountDetail rechargeDetail = new SysUserCashAccountDetail();
                rechargeDetail.setAmount(amount);
                rechargeDetail.setBalance(cashAccount.getBalance().add(amount));
                rechargeDetail.setComment("缴费前充值");
                rechargeDetail.setCreateTime(nowDate);
                rechargeDetail.setStatus(DealStatusEnum.SUCCESS);
                rechargeDetail.setTransNo(studentPaymentOrder.getTransNo());
                rechargeDetail.setType(PlatformCashAccountDetailTypeEnum.RECHARGE);
                rechargeDetail.setUpdateTime(nowDate);
                rechargeDetail.setUserId(userId);
                rechargeDetail.setChannel(studentPaymentOrder.getPaymentChannel());
                rechargeDetail.setComAmount(studentPaymentOrder.getComAmount());
                rechargeDetail.setPerAmount(studentPaymentOrder.getPerAmount());
                sysUserCashAccountDetailService.insert(rechargeDetail);

                //缴费
                SysUserCashAccountDetail paymentDetail = new SysUserCashAccountDetail();
                paymentDetail.setAmount(amount.negate());
                paymentDetail.setBalance(cashAccount.getBalance());
                paymentDetail.setComment("乐器置换");
                paymentDetail.setCreateTime(nowDate);
                paymentDetail.setStatus(DealStatusEnum.SUCCESS);
                paymentDetail.setTransNo(studentPaymentOrder.getTransNo());
                paymentDetail.setType(PlatformCashAccountDetailTypeEnum.PAY_FEE);
                paymentDetail.setUpdateTime(nowDate);
                paymentDetail.setUserId(userId);
                rechargeDetail.setChannel(studentPaymentOrder.getPaymentChannel());
                sysUserCashAccountDetailService.insert(paymentDetail);
            }
            //添加sell_order
            this.addSellOrder(studentPaymentOrder, replacementInstrumentActivity);
            try {
                contractService.transferProduceContract(userId, null);
            } catch (Exception e) {
                logger.error("产品协议生成失败", e);
            }
            return true;
        }

        if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {

            replacementInstrumentActivity.setPayStatus(0);
            replacementInstrumentActivity.setUpdateTime(nowDate);
            if (this.update(replacementInstrumentActivity) <= 0) {
                throw new BizException("置换信息更新失败");
            }

            if (studentPaymentOrder.getBalancePaymentAmount() != null && studentPaymentOrder.getBalancePaymentAmount().compareTo(BigDecimal.ZERO) > 0) {
                sysUserCashAccountService.updateBalance(studentPaymentOrder.getUserId(), studentPaymentOrder.getBalancePaymentAmount(), PlatformCashAccountDetailTypeEnum.REFUNDS, "乐保购买支付失败");
            }

            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_SMS_PUSH_SPORADIC_PAYMENT_FAILED, map, null, 0, null, "STUDENT",
                    studentPaymentOrder.getActualAmount(), "乐器置换");
            return false;
        }
        return false;
    }

    @Override
    public ReplacementInstrumentActivityStatDto getInfo(Integer id) {
        ReplacementInstrumentActivityStatDto info = replacementInstrumentActivityDao.getInfo(id);
        if (info != null && info.getOpenFlag().equals(0)) {
            ReplacementInstrumentCooperation byCooperationId = replacementInstrumentCooperationDao.get(info.getReplacementInstrumentCooperationId());
            if (byCooperationId != null && byCooperationId.getOpenPay().equals(YesOrNoEnum.YES)) {
                info.setOpenFlag(1);
            }
        }
        return info;
    }

    @Override
    public PageInfo<ReplacementInstrumentActivityStatDto> getPageList(ReplacementInstrumentActivityQueryInfo queryInfo) {
        PageInfo<ReplacementInstrumentActivityStatDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List<ReplacementInstrumentActivityStatDto> dataList = new ArrayList<>();
        int count = replacementInstrumentActivityDao.getCount(params);
        pageInfo.setTotal(count);

        if (queryInfo.getPage() <= pageInfo.getTotalPage()) {
            params.put("offset", pageInfo.getOffset());
            dataList = replacementInstrumentActivityDao.getPageList(params);
            List<Integer> ids = dataList.stream().map(ReplacementInstrumentActivity::getId).collect(Collectors.toList());
            if (ids.size() > 0) {
                List<StudentPaymentOrder> activityPageOrders = replacementInstrumentActivityDao.getActivityOrder(ids);
                Map<Integer, List<StudentPaymentOrder>> activityOrderMap = activityPageOrders.stream().collect(Collectors.groupingBy(e -> Integer.parseInt(e.getMusicGroupId())));
                for (ReplacementInstrumentActivityStatDto replacementInstrumentActivityStatDto : dataList) {
                    if (!activityOrderMap.containsKey(replacementInstrumentActivityStatDto.getId())) continue;
                    List<StudentPaymentOrder> activityOrders = activityOrderMap.get(replacementInstrumentActivityStatDto.getId());
                    replacementInstrumentActivityStatDto.setActualAmount(activityOrders.get(0).getActualAmount());
                    replacementInstrumentActivityStatDto.setBalance(activityOrders.get(0).getBalancePaymentAmount());
                }
            }
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    private List<SellOrder> addSellOrder(StudentPaymentOrder order, ReplacementInstrumentActivity replacementInstrumentActivity) {
        if (replacementInstrumentActivity.getGoodsId() == null) {
            return null;
        }
        List<Goods> goodies = new ArrayList<>();
        Goods goods = goodsDao.get(replacementInstrumentActivity.getInstrumentsId());
        goodies.add(goods);
        if (goods.getComplementGoodsIdList() != null) {
            goodies = goodsDao.findGoodsByIds(goods.getComplementGoodsIdList());
        }
        Map<Integer, BigDecimal> groupPurchasePriceMap = goodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getGroupPurchasePrice));
        BigDecimal goodsTotalPrice = goodies.stream().map(Goods::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<Integer, GoodsType> goodsTypeMap = goodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getType));

        AccountType accountType = sysPaymentConfigService.checkAccountType(PaymentChannelEnum.valueOf(order.getPaymentChannel()), order.getMerNos());

        List<Integer> goodsIds = new ArrayList<>();
        goodsIds.add(goods.getId());
        List<SellOrder> sellOrders = goodsService.subtractStock(goodsIds, accountType);

        BigDecimal hasRouteSellOrderExpectAmount = BigDecimal.ZERO; //已分配预计金额
        BigDecimal hasRouteSellOrderBalance = BigDecimal.ZERO; //已分配余额

        int i = 1;
        for (SellOrder sellOrder : sellOrders) {
            BigDecimal sellOrderExpectAmount = order.getExpectAmount().compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : groupPurchasePriceMap.get(sellOrder.getGoodsId()).multiply(order.getExpectAmount()).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
            BigDecimal sellOrderBalance = order.getExpectAmount().compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : groupPurchasePriceMap.get(sellOrder.getGoodsId()).multiply(order.getBalancePaymentAmount()).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
            if (i == sellOrders.size()) {
                sellOrderExpectAmount = order.getExpectAmount().subtract(hasRouteSellOrderExpectAmount);
                sellOrderBalance = order.getBalancePaymentAmount().subtract(hasRouteSellOrderBalance);
            }
            sellOrder.setOrganId(order.getOrganId());
            sellOrder.setTransNo(order.getTransNo());
            sellOrder.setOrderId(order.getId());
            sellOrder.setCooperationOrganId(replacementInstrumentActivity.getCooperationOrganId());
            sellOrder.setOrderNo(order.getOrderNo());
            sellOrder.setActualAmount(sellOrderExpectAmount.subtract(sellOrderBalance));
            sellOrder.setBalanceAmount(sellOrderBalance);
            sellOrder.setExpectAmount(sellOrderExpectAmount);
            sellOrder.setNum(1);
            sellOrder.setUserId(order.getUserId());
            sellOrder.setPaymentChannel(order.getPaymentChannel());
            sellOrder.setMerNo(order.getMerNos());
            sellOrder.setSellTime(order.getCreateTime());
            sellOrder.setCreateIme(new Date());
            sellOrder.setUpdateTime(new Date());
            if (goodsTypeMap.get(sellOrder.getGoodsId()).equals(GoodsType.INSTRUMENT)) {
                sellOrder.setType(SellTypeEnum.INSTRUMENT);
            } else if (goodsTypeMap.get(sellOrder.getGoodsId()).equals(GoodsType.ACCESSORIES)) {
                sellOrder.setType(SellTypeEnum.ACCESSORIES);
            } else {
                sellOrder.setType(SellTypeEnum.OTHER);
            }
            i++;
        }
        if (sellOrders.size() > 0) {
            sellOrderDao.batchInsert(sellOrders);
        }
        return sellOrders;
    }

    @Transactional(rollbackFor = Exception.class)
    public void resultSync() {
        //获取所有问卷结果
        List<ReplacementInstrumentActivity> activities = replacementInstrumentActivityDao.findAll(new HashMap<>());
        List<QuestionnaireUserResult> questionnaireUserResultList = new ArrayList<>();
        for (ReplacementInstrumentActivity activity : activities) {
            String questionResult = activity.getQuestionResult();
            if (StringUtils.isEmpty(questionResult)) {
                continue;
            }
            String[] split = questionResult.split("");
            //获取所有问题
            List<QuestionnaireQuestion> questionList = questionnaireQuestionDao.findByTopicId(activity.getTopicId());
            for (int i = 0; i < split.length; i++) {
                QuestionnaireUserResult result = new QuestionnaireUserResult();
                QuestionnaireQuestion question = questionList.get(i);
                //获取问题答案
                QuestionnaireQuestionItem item = questionnaireQuestionItemDao.findByQuestionId(question.getId());
                result.setUserId(activity.getUserId());
                result.setActiveId(activity.getReplacementInstrumentCooperationId());
                result.setActiveType(QuestionnaireActiveTypeEnum.REPLACEMENT);
                result.setQuestionnaireQuestionId(question.getId());
                result.setQuestionnaireQuestionItemIdList(item.getId() + (Integer.parseInt(split[i]) == 0 ? 1 : 0) + "");
                result.setQuestionnaireTopicId(question.getQuestionnaireTopicId());
                questionnaireUserResultList.add(result);
            }
        }
        questionnaireUserResultDao.batchInsert1(questionnaireUserResultList);
    }

    @Override
    public ReplacementInstrumentActivity queryUserInfo(Integer cooperationOrganId, SysUser user, Integer cooperationId) {
        ReplacementInstrumentActivity replacementInstrumentActivity = findByUserId(cooperationOrganId, user.getId(), cooperationId);
        ReplacementInstrumentCooperation cooperation = replacementInstrumentCooperationDao.get(cooperationId);
        if (replacementInstrumentActivity == null) {
            Student student = studentService.get(user.getId());
            replacementInstrumentActivity = new ReplacementInstrumentActivity();

            replacementInstrumentActivity.setUserId(user.getId());
            replacementInstrumentActivity.setClasses(student.getCurrentClass());
            if (student.getCurrentGradeNum() != null) {
                replacementInstrumentActivity.setGrade(student.getCurrentGradeNum().toString());
            }
            replacementInstrumentActivity.setCooperationOrganId(cooperationOrganId);
            replacementInstrumentActivity.setUserName(StringUtils.isEmpty(user.getUsername()) ? user.getRealName() : user.getUsername());
            String subjectIdList = student.getSubjectIdList();
            if (StringUtils.isNotEmpty(subjectIdList)) {
                replacementInstrumentActivity.setSubjectId(Integer.parseInt(subjectIdList.split(",")[0]));
            }
            replacementInstrumentActivity.setTopicId(cooperation.getTopicId());
            replacementInstrumentActivity.setReplacementInstrumentCooperationId(cooperationId);
        }
        replacementInstrumentActivity.setReplacementInstrumentCooperationTitle(cooperation.getTitle());
        replacementInstrumentActivity.setMobileNo(user.getPhone());
        CooperationOrgan cooperationOrgan = cooperationOrganService.get(cooperationOrganId);
        if (cooperationOrgan != null) {
            replacementInstrumentActivity.setCooperationOrganName(cooperationOrgan.getName());
        }
        replacementInstrumentActivity.setShowQuestion(cooperation.getShowQuestion());
        return replacementInstrumentActivity;
    }
}
