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


import com.alibaba.fastjson.JSONObject;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.FinancialExpenditure;
import com.ym.mec.biz.dal.entity.Organization;
import com.ym.mec.biz.dal.enums.ExpenditureTypeEnum;
import com.ym.mec.biz.dal.enums.FeeProjectEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.TemplateTypeEnum;
import com.ym.mec.biz.dal.page.FinancialExpenditureQueryInfo;
import com.ym.mec.biz.service.FinancialExpenditureService;
import com.ym.mec.biz.service.GroupClassService;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.biz.service.VipGroupService;
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.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import com.ym.mec.util.ini.IniFileUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.record.WriteAccessRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FinancialExpenditureServiceImpl extends BaseServiceImpl<Long, FinancialExpenditure> implements FinancialExpenditureService {

    @Autowired
    private FinancialExpenditureDao financialExpenditureDao;
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private VipGroupService vipGroupService;
    @Autowired
    private GroupClassService groupClassService;
    @Autowired
    private MusicGroupService musicGroupService;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private FinancialExpenditureService financialExpenditureService;

    @Override
    public BaseDAO<Long, FinancialExpenditure> getDAO() {
        return financialExpenditureDao;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(FinancialExpenditureServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<FinancialExpenditure> importFinancialExpenditure(MultipartFile file) throws Exception {
        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.FINANCIAL_EXPENDITURE.getMsg());
        List<FinancialExpenditure> financialExpenditures = new ArrayList<>();
        Map<String, Integer> organMap = getMap("organization", "name_", "id_", true, TenantContextHolder.getTenantId(), String.class, Integer.class);
        Map<String, Integer> cooperationOrganMap = getMap("cooperation_organ", "name_", "id_", true, TenantContextHolder.getTenantId(), 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;
            }
            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();
                for (String s : row.keySet()) {
                    if (!columns.containsKey(s)) {
                        continue;
                    }
                    String columnValue = columns.get(s);
                    if (columnValue.equals("type")) {
                        for (ExpenditureTypeEnum expenditureType : ExpenditureTypeEnum.values()) {
                            if (expenditureType.getDesc().equals(row.get(s).toString())) {
                                objectMap.put(columnValue, expenditureType);
                                break;
                            }
                        }
                        continue;
                    }
                    if (columnValue.equals("dingtalkProcessNo")) {
                        if (StringUtils.isEmpty(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：钉钉流程编号不可为空;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("incomeType", row.get(s));
                        }
                    }
                    if (columnValue.equals("feeProject")) {
                        for (FeeProjectEnum feeProject : FeeProjectEnum.values()) {
                            if (feeProject.getDesc().equals(row.get(s).toString())) {
                                objectMap.put(columnValue, feeProject);
                                break;
                            }
                        }
                        continue;
                    }
                    if (columnValue.equals("amount")) {
                        if (StringUtils.isEmpty(row.get(s).toString())) {
                            sb.append("第" + rowNum).append("行数据导入失败：费用不可为空;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("amount", 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("organId", integer);
                        }
                        continue;
                    }
                    if (columnValue.equals("cooperationOrganName") && StringUtils.isNotEmpty(row.get(s).toString())) {
                        Integer integer = cooperationOrganMap.get(row.get(s));
                        if (integer == null) {
                            sb.append("第" + rowNum).append("行数据导入失败：合作单位校验失败;");
                            continue valueIsNull;
                        } else {
                            objectMap.put("cooperationOrganId", integer);
                        }
                        continue;
                    }
                    if (columnValue.equals("paymentTime") && StringUtils.isNotEmpty(row.get(s).toString())) {
                        String toString = row.get(s).toString();
                        if (StringUtils.isNotEmpty(toString)) {
                            Date date = DateUtil.stringToDate(toString, DateUtil.DEFAULT_PATTERN);
                            if (date == null) {
                                throw new BizException("导入数据错误  付款时间格式错误");
                            } else {
                                objectMap.put(columnValue, DateUtil.format(date, DateUtil.DEFAULT_PATTERN));
                            }
                        }
                        continue;
                    }
                    objectMap.put(columnValue, row.get(s));
                }
                FinancialExpenditure financialExpenditure = null;
                try {
                    financialExpenditure = JSONObject.parseObject(objectMap.toJSONString(), FinancialExpenditure.class);
                    financialExpenditures.add(financialExpenditure);
                } catch (Exception ex) {
                    throw new BizException("导入数据出错,请检查Excel表格");
                }
            }
        }
        if (sb.length() > 0) {
            throw new BizException(sb.toString());
        }
        if (financialExpenditures.size() != 0) {
            financialExpenditureDao.batchInsert(financialExpenditures);
        }
        return financialExpenditures;
    }

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

        List<FinancialExpenditureDto> dataList = null;
        int count = financialExpenditureDao.findFinancialExpenditureCount(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = financialExpenditureDao.queryFinancialExpenditurePage(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public void batchDel(String ids) {
        if (StringUtils.isEmpty(ids)) {
            throw new BizException("参数校验失败");
        }
        financialExpenditureDao.batchDel(ids);
    }

    @Override
    public List<FinancialExpenditure> batchAdd(List<FinancialExpenditure> financialExpenditures) {
        financialExpenditureDao.batchInsert(financialExpenditures);
        return financialExpenditures;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncOaPayLog(Integer workOrderId,String fileUrl) throws Exception {
        PWorkOrderInfo pWorkOrderInfo = financialExpenditureDao.getWorkOrderInfo(workOrderId);
        if (pWorkOrderInfo != null){
            Integer hasFinancial = financialExpenditureDao.findByBatchNoAndProcessNo(workOrderId);
            if(hasFinancial != null){
                return;
            }
            String realName = "";
            if(pWorkOrderInfo.getCreator() != null){
                SimpleUserDto simpleUser = teacherDao.getSimpleUser(pWorkOrderInfo.getCreator());
                if(Objects.nonNull(simpleUser)){
                    realName = simpleUser.getRealName();
                }
            }
            String formStructure = financialExpenditureDao.getFormStructure(workOrderId);
            JSONObject formData = JSONObject.parseObject(financialExpenditureDao.getFormData(workOrderId));
            OaFormStructureDto oaFormStructureDto = JSONObject.parseObject(formStructure, OaFormStructureDto.class);
            List<OaInputDto> oaInputDtos = oaFormStructureDto.getList();
            //课程退费和乐团退费需要单独处理
            if(pWorkOrderInfo.getProcess().equals(33) ||
                    pWorkOrderInfo.getProcess().equals(22) ||
                    pWorkOrderInfo.getProcess().equals(19) ||
                    pWorkOrderInfo.getProcess().equals(28)){
                List<FinancialExpenditure> financialExpenditureList = new ArrayList<>();
                for (OaInputDto oaInputDto : oaInputDtos) {
                    if(!"子表单".equals(oaInputDto.getName())){
                        continue;
                    }
                    String submitForm = oaInputDto.getModel();
                    if(Objects.isNull(formData.get(submitForm))){
                        continue;
                    }
                    List<HashMap> hashMaps = JSONObject.parseArray(formData.get(submitForm).toString(), HashMap.class);
                    nullUser: for (HashMap hashMap : hashMaps) {
                        FinancialExpenditure financialExpenditure = new FinancialExpenditure();
                        financialExpenditure.setBatchNo(pWorkOrderInfo.getId().toString());
                        financialExpenditure.setFinancialProcessNo(pWorkOrderInfo.getId().toString());
                        financialExpenditure.setApplyUser(realName);
                        financialExpenditure.setApplyUserId(pWorkOrderInfo.getCreator());
                        financialExpenditure.setProcessId(pWorkOrderInfo.getProcess());
                        List<OaColumnDto> columns = oaInputDto.getColumns();
                        if(columns != null && columns.size() > 0){
                            for (OaColumnDto column : columns) {
                                List<OaInputDto> columnList = column.getList();
                                if(columnList != null && columnList.size() > 0){
                                    for (OaInputDto inputDto : columnList) {
                                        String name = inputDto.getName();
                                        if(name.contains("课程组编号")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setVipGroupId(Long.parseLong(o.toString()));
                                                continue;
                                            }
                                        }else if(name.contains("课程类型")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setGroupType(o.toString());
                                                continue;
                                            }
                                        }else if(name.contains("乐团编号")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setMusicGroupId(o.toString());
                                                continue;
                                            }
                                        }else if(name.contains("退费项目")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setReturnFeeType(o.toString());
                                                continue;
                                            }
                                        }else if(name.contains("学员编号")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setStudentId(Integer.parseInt(o.toString()));
                                                continue;
                                            }else {
                                                continue nullUser;
                                            }
                                        }else if(name.contains("分部")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                int organId = Integer.parseInt(o.toString());
                                                Organization organization = organizationDao.get(organId);
                                                if(organization != null){
                                                    financialExpenditure.setOrganId(organization.getId());
                                                    financialExpenditure.setOrganName(organization.getName());
                                                }
                                                continue;
                                            }
                                        }else if(name.contains("金额") || name.contains("住宿费") || name.contains("出差补助") || name.contains("交通费")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setAmount(financialExpenditure.getAmount().add(new BigDecimal(Double.parseDouble(o.toString()))));
                                                continue;
                                            }
                                        }else if(name.contains("情况说明")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setCause(o.toString());
                                                continue;
                                            }
                                        }else if(name.contains("支出类型")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setType(ExpenditureTypeEnum.valueOfDesc(o.toString()));
                                                continue;
                                            }
                                        }else if(name.contains("费用类型")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setFeeProject(FeeProjectEnum.valueOfDesc(o.toString()));
                                                continue;
                                            }
                                        }else if(name.contains("住宿费")){
                                            Object o = hashMap.get(inputDto.getModel());
                                            if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                                financialExpenditure.setFeeProject(FeeProjectEnum.valueOfDesc(o.toString()));
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        financialExpenditureList.add(financialExpenditure);
                    }
                }
                //课程退费
                if(pWorkOrderInfo.getProcess().equals(22)){
                    for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                        ReturnFeeDto returnFeeDto = new ReturnFeeDto();
                        returnFeeDto.setGroupType(GroupType.valueOfDesc(financialExpenditure.getGroupType()));
                        returnFeeDto.setAmount(financialExpenditure.getAmount());
                        returnFeeDto.setStudentId(financialExpenditure.getStudentId());
                        returnFeeDto.setConfirmReturnActivityGive(true);
                        returnFeeDto.setGroupId(financialExpenditure.getVipGroupId());
                        returnFeeDto.setVipGroupId(financialExpenditure.getVipGroupId());
                        if(returnFeeDto.getGroupType() == GroupType.VIP){
                            vipGroupService.applyRefundForStudentOa(returnFeeDto);
                        }else if(returnFeeDto.getGroupType() == GroupType.COMM || returnFeeDto.getGroupType() == GroupType.PRACTICE){
                            groupClassService.cancelGroupOa(returnFeeDto);
                        }
                    }
                }else if(pWorkOrderInfo.getProcess().equals(33) || pWorkOrderInfo.getProcess().equals(19)){
                    //退团
                    for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                        String returnFeeType = financialExpenditure.getReturnFeeType();
                        if(StringUtils.isNotEmpty(returnFeeType)){
                            if(returnFeeType.contains("乐器")){
                                financialExpenditure.setRefundInstrumentFeeFlag(true);
                            }
                            if(returnFeeType.contains("乐保")){
                                financialExpenditure.setMaintenanceFeeFlag(true);
                            }
                            if(returnFeeType.contains("教辅")){
                                financialExpenditure.setRefundTeachingAssistantsFeeFlag(true);
                            }
                        }
                    }
                    //处理excel文件
                    List<FinancialExpenditure> financialExpenditures = new ArrayList<>();
                    if(StringUtils.isNotEmpty(fileUrl)){
                        String[] split = fileUrl.split(",");
                        for (String s : split) {
                            URL url = new URL(s);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setConnectTimeout(3*1000);
                            File file = File.createTempFile(UUID.randomUUID().toString(), ".xls");
                            FileUtils.copyInputStreamToFile(conn.getInputStream(),file);
                            byte[] bytes = FileUtils.readFileToByteArray(file);
                            String fileName = file.getName();
                            //删除临时文件
                            if (file.exists()) {
                                file.delete();
                            }
                            financialExpenditures.addAll(financialExpenditureService.checkOaQuitMusicGroupExcel(bytes, fileName));
                        }
                        //去除重复数据
                        financialExpenditures.removeAll(Collections.singleton(null));
                        if(CollectionUtils.isNotEmpty(financialExpenditureList)){
                            for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                                if(financialExpenditures.contains(financialExpenditure)) {
                                    continue;
                                }
                                financialExpenditures.add(financialExpenditure);
                            }
                        }
                    }
                    if(CollectionUtils.isNotEmpty(financialExpenditures)){
                        for (FinancialExpenditure financialExpenditure : financialExpenditures) {
                            financialExpenditure.setApplyUser(realName);
                            financialExpenditure.setType(ExpenditureTypeEnum.REFUND);
                            financialExpenditure.setFeeProject(FeeProjectEnum.REFUND);
                            financialExpenditure.setBatchNo(pWorkOrderInfo.getId().toString());
                            financialExpenditure.setFinancialProcessNo(pWorkOrderInfo.getId().toString());
                        }
                        financialExpenditureList = financialExpenditures;
                    }
                    for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                        musicGroupService.directQuitMusicGroupOa(financialExpenditure);
                    }
                }
                financialExpenditureDao.batchInsert(financialExpenditureList);
            }else {
                FinancialExpenditure financialExpenditure = new FinancialExpenditure();
                financialExpenditure.setBatchNo(workOrderId.toString());
                financialExpenditure.setFinancialProcessNo(workOrderId.toString());
                financialExpenditure.setApplyUser(realName);
                financialExpenditure.setApplyUserId(pWorkOrderInfo.getCreator());
                financialExpenditure.setProcessId(pWorkOrderInfo.getProcess());
                Integer organId = financialExpenditureDao.getDeptId(pWorkOrderInfo.getDeptId());
                Organization organization = organizationDao.get(organId);
                if(organization != null){
                    financialExpenditure.setOrganId(organization.getId());
                    financialExpenditure.setOrganName(organization.getName());
                }
                for (OaInputDto oaInputDto : oaInputDtos) {
                    String name = oaInputDto.getName();
                    if(name.contains("金额")){
                        Object o = formData.get(oaInputDto.getModel());
                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                            financialExpenditure.setAmount(new BigDecimal(Double.parseDouble(o.toString())));
                            continue;
                        }
                    }else if(name.contains("情况说明")){
                        Object o = formData.get(oaInputDto.getModel());
                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                            financialExpenditure.setCause(o.toString());
                            continue;
                        }
                    }else if(name.contains("支出类型")){
                        Object o = formData.get(oaInputDto.getModel());
                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                            financialExpenditure.setType(ExpenditureTypeEnum.valueOfDesc(o.toString()));
                            continue;
                        }
                    }else if(name.contains("费用类型")){
                        Object o = formData.get(oaInputDto.getModel());
                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                            financialExpenditure.setFeeProject(FeeProjectEnum.valueOfDesc(o.toString()));
                            continue;
                        }
                    }
                }
                financialExpenditureDao.insert(financialExpenditure);
            }
        }
    }

    @Override
    public void checkCourseReturnFee(Map<String,String> paramMap) {
        String tplInfoId = paramMap.get("tplInfoId");
        if(StringUtils.isEmpty(tplInfoId)){
            throw new BizException("参数校验失败");
        }
        if(tplInfoId.equals("11") || tplInfoId.equals("8") || tplInfoId.equals("20")){
            String data = paramMap.get("formData");
            if(StringUtils.isEmpty(data)){
                return;
            }
            JSONObject formData = JSONObject.parseObject(data);
            String formStructure = financialExpenditureDao.getTplInfo(tplInfoId);
            OaFormStructureDto oaFormStructureDto = JSONObject.parseObject(formStructure, OaFormStructureDto.class);
            List<OaInputDto> oaInputDtos = oaFormStructureDto.getList();
            List<FinancialExpenditure> financialExpenditureList = new ArrayList<>();
            for (OaInputDto oaInputDto : oaInputDtos) {
                if(!"子表单".equals(oaInputDto.getName())){
                    continue;
                }
                String submitForm = oaInputDto.getModel();
                if(Objects.isNull(formData.get(submitForm))){
                    continue;
                }
                List<HashMap> hashMaps = JSONObject.parseArray(formData.get(submitForm).toString(), HashMap.class);
                nullUser: for (HashMap hashMap : hashMaps) {
                    FinancialExpenditure financialExpenditure = new FinancialExpenditure();
                    List<OaColumnDto> columns = oaInputDto.getColumns();
                    if(columns != null && columns.size() > 0){
                        for (OaColumnDto column : columns) {
                            List<OaInputDto> columnList = column.getList();
                            if(columnList != null && columnList.size() > 0){
                                for (OaInputDto inputDto : columnList) {
                                    String name = inputDto.getName();
                                    if(name.contains("课程组编号")){
                                        Object o = hashMap.get(inputDto.getModel());
                                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                            financialExpenditure.setVipGroupId(Long.parseLong(o.toString()));
                                            continue;
                                        }
                                    }else if(name.contains("课程类型")){
                                        Object o = hashMap.get(inputDto.getModel());
                                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                            financialExpenditure.setGroupType(o.toString());
                                            continue;
                                        }
                                    }else if(name.contains("乐团编号")){
                                        Object o = hashMap.get(inputDto.getModel());
                                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                            financialExpenditure.setMusicGroupId(o.toString());
                                            continue;
                                        }
                                    }else if(name.contains("学员编号")){
                                        Object o = hashMap.get(inputDto.getModel());
                                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                            financialExpenditure.setStudentId(Integer.parseInt(o.toString()));
                                            continue;
                                        }else {
                                            continue nullUser;
                                        }
                                    }else if(name.contains("金额")){
                                        Object o = hashMap.get(inputDto.getModel());
                                        if(Objects.nonNull(o) && StringUtils.isNotEmpty(o.toString())){
                                            financialExpenditure.setAmount(new BigDecimal(Double.parseDouble(o.toString())));
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    financialExpenditureList.add(financialExpenditure);
                }
            }
            if(CollectionUtils.isEmpty(financialExpenditureList)){
                return;
            }
            //课程退费
            if(tplInfoId.equals("11")){
                long count = financialExpenditureList.stream().filter(e -> StringUtils.isEmpty(e.getGroupType()) ||
                        Objects.isNull(e.getAmount()) ||
                        Objects.isNull(e.getStudentId()) ||
                        Objects.isNull(e.getVipGroupId())).count();
                if(count > 0l){
                    throw new BizException("表单信息有误,请核实");
                }
                for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                    ReturnFeeDto returnFeeDto = new ReturnFeeDto();
                    returnFeeDto.setGroupType(GroupType.valueOfDesc(financialExpenditure.getGroupType()));
                    returnFeeDto.setAmount(financialExpenditure.getAmount());
                    returnFeeDto.setStudentId(financialExpenditure.getStudentId());
                    returnFeeDto.setConfirmReturnActivityGive(true);
                    returnFeeDto.setGroupId(financialExpenditure.getVipGroupId());
                    returnFeeDto.setVipGroupId(financialExpenditure.getVipGroupId());
                    if(returnFeeDto.getGroupType() == GroupType.VIP){
                        vipGroupService.checkApplyRefundForStudentOa(returnFeeDto);
                    }else if(returnFeeDto.getGroupType() == GroupType.COMM || returnFeeDto.getGroupType() == GroupType.PRACTICE){
                        groupClassService.checkCancelGroupOa(returnFeeDto);
                    }
                }
            }else {
                long count = financialExpenditureList.stream().
                        filter(e -> StringUtils.isEmpty(e.getMusicGroupId()) ||
                        Objects.isNull(e.getAmount()) ||
                        Objects.isNull(e.getStudentId())).count();
                if(count > 0l){
                    throw new BizException("表单信息有误,请核实");
                }
                for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                    musicGroupService.checkDirectQuitMusicGroupOa(financialExpenditure);
                }
            }
        }
    }

    @Override
    public List<FinancialExpenditure> checkOaQuitMusicGroupExcel(byte[] buf,String filename) throws Exception {
        Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(buf), 2, filename);
        InputStream inputStream = new ClassPathResource("columnMapper.ini").getInputStream();
        Map<String, String> columns = IniFileUtil.readIniFile(inputStream, TemplateTypeEnum.OA_QUIT_MUSIC_GROUP.getMsg());
        List<FinancialExpenditure> financialExpenditureList = new ArrayList<>();
        List<Organization> organs = organizationDao.findAllOrgans(1);
        Map<String, List<Organization>> collect = organs.stream().collect(Collectors.groupingBy(Organization::getName));
        for (String e : sheetsListMap.keySet()) {
            List<Map<String, Object>> sheet = sheetsListMap.get(e);
            for (Map<String, Object> row : sheet) {
                if (row.size() == 0) {
                    continue;
                }
                JSONObject objectMap = new JSONObject();
                for (String s : row.keySet()) {
                    if (!columns.containsKey(s)) {
                        continue;
                    }
                    String columnValue = columns.get(s);
                    if(Objects.equals(columnValue,"refundInstrumentFeeFlag")
                            || Objects.equals(columnValue,"refundTeachingAssistantsFeeFlag")
                            || Objects.equals(columnValue,"maintenanceFeeFlag")
                            || Objects.equals(columnValue,"refundCourseFee")){
                        if(Objects.nonNull(row.get(s))){
                            objectMap.put(columnValue, Objects.equals("是",row.get(s))?true:false);
                        }
                    }else if(Objects.equals(columnValue,"organName")){
                        if(Objects.isNull(row.get(s)) || StringUtils.isEmpty(row.get(s).toString())){
                            throw new BizException("乐团退费模板错误: 请录入分部信息");
                        }
                        if(!collect.containsKey(row.get(s).toString())){
                            throw new BizException("乐团退费模板错误: 分部 {} 不存在",row.get(s).toString());
                        }
                        objectMap.put("organId",collect.get(row.get(s).toString()).get(0).getId());
                    }else {
                        objectMap.put(columnValue, row.get(s));
                    }
                }
                FinancialExpenditure financialExpenditure = JSONObject.parseObject(objectMap.toJSONString(),FinancialExpenditure.class);
                if(StringUtils.isEmpty(financialExpenditure.getMusicGroupId())
                        || Objects.isNull(financialExpenditure.getStudentId())){
                    throw new BizException("乐团退费模板错误: 乐团编号或学员编号不可为空");
                }
                if(Objects.isNull(financialExpenditure.getOrganId())){
                    throw new BizException("乐团退费模板错误: 请填写分部信息");
                }
                if(Objects.isNull(financialExpenditure.getAmount())){
                    throw new BizException("乐团退费模板错误: 退费金额不可为空");
                }
                if(StringUtils.isEmpty(financialExpenditure.getMerNo()) ||
                        StringUtils.isEmpty(financialExpenditure.getBankAddress()) ||
                        StringUtils.isEmpty(financialExpenditure.getMerNoName())){
                    throw new BizException("乐团退费模板错误: 请完整填写收款账户信息");
                }
                financialExpenditureList.add(financialExpenditure);
            }
        }
        if(CollectionUtils.isNotEmpty(financialExpenditureList)){
            for (FinancialExpenditure financialExpenditure : financialExpenditureList) {
                musicGroupService.checkDirectQuitMusicGroupOa(financialExpenditure);
            }
        }
        return financialExpenditureList;
    }
}
