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

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
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.entity.*;
import com.ym.mec.biz.dal.enums.*;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.IniFileUtil;
import com.ym.mec.util.excel.POIUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.biz.dal.dto.PageInfoOrder;
import com.ym.mec.biz.dal.dto.StudentPaymentRouteOrderDto;
import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
import com.ym.mec.biz.service.GoodsService;
import com.ym.mec.biz.service.SellOrderService;
import com.ym.mec.biz.service.StudentPaymentRouteOrderService;
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.util.collection.MapUtil;
import org.springframework.web.multipart.MultipartFile;

@Service
public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, StudentPaymentRouteOrder> implements StudentPaymentRouteOrderService {

    @Autowired
    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
    @Autowired
    private SysUserCashAccountDao sysUserCashAccountDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private SellOrderDao sellOrderDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SellOrderService sellOrderService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;
    @Autowired
    private MusicGroupPaymentCalenderDetailDao musicGroupPaymentCalenderDetailDao;

    @Override
    public BaseDAO<Long, StudentPaymentRouteOrder> getDAO() {
        return studentPaymentRouteOrderDao;
    }

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

        List<StudentPaymentRouteOrder> dataList = null;
        int count = studentPaymentRouteOrderDao.queryAuditCount(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentPaymentRouteOrderDao.queryAuditPage(params);
        }
        if (count == 0) {
            dataList = new ArrayList<StudentPaymentRouteOrder>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfoOrder<StudentPaymentRouteOrderDto> OrderQueryPage(StudentPaymentOrderQueryInfo queryInfo) {
        PageInfoOrder<StudentPaymentRouteOrderDto> pageInfo = new PageInfoOrder<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List<StudentPaymentRouteOrderDto> dataList = new ArrayList<>();
        int count = this.findCount(params);

        BigDecimal totalUserBalance = sysUserCashAccountDao.getTotalUserBalance(params);
        pageInfo.setTotalUserBalance(totalUserBalance);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentPaymentRouteOrderDao.queryPageOrder(params);

            StudentPaymentRouteOrderDto orderMoneyAmount = studentPaymentRouteOrderDao.getOrderMoneyAmount(params);
            BigDecimal totalActualAmount = orderMoneyAmount.getActualAmount() != null ? orderMoneyAmount.getActualAmount() : BigDecimal.ZERO;
            BigDecimal totalBalancePaymentAmount = orderMoneyAmount.getBalancePaymentAmount() != null ? orderMoneyAmount.getBalancePaymentAmount() : BigDecimal.ZERO;

            params.put("chargeType", SporadicChargeTypeEnum.RECHARGE);
            BigDecimal totalChargeAmount = studentPaymentRouteOrderDao.getChargeAmount(params);
            totalChargeAmount = totalChargeAmount != null ? totalChargeAmount : BigDecimal.ZERO;
            BigDecimal totalAdvanceAmount = totalChargeAmount.subtract(totalBalancePaymentAmount);

            pageInfo.setTotalAdvanceAmount(totalAdvanceAmount);
            pageInfo.setTotalActualAmount(totalActualAmount);
            pageInfo.setTotalRevenueAmount(totalActualAmount.subtract(totalAdvanceAmount));
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public StudentPaymentRouteOrder addOutOrder(StudentPaymentRouteOrder studentPaymentRouteOrder) {
//        Map<String, Object> params = new HashMap<>();
//        params.put("transNo", studentPaymentRouteOrder.getTransNo());
//        if (studentPaymentRouteOrderDao.queryAuditCount(params) > 0) {
//            throw new BizException("流水号不能重复");
//        }
        if (studentPaymentRouteOrder.getCalenderId() != null) {
            MusicGroupPaymentCalender musicGroupPaymentCalender = musicGroupPaymentCalenderDao.getSchoolCalender(studentPaymentRouteOrder.getCalenderId());
            if (musicGroupPaymentCalender == null) {
                throw new BizException("学校缴费单号（审核通过）不存在，请核查");
            }
        }
        Date nowDate = new Date();
        String orderNo = idGeneratorService.generatorId("payment") + "";
        studentPaymentRouteOrder.setOrderNo(orderNo);
        studentPaymentRouteOrder.setAuditStatus(AuditStatusEnum.ING);
        studentPaymentRouteOrder.setCreateTime(nowDate);
        studentPaymentRouteOrder.setUpdateTime(nowDate);
        studentPaymentRouteOrder.setRouteAmount(studentPaymentRouteOrder.getSaleAmount().add(studentPaymentRouteOrder.getServiceAmount()));
        studentPaymentRouteOrder.setRouteBalanceAmount(BigDecimal.ZERO);
        studentPaymentRouteOrder.setFeeFlag("N");

        studentPaymentRouteOrderDao.insert(studentPaymentRouteOrder);

        return studentPaymentRouteOrder;
    }

    @Override
    public StudentPaymentRouteOrder updateOutOrder(StudentPaymentRouteOrder studentPaymentRouteOrder) {
        Date nowDate = new Date();
        studentPaymentRouteOrder.setAuditStatus(AuditStatusEnum.ING);
        studentPaymentRouteOrder.setUpdateTime(nowDate);
        studentPaymentRouteOrder.setRouteAmount(studentPaymentRouteOrder.getSaleAmount().add(studentPaymentRouteOrder.getServiceAmount()));
        studentPaymentRouteOrder.setRouteBalanceAmount(BigDecimal.ZERO);
        studentPaymentRouteOrder.setFeeFlag("N");

        studentPaymentRouteOrderDao.update(studentPaymentRouteOrder);

        return studentPaymentRouteOrder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public boolean auditOutOrder(Long studentPaymentRouteOrderId, AuditStatusEnum auditStatus, String memo, Integer operatorId) {
        StudentPaymentRouteOrder studentPaymentRouteOrder = studentPaymentRouteOrderDao.get(studentPaymentRouteOrderId);
        if (studentPaymentRouteOrder == null) {
            throw new BizException("查询订单信息失败");
        }

        if (studentPaymentRouteOrder.getAuditStatus() != AuditStatusEnum.ING) {
            throw new BizException("只有“审核中”的订单才能审核");
        }

        Date nowDate = new Date();
        String orderNo = idGeneratorService.generatorId("payment") + "";

        studentPaymentRouteOrder.setUpdateBy(operatorId);
        studentPaymentRouteOrder.setUpdateTime(nowDate);
        studentPaymentRouteOrder.setAuditComment(memo);
        studentPaymentRouteOrder.setAuditStatus(auditStatus);
        if (auditStatus == AuditStatusEnum.PASS) {
            studentPaymentRouteOrder.setOrderNo(orderNo);
        }

        studentPaymentRouteOrderDao.update(studentPaymentRouteOrder);

        if (auditStatus == AuditStatusEnum.PASS) {
            StudentPaymentOrder studentPaymentOrder = new StudentPaymentOrder();
            studentPaymentOrder.setActualAmount(studentPaymentRouteOrder.getRouteAmount());
            if(studentPaymentRouteOrder.getSchoolId() != null) {
                studentPaymentOrder.setMusicGroupId(studentPaymentRouteOrder.getSchoolId() + "");
            }
            studentPaymentOrder.setType(OrderTypeEnum.OUTORDER);
            studentPaymentOrder.setMerNos(studentPaymentRouteOrder.getMerNo());
            studentPaymentOrder.setOrderNo(studentPaymentRouteOrder.getOrderNo());
            studentPaymentOrder.setGroupType(GroupType.OUTORDER);
            studentPaymentOrder.setOrganId(studentPaymentRouteOrder.getRouteOrganId());
            studentPaymentOrder.setExpectAmount(studentPaymentRouteOrder.getRouteAmount());
            studentPaymentOrder.setStatus(DealStatusEnum.SUCCESS);
            studentPaymentOrder.setCreateTime(studentPaymentRouteOrder.getPayTime());
            studentPaymentOrder.setUpdateTime(nowDate);
            studentPaymentOrder.setMemo(studentPaymentRouteOrder.getMemo());
            studentPaymentOrder.setUserId(studentPaymentRouteOrder.getUserId());
            studentPaymentOrder.setPayTime(studentPaymentRouteOrder.getPayTime());
            studentPaymentOrder.setTransNo(studentPaymentRouteOrder.getTransNo());
            studentPaymentOrder.setOrderNo(orderNo);

            studentPaymentRouteOrderDao.insertOrder(studentPaymentOrder);

            if (StringUtils.isNoneBlank(studentPaymentRouteOrder.getGoodsJson())) {
                BigDecimal hasRouteAmount = BigDecimal.ZERO;
                BigDecimal goodsTotalPrice = BigDecimal.ZERO;

                List<Integer> goodsIdList = new ArrayList<>();
                JSONObject jsonObj = JSON.parseObject(studentPaymentRouteOrder.getGoodsJson());
                for (Entry<String, Object> goodsMap : jsonObj.entrySet()) {
                    Integer goodsId = Integer.parseInt(goodsMap.getKey());
                    Integer nums = Integer.parseInt(goodsMap.getValue().toString());
                    Goods goods = goodsDao.get(goodsId);
                    goodsTotalPrice = goodsTotalPrice.add(goods.getGroupPurchasePrice().multiply(new BigDecimal(nums)));
                    for (int i = 0; i < nums; i++) {
                        goodsIdList.add(goodsId);
                    }
                }
                List<SellOrder> sellOrderList = goodsService.subtractStock(goodsIdList, AccountType.INTERNAL);

                int i = 1;
                for (Entry<String, Object> goodsMap : jsonObj.entrySet()) {
                    Integer goodsId = Integer.parseInt(goodsMap.getKey());
                    Integer nums = Integer.parseInt(goodsMap.getValue().toString());
                    Goods goods = goodsDao.get(goodsId);

                    BigDecimal actualAmount = BigDecimal.ZERO;
                    if (goodsTotalPrice.compareTo(BigDecimal.ZERO) != 0) {
                        actualAmount = studentPaymentRouteOrder.getSaleAmount().multiply(goods.getGroupPurchasePrice().multiply(new BigDecimal(nums))).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
                    }
                    if (i == jsonObj.entrySet().size()) {
                        actualAmount = studentPaymentRouteOrder.getSaleAmount().subtract(hasRouteAmount);
                    }
                    hasRouteAmount = hasRouteAmount.add(actualAmount);
                    i++;

                    int complementNum = goods.getComplementGoodsIdList() == null ? 1 : goods.getComplementGoodsIdList().split(",").length;
                    int goodsNum = nums * complementNum;
                    BigDecimal complementPrice = goods.getGroupPurchasePrice().multiply(new BigDecimal(nums));
                    Map<Integer, BigDecimal> complementGoodsPrice = new HashMap<>();
                    complementGoodsPrice.put(goods.getId(), goods.getGroupPurchasePrice());
                    if (goods.getComplementGoodsIdList() != null) {
                        List<Goods> complementGoodies = goodsDao.findGoodsByIds(goods.getComplementGoodsIdList());
                        complementGoodsPrice = complementGoodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getGroupPurchasePrice));
                        complementPrice = complementGoodies.stream().map(Goods::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add).multiply(new BigDecimal(nums));
                    }

                    BigDecimal hasRouteSellOrderActualAmount = BigDecimal.ZERO;
                    for (SellOrder sellOrder : sellOrderList) {
                        if (!Integer.valueOf(goodsMap.getKey()).equals(sellOrder.getParentGoodsId()) && !Integer.valueOf(goodsMap.getKey()).equals(sellOrder.getGoodsId())) {
                            continue;
                        }
                        BigDecimal sellOrderActualAmount = BigDecimal.ZERO;
                        if (complementPrice.compareTo(BigDecimal.ZERO) > 0) {
                            sellOrderActualAmount = complementGoodsPrice.get(sellOrder.getGoodsId()).multiply(new BigDecimal(sellOrder.getNum())).multiply(actualAmount).divide(complementPrice, 2, BigDecimal.ROUND_DOWN);
                        }
                        goodsNum = goodsNum - sellOrder.getNum();
                        if (goodsNum <= 0) {
                            sellOrderActualAmount = actualAmount.subtract(hasRouteSellOrderActualAmount);
                        }
                        hasRouteSellOrderActualAmount = hasRouteSellOrderActualAmount.add(sellOrderActualAmount);

                        sellOrder.setSellTime(studentPaymentRouteOrder.getPayTime());
                        sellOrder.setOrganId(studentPaymentRouteOrder.getRouteOrganId());
                        sellOrder.setCooperationOrganId(studentPaymentRouteOrder.getSchoolId());
                        sellOrder.setTransNo(studentPaymentRouteOrder.getTransNo());
                        sellOrder.setOrderId(studentPaymentOrder.getId());
                        sellOrder.setOrderNo(studentPaymentRouteOrder.getOrderNo());
                        sellOrder.setActualAmount(sellOrderActualAmount);
                        sellOrder.setBalanceAmount(BigDecimal.ZERO);
                        sellOrder.setExpectAmount(sellOrderActualAmount);
                        sellOrder.setUserId(studentPaymentRouteOrder.getUserId());
                        sellOrder.setPaymentChannel(studentPaymentOrder.getPaymentChannel());
                        sellOrder.setMerNo(studentPaymentRouteOrder.getMerNo());
                        sellOrder.setSellTime(studentPaymentRouteOrder.getCreateTime());
                        sellOrder.setCreateIme(nowDate);
                        sellOrder.setUpdateTime(nowDate);
                        sellOrder.setType(SellTypeEnum.SCHOOL_BUY);
                    }
                }
                sellOrderDao.batchInsert(sellOrderList);
            }

            if (studentPaymentRouteOrder.getCalenderId() == null) {
                return true;
            }

            //根据学校缴费项id，确定缴费状态
            BigDecimal amount = studentPaymentRouteOrderDao.sumAmountByCalenderId(studentPaymentRouteOrder.getCalenderId());
            List<MusicGroupPaymentCalenderDetail> calenderDetails = musicGroupPaymentCalenderDetailDao.getCalenderDetailWithCalender(studentPaymentRouteOrder.getCalenderId());
            MusicGroupPaymentCalender musicGroupPaymentCalender = musicGroupPaymentCalenderDao.get(studentPaymentRouteOrder.getCalenderId());

            if (amount.compareTo(musicGroupPaymentCalender.getPaymentAmount()) >= 0) {
                musicGroupPaymentCalender.setActualNum(musicGroupPaymentCalender.getExpectNum());
                musicGroupPaymentCalender.setStatus(MusicGroupPaymentCalender.PaymentCalenderStatusEnum.PAID);
                musicGroupPaymentCalenderDao.update(musicGroupPaymentCalender);

                for (MusicGroupPaymentCalenderDetail calenderDetail : calenderDetails) {
                    calenderDetail.setActualAmount(calenderDetail.getExpectAmount());
                    calenderDetail.setPaymentStatus(MusicGroupStudentFee.PaymentStatus.PAID_COMPLETED);
                    calenderDetail.setPayTime(nowDate);
                    calenderDetail.setUpdateTime(nowDate);
                }
                if (calenderDetails.size() > 0) {
                    musicGroupPaymentCalenderDetailDao.batchUpdate(calenderDetails);
                }
            }

        }
        return true;
    }

    @Override
    public StudentPaymentRouteOrder addRouteOrder(String orderNo, Integer routeOrganId, BigDecimal routeBalanceAmount) {
        StudentPaymentRouteOrder studentPaymentRouteOrder = new StudentPaymentRouteOrder();
        studentPaymentRouteOrder.setOrderNo(orderNo);
        studentPaymentRouteOrder.setRouteOrganId(routeOrganId);
        studentPaymentRouteOrder.setRouteAmount(BigDecimal.ZERO);
        studentPaymentRouteOrder.setRouteBalanceAmount(routeBalanceAmount);
        studentPaymentRouteOrder.setFeeFlag("N");
        if (studentPaymentRouteOrderDao.insert(studentPaymentRouteOrder) <= 0) {
            throw new BizException("插入订单失败");
        }
        return studentPaymentRouteOrder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteRouteOrder(Long orderId) {
        StudentPaymentOrder studentPaymentOrder = studentPaymentOrderDao.get(orderId);
        if (studentPaymentOrder == null) {
            throw new BizException("订单不存在,请核查");
        }
        studentPaymentOrderDao.delete(orderId);
        studentPaymentRouteOrderDao.deleteByOrderNo(studentPaymentOrder.getOrderNo());
        //归还库存
        List<SellOrder> sellOrders = sellOrderService.getSellOrderByParentGoodsId(orderId, null);
        if (sellOrders.size() > 0) {
            sellOrderDao.deleteByOrderId(orderId);
        }
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<List<StudentPaymentRouteOrder>> importRouteOrder(MultipartFile file) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null || sysUser.getId() == null) {
            throw new BizException("用户信息获取失败");
        }
        Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
        InputStream inputStream = new ClassPathResource("columnMapper.ini").getInputStream();
        Map<String, String> columns = IniFileUtil.readIniFile(inputStream, TemplateTypeEnum.ROUTE_ORDER.getMsg());
        List<StudentPaymentRouteOrder> studentPaymentRouteOrders = new ArrayList<>();
        Map<String, Integer> organMap = getMap("organization", "name_", "id_", true, String.class, Integer.class);
        Map<String, Integer> cooperationOrganMap = getMap("cooperation_organ", "name_", "id_", true, String.class, Integer.class);
        StringBuffer sb = new StringBuffer();
        for (String e : sheetsListMap.keySet()) {
            List<Map<String, Object>> sheet = sheetsListMap.get(e);
            List<Object> collect = sheet.stream().map(m -> m.get("交易流水号")).collect(Collectors.toList());
            if (collect == null || collect.size() == 0) {
                continue;
            }
//            List<String> list = studentPaymentRouteOrderDao.countByTransNo(collect);
//            if (list != null && list.size() > 0) {
//                throw new BizException("导入数据错误  重复的交易流水号:{}", list.get(0));
//            }
            Date nowDate = new Date();

            List<Object> calenderIds = sheet.stream().map(m -> m.get("缴费单号")).collect(Collectors.toList());
            List<MusicGroupPaymentCalender> calenders = musicGroupPaymentCalenderDao.getPaymentCalenderWithCalenderIdsAndPayUserType(calenderIds, MusicGroupPaymentCalender.PayUserType.SCHOOL);
            Map<String, Long> schoolCalender = calenders.stream().collect(Collectors.toMap(m -> m.getId().toString(), MusicGroupPaymentCalender::getId));

            valueIsNull:
            for (int j = 0; j < sheet.size(); j++) {
                int rowNum = j + 2;
                Map<String, Object> row = sheet.get(j);
                if (row.size() == 0) {
                    continue;
                }
                JSONObject objectMap = new JSONObject();
                Iterator<String> iterator = row.keySet().iterator();
                for (int i = 0; i < row.keySet().size(); i++) {
                    String s = iterator.next();
                    if (!columns.containsKey(s)) {
                        continue;
                    }
                    String columnValue = columns.get(s);
                    if (columnValue.equals("incomeType")) {
                        if (StringUtils.isEmpty(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：收入类型不可为空;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("incomeType", row.get(s));
                        }
                    }
                    if (columnValue.equals("transNo")) {
                        if (StringUtils.isEmpty(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：交易流水号不可为空;");
                            continue valueIsNull;
                        }
                    }
                    if (columnValue.equals("payTime") && StringUtils.isEmpty(row.get(s).toString())) {
                        if (StringUtils.isEmpty(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：交易日期不可为空;");
                            continue valueIsNull;
                        }
                    }
                    if (columnValue.equals("merNo")) {
                        if (StringUtils.isEmpty(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：收款账户不可为空;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("merNo", row.get(s));
                        }
                        continue;
                    }
                    if (columnValue.equals("organName") && StringUtils.isNotEmpty(row.get(s).toString())) {
                        Integer integer = organMap.get(row.get(s));
                        if (integer == null) {
                            sb.append("第" + rowNum).append("行数据导入失败：分部名称不存在;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("routeOrganId", integer);
                        }
                        continue;
                    }
                    if (columnValue.equals("cooperationOrganName") && StringUtils.isNotEmpty(row.get(s).toString())) {
                        Integer integer = cooperationOrganMap.get(row.get(s));
                        if (integer != null) {
                            objectMap.put("schoolId", integer);
                        } else {
                            sb.append("第" + rowNum).append("行数据导入失败：所属学校名称不存在;");
                            continue valueIsNull;
                        }
                        continue;
                    }
                    if (columnValue.equals("userId") && StringUtils.isNotEmpty(row.get(s).toString())) {
                        Boolean flag = teacherDao.existUser(row.get(s));
                        if (flag) {
                            objectMap.put("userId", row.get(s));
                        } else {
                            sb.append("第" + rowNum).append("行数据导入失败：学员编号不存在;");
                            continue valueIsNull;
                        }
                        continue;
                    }
                    if (columnValue.equals("payTime")) {
                        String toString = row.get(s).toString();
                        Date date = DateUtil.stringToDate(toString, DateUtil.DEFAULT_PATTERN);
                        if (date == null) {
                            sb.append("第" + rowNum).append("行数据导入失败：交易日期格式错误;");
                            continue valueIsNull;
                        } else if (date.after(nowDate)) {
                            sb.append("第" + rowNum).append("行数据导入失败：交易日期不能大于当前日期");
                            continue valueIsNull;
                        } else {
                            objectMap.put(columnValue, DateUtil.format(date, DateUtil.DEFAULT_PATTERN));
                        }
                        continue;
                    }
                    if (columnValue.equals("calenderId")) {
                        if (StringUtils.isNotBlank(row.get(s).toString()) && !schoolCalender.containsKey(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：学校缴费单号（审核通过）不存在;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("calenderId", row.get(s));
                        }
                        continue;
                    }
                    objectMap.put(columnValue, row.get(s));
                }
                StudentPaymentRouteOrder studentPaymentRouteOrder = JSONObject.parseObject(objectMap.toJSONString(), StudentPaymentRouteOrder.class);
                //销售收入
                if ("销售收入".equals(studentPaymentRouteOrder.getIncomeType())) {
                    if (studentPaymentRouteOrder.getSaleAmount() == null) {
                        throw new BizException("导入失败：交易流水号{},收入类型为销售收入时，销售金额不可为空", studentPaymentRouteOrder.getTransNo());
                    }
                    studentPaymentRouteOrder.setServiceAmount(BigDecimal.ZERO);
                    String goodsIds = studentPaymentRouteOrder.getGoodsIds();
                    String goodsNums = studentPaymentRouteOrder.getGoodsNums();

                    if (StringUtils.isEmpty(goodsNums)) {
                        throw new BizException("导入失败：有销售金额时商品数量必填");
                    }
                    if (StringUtils.isEmpty(goodsIds)) {
                        throw new BizException("导入失败：有销售金额时商品编号必填");
                    }
                    List<String> goodsIdList = new ArrayList(Arrays.asList(goodsIds.split(",")));
                    List<String> goodsNumList = new ArrayList(Arrays.asList(goodsNums.split(",")));
                    if (goodsIdList.size() != goodsNumList.size()) {
                        throw new BizException("导入失败：商品编号和商品数量不一致");
                    }
                    JSONObject goodsJSON = new JSONObject();
                    for (int i = 0; i < goodsIdList.size(); i++) {
                        if (!goodsDao.findByIdAndStatus(goodsIdList.get(i), 1)) {
                            throw new BizException("导入失败：商品编号{}不存在", goodsIdList.get(i));
                        }
                        try {
                            int goodsNum = Integer.parseInt(goodsNumList.get(i));
                            goodsJSON.put(goodsIdList.get(i), goodsNum);
                        } catch (Exception e1) {
                            throw new BizException("导入失败：商品数量{}填写错误", goodsNumList.get(i));
                        }
                    }
                    studentPaymentRouteOrder.setGoodsJson(goodsJSON.toJSONString());
                    //服务收入
                } else {
                    studentPaymentRouteOrder.setSaleAmount(BigDecimal.ZERO);
                    if (studentPaymentRouteOrder.getServiceAmount() == null) {
                        throw new BizException("导入失败：交易流水号{},收入类型为服务收入时，服务金额不可为空", studentPaymentRouteOrder.getTransNo());
                    }
                }
                studentPaymentRouteOrder.setRouteBalanceAmount(BigDecimal.ZERO);
                studentPaymentRouteOrder.setAuditStatus(AuditStatusEnum.ING);
                studentPaymentRouteOrder.setRouteAmount(studentPaymentRouteOrder.getSaleAmount().add(studentPaymentRouteOrder.getServiceAmount()));
                studentPaymentRouteOrder.setCreateBy(sysUser.getId());
                studentPaymentRouteOrder.setUpdateBy(sysUser.getId());
                //studentPaymentRouteOrder.setUserId(sysUser.getId());
                studentPaymentRouteOrders.add(studentPaymentRouteOrder);
            }
        }
        if (studentPaymentRouteOrders.size() > 0) {
//            Map<String, List<StudentPaymentRouteOrder>> stringListMap = studentPaymentRouteOrders.stream().collect(Collectors.groupingBy(StudentPaymentRouteOrder::getTransNo));
//            if (stringListMap.size() != studentPaymentRouteOrders.size()) {
//                throw new BizException("导入失败：请勿录入重复的交易流水号");
//            }
            studentPaymentRouteOrderDao.batchAdd(studentPaymentRouteOrders);
        } else {
            throw new BizException(sb.length() > 0 ? sb.toString() : "导入失败：没有可以录入的数据");
        }
        HttpResponseResult httpResponseResult = new HttpResponseResult();
        httpResponseResult.setData(studentPaymentRouteOrders);
        httpResponseResult.setMsg(sb.toString());
        if (StringUtils.isNotEmpty(sb.toString())) {
            httpResponseResult.setCode(0);
        } else {
            httpResponseResult.setCode(200);
        }
        return httpResponseResult;
    }

}
