package com.jpsoft.shinestar.modules.base.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.domain.Person;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.dto.MeetingPersonDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.POIUtils;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/meetingInfo")
public class MeetingInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MeetingInfoService meetingInfoService;

    @Autowired
    private MeetingTimeService meetingTimeService;

    @Autowired
    private AddressInfoService addressInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private MeetingPersonService meetingPersonService;

    @Autowired
    private MeetingAddressService meetingAddressService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private OSSConfig ossConfig;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<MeetingInfo> create(){
        MessageResult<MeetingInfo> msgResult = new MessageResult<>();

        MeetingInfo meetingInfo = new MeetingInfo();

        List<MeetingTime> meetingTimeList = new ArrayList<>();

        List<MeetingTime> removeMeetingTimeList = new ArrayList<>();

        meetingInfo.setMeetingTimeDataList(meetingTimeList);
        meetingInfo.setRemoveMeetingTimeList(removeMeetingTimeList);

        msgResult.setData(meetingInfo);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<MeetingInfo> add(@RequestBody MeetingInfo meetingInfo,@RequestAttribute String subject){
        MessageResult<MeetingInfo> msgResult = new MessageResult<>();

        try {
            meetingInfo.setId(UUID.randomUUID().toString());
            meetingInfo.setCreateBy(subject);
            meetingInfo.setCreateTime(new Date());
            meetingInfo.setDelFlag(false);
            meetingInfo.setStatus("1");
            meetingInfo.setPushStatus("0");

            int affectCount = meetingInfoService.insertAndPerson(meetingInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(meetingInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<MeetingInfo> detail(@PathVariable("id") String id){
        MessageResult<MeetingInfo> msgResult = new MessageResult<>();

        try {
            long beginTime = System.currentTimeMillis();

            MeetingInfo meetingInfo = meetingInfoService.get(id);

            if (meetingInfo != null) {
                List<MeetingTime> meetingTimeList = meetingTimeService.findByMeetingId(meetingInfo.getId());

                for (MeetingTime meetingTime:meetingTimeList) {
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(meetingTime.getMeetingTime());
                    String start = (String)jsonObject.get("start");
                    String end = (String)jsonObject.get("end");
                    meetingTime.setMeetingTimeRange(start + "," + end);

                    String[] meetingTimeArray = {start,end};
                    meetingTime.setMeetingTimeArray(meetingTimeArray);

                    net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(meetingTime.getStartSignInTime());
                    String start1 = (String)jsonObject1.get("start");
                    String end1 = (String)jsonObject1.get("end");
                    meetingTime.setStartSignInTimeRange(start1 + "," + end1);

                    String[] startSignInTimeArray = {start1,end1};
                    meetingTime.setStartSignInTimeArray(startSignInTimeArray);

                    net.sf.json.JSONObject jsonObject2 = net.sf.json.JSONObject.fromObject(meetingTime.getEndSignInTime());

                    if(jsonObject2.containsKey("start") && jsonObject2.containsKey("end")){
                        String start2 = (String)jsonObject2.get("start");
                        String end2 = (String)jsonObject2.get("end");
                        meetingTime.setEndSignInTimeRange(start2 + "," + end2);

                        String[] endSignInTimeArray = {start2,end2};
                        meetingTime.setEndSignInTimeArray(endSignInTimeArray);
                    }
                }

                logger.error("meetingTimeService.findByMeetingId 耗时:" + (System.currentTimeMillis() - beginTime));
                beginTime = System.currentTimeMillis();

                List<MeetingTime> removeMeetingTimeList = new ArrayList<>();

                meetingInfo.setMeetingTimeDataList(meetingTimeList);
                meetingInfo.setRemoveMeetingTimeList(removeMeetingTimeList);

                List<MeetingPerson> list = meetingPersonService.findByMeetingId(meetingInfo.getId());

                logger.error("meetingPersonService.findByMeetingId 耗时:" + (System.currentTimeMillis() - beginTime));
                beginTime = System.currentTimeMillis();

                String selectPersonKey = "";

                List<MeetingPersonDTO> dtoList = new ArrayList<>();

                for (MeetingPerson meetingPerson:list) {
                    selectPersonKey += meetingPerson.getPersonId() + ",";

                    MeetingPersonDTO dto = new MeetingPersonDTO();
                    dto.setKey(meetingPerson.getPersonId().toString());
                    dto.setLabel(meetingPerson.getPersonName() + "-" + meetingPerson.getCompanyName());

                    dtoList.add(dto);
                }

                if(StringUtils.isNotEmpty(selectPersonKey)){
                    selectPersonKey = selectPersonKey.substring(0,selectPersonKey.lastIndexOf(","));
                }

                if(StringUtils.isNotEmpty(meetingInfo.getSearchCompanyId())){
                    String[] arrCompanyId = meetingInfo.getSearchCompanyId().split(",");
                    meetingInfo.setSearchCompanyIds(arrCompanyId);
                }

                meetingInfo.setSelectPersonDto(dtoList);
                meetingInfo.setSelectPersonKey(selectPersonKey);

                msgResult.setResult(true);
                msgResult.setData(meetingInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<MeetingInfo> update(@RequestBody MeetingInfo meetingInfo,@RequestAttribute String subject){
        MessageResult<MeetingInfo> msgResult = new MessageResult<>();

        try {
            meetingInfo.setUpdateBy(subject);
            meetingInfo.setUpdateTime(new Date());

            int affectCount = meetingInfoService.updateAndPerson(meetingInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(meetingInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="删除用户")
    @PostMapping("delete/{id}")
    public MessageResult<MeetingInfo> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<MeetingInfo> msgResult = new MessageResult<>();

        try {
            MeetingInfo meetingInfo = meetingInfoService.get(id);
            meetingInfo.setDelFlag(true);
            meetingInfo.setUpdateBy(subject);
            meetingInfo.setUpdateTime(new Date());

            int affectCount = meetingInfoService.update(meetingInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                MeetingInfo meetingInfo = meetingInfoService.get(id);
                meetingInfo.setDelFlag(true);
                meetingInfo.setUpdateBy(subject);
                meetingInfo.setUpdateTime(new Date());

                affectCount += meetingInfoService.update(meetingInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String name,String pushStatus,String meetingDateRange,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        try {
            //加载前更新加载数据
            updateMeetingData();


            Map<String, Object> searchParams = new HashMap<>();

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));

            if (StringUtils.isNotEmpty(name)) {
                searchParams.put("name", "%" + name + "%");
            }

            if (StringUtils.isNotEmpty(pushStatus)) {
                searchParams.put("pushStatus", pushStatus);
            }

            if (StringUtils.isNotEmpty(meetingDateRange)) {
                String[] timeRangeArray = meetingDateRange.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime+=" 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime+=" 00:00:00";
                    endTime+=" 23:59:59";
                }

                searchParams.put("beginTime", beginTime);
                searchParams.put("endTime", endTime);
            }


            Page<MeetingInfo> page = meetingInfoService.pageSearch(searchParams, pageIndex, pageSize, sortList);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            for (MeetingInfo meetingInfo : page) {
                List<MeetingTime> list = meetingTimeService.findByMeetingId(meetingInfo.getId());
                List<String> meetingDateList = new ArrayList<>();
                List<String> meetingTimeList = new ArrayList<>();
                List<String> startSignInTimeList = new ArrayList<>();
                List<String> endSignInTimeList = new ArrayList<>();

                for (MeetingTime meetingTime : list) {
                    Date meetingDate = meetingTime.getMeetingDate();
                    if (meetingDate != null) {
                        meetingDateList.add(sdf.format(meetingDate));
                    }

                    String meetingTimeStr = meetingTime.getMeetingTime();
                    if (StringUtils.isNotEmpty(meetingTimeStr)) {
                        JSONObject jsonObject = JSONUtil.parseObj(meetingTimeStr);
                        String start = jsonObject.get("start").toString();
                        String end = jsonObject.get("end").toString();
                        meetingTimeList.add(start + "-" + end);
                    }

                    String startSignInTimeStr = meetingTime.getStartSignInTime();
                    if (StringUtils.isNotEmpty(startSignInTimeStr)) {
                        JSONObject jsonObject = JSONUtil.parseObj(startSignInTimeStr);
                        String start = jsonObject.get("start").toString();
                        String end = jsonObject.get("end").toString();
                        startSignInTimeList.add(start + "-" + end);
                    }

                    String endSignInTimeStr = meetingTime.getEndSignInTime();
                    if (StringUtils.isNotEmpty(endSignInTimeStr)) {
                        JSONObject jsonObject = JSONUtil.parseObj(endSignInTimeStr);
                        String start = jsonObject.get("start").toString();
                        String end = jsonObject.get("end").toString();
                        endSignInTimeList.add(start + "-" + end);
                    }
                }
                meetingInfo.setMeetingDateList(meetingDateList);
                meetingInfo.setMeetingTimeList(meetingTimeList);
                meetingInfo.setStartSignInTimeList(startSignInTimeList);
                meetingInfo.setEndSignInTimeList(endSignInTimeList);

                String addressId = meetingInfo.getAddressId();
                AddressInfo addressInfo = addressInfoService.findByMeetingIdAndAddressId(meetingInfo.getId(), addressId);
                if (addressInfo != null) {
                    meetingInfo.setAddressName(addressInfo.getName());
                }
                User user = userService.get(meetingInfo.getCreateBy());
                if(user!=null){
                    meetingInfo.setCreateName(user.getRealName());
                }

                String statusN = dataDictionaryService.findNameByCatalogNameAndValue("会议状态",meetingInfo.getStatus());
                meetingInfo.setStatusN(statusN);

                String pushStatusN = dataDictionaryService.findNameByCatalogNameAndValue("推送状态",meetingInfo.getPushStatus());
                meetingInfo.setPushStatusN(pushStatusN);

            }

            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(page));
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    //加载前更新加载数据
    private void updateMeetingData() throws ParseException {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MeetingInfo> list = meetingInfoService.notEndList();

        for (MeetingInfo meetingInfo:list) {
            List<MeetingTime> meetingTimeList = meetingTimeService.findByMeetingId(meetingInfo.getId());

            List<Date> meetingEndDateTimeList = new ArrayList<>();
            for (MeetingTime meetingTime:meetingTimeList) {
                Date meetingDate = meetingTime.getMeetingDate();
                String meetingTimeStr = meetingTime.getMeetingTime();

                if(StringUtils.isNotEmpty(meetingTimeStr)) {
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(meetingTimeStr);
                    String start = jsonObject.get("start").toString();
                    String end = jsonObject.get("end").toString();

                    String meetingDateStr = sdf.format(meetingDate);
                    String startDateTimeStr = meetingDateStr + " " + start + ":00";
                    String endDateTimeStr = meetingDateStr + " " + end + ":00";

                    Date meetingStartDateTime = sdf1.parse(startDateTimeStr);
                    Date meetingEndDateTime = sdf1.parse(endDateTimeStr);

                    meetingEndDateTimeList.add(meetingEndDateTime);

                    if(now.compareTo(meetingStartDateTime) >= 0){
                        //会议进行中
                        meetingInfo.setStatus("2");
                        meetingInfo.setUpdateTime(now);
                        int count = meetingInfoService.update(meetingInfo);
                    }
                }

            }

            boolean isEnd = false;

            for (Date date:meetingEndDateTimeList) {
                if(now.compareTo(date) < 0){
                    isEnd = true;
                    break;
                }
            }

            if(!isEnd){
                //会议已结束
                meetingInfo.setStatus("3");
                meetingInfo.setUpdateTime(now);
                int count = meetingInfoService.update(meetingInfo);
            }
        }
    }



    @ApiOperation(value="部门人员列表")
    @PostMapping("personListByCompanyId")
    public MessageResult<List<MeetingPersonDTO>> personListByCompanyId(String companyId){
        MessageResult<List<MeetingPersonDTO>> msgResult = new MessageResult<>();

        try {
            List<PersonInfo> list = new ArrayList<>();

            if(StringUtils.isNotEmpty(companyId)){
                String[] companyIdArray = companyId.split(",");

                for (String companyIdStr:companyIdArray) {
                    CompanyInfo companyInfo = companyInfoService.get(companyIdStr);
                    List<PersonInfo> curPersonList = personInfoService.findListByCompanyCode(companyInfo.getCode() + "%");

                    if(curPersonList.size()>0){
                        list.addAll(curPersonList);
                    }
                }
            }
            else{
                list = personInfoService.list();
            }

            List<MeetingPersonDTO> dtoList = new ArrayList<>();
            Set<Long> personIdSet = new HashSet<>();

            for (PersonInfo personInfo:list) {
                if(!personIdSet.contains(personInfo.getId())){
                    MeetingPersonDTO dto = new MeetingPersonDTO();
                    dto.setKey(personInfo.getId().toString());
                    dto.setLabel(personInfo.getName() + "-" + personInfo.getCompanyName());

                    dtoList.add(dto);

                    personIdSet.add(personInfo.getId());
                }
            }

            msgResult.setResult(true);
            msgResult.setData(dtoList);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="修改会议状态")
    @PostMapping("updateStatus/{id}")
    public MessageResult<Object> updateStatus(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            MeetingInfo meetingInfo = meetingInfoService.get(id);

            meetingInfo.setStatus("4");
            meetingInfo.setUpdateBy(subject);
            meetingInfo.setUpdateTime(new Date());

            int affectCount = meetingInfoService.update(meetingInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("修改失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="推送消息")
    @PostMapping("sendMessage/{id}")
    public MessageResult<MeetingInfo> sendMessage(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<MeetingInfo> msgResult = new MessageResult<>();

        try {
            MeetingInfo meetingInfo = meetingInfoService.get(id);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            if (meetingInfo != null) {
                if(meetingInfo.getStatus().equals("1")){
                    new Thread(()-> {
                        try {
                            //未开始的会议才能推送消息
                            String meetingDateTime="";
                            String addressName ="";
                            String remark ="会议时间表：";

                            AddressInfo addressInfo = addressInfoService.get(meetingInfo.getAddressId());
                            if(addressInfo!=null){
                                addressName = addressInfo.getName();
                            }


                            List<MeetingTime> list = meetingTimeService.findByMeetingId(meetingInfo.getId());

                            for (MeetingTime meetingTime:list) {
                                Date meetingDate = meetingTime.getMeetingDate();
                                String meetingDateStr = sdf.format(meetingDate);
                                String meetingTimeStr = meetingTime.getMeetingTime();
                                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(meetingTimeStr);
                                String start = jsonObject.get("start").toString();
                                String end = jsonObject.get("end").toString();

                                String meetingStartDateTimeStr = meetingDateStr + " " + start + ":00";
                                String meetingEndDateTimeStr = meetingDateStr + " " + end + ":00";

                                meetingDateTime = meetingStartDateTimeStr + "至" + meetingEndDateTimeStr;

                                remark += meetingStartDateTimeStr + "至" + meetingEndDateTimeStr+",";
                            }

                            if(StringUtils.isNotEmpty(remark)){
                                remark = remark.substring(0,remark.lastIndexOf(","));
                            }

                            List<MeetingPerson> meetingPersonList = meetingPersonService.findByMeetingId(meetingInfo.getId());


                            for (MeetingPerson meetingPerson : meetingPersonList) {
                                PersonInfo personInfo = personInfoService.get(meetingPerson.getPersonId());
                                if (personInfo != null) {
                                    boolean result = WechatMessageUtil.sendMeetingMessage(personInfo.getOpenId(), meetingInfo.getName(), meetingInfo.getName(), meetingDateTime, addressName, remark, null, wxConfig.getAppId(), wxConfig.getAppSecret());
                                }
                            }
                        }
                        catch(Exception ex){
                            logger.error(ex.getMessage(),ex);
                        }
                    }).start();

                    msgResult.setResult(true);
                }
                else{
                    msgResult.setResult(false);
                    msgResult.setMessage("推送失败，会议已开始，已关闭或已结束不能推送消息！");
                }
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据不存在！");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }




    @ApiOperation(value = "导入人员")
    @PostMapping("importXls")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uploadFile", value = "上传文件", required = true, paramType = "form", dataType = "__file")
    })
    public MessageResult<Object> importXls(MultipartFile uploadFile,
                                           @RequestAttribute String subject) {
        User user = userService.get(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            POIUtils poiUtils = new POIUtils(uploadFile.getInputStream());
            int sheetIndex = 0;
            Sheet sheet1 = poiUtils.getSheetAt(sheetIndex);

            int affectCount = 0;
            int failCount = 0;
            int validateColIndex = 10;

            List<MeetingPersonDTO> dtoList = new ArrayList<>();

            for (int rowIndex = 1; rowIndex <= sheet1.getLastRowNum(); rowIndex++) {
                try {
                    String name = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 0).toString().replace(" ", "");
                    String jobNumber = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 1).toString().replace(" ", "");

                    if (StringUtils.isEmpty(jobNumber)) {
                        break;
                    }

                    PersonInfo personInfo = personInfoService.findJobNumber(jobNumber);

                    if (personInfo == null) {
                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("公司不存在的人员!");
                        failCount++;
                        continue;
                    } else {

                        MeetingPersonDTO dto = new MeetingPersonDTO();
                        dto.setKey(personInfo.getId().toString());
                        dto.setLabel(personInfo.getName());

                        dtoList.add(dto);

                        affectCount++;
                    }
                } catch (Exception innerEx) {
                    logger.error(innerEx.getMessage(), innerEx);
                }
            }

            if (failCount > 0) {
                //有导入失败的记录
                msgResult.setResult(false);
                msgResult.setMessage("数据成功导入" + affectCount + "条,有" + failCount + "条数据未导入成功，错误原因请查看报表。");

                //todo 只保留错误数据的sheet
                Workbook wb = poiUtils.exportErrorXls(sheetIndex, validateColIndex, 1 + affectCount + failCount);

                //todo 将wb保存到oss
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                wb.write(output);

                byte[] buffer = output.toByteArray();
                ByteArrayInputStream input = new ByteArrayInputStream(buffer);

                String downloadUrl = OSSUtil.upload(ossConfig, "import", "error.xls", input);

                //todo 返回导入失败报表下载链接
                msgResult.setData(downloadUrl);
            } else {
                msgResult.setResult(true);
                msgResult.setMessage("数据成功导入" + affectCount + "条");
                msgResult.setData(dtoList);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


}
