package com.fdkankan.agent.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fdkankan.agent.common.ResultCode;
import com.fdkankan.agent.entity.AgentNewCamera;
import com.fdkankan.agent.entity.Camera;
import com.fdkankan.agent.entity.CameraDetail;
import com.fdkankan.agent.exception.BusinessException;
import com.fdkankan.agent.request.AuthModelingParam;
import com.fdkankan.agent.response.AgentNewVo;
import com.fdkankan.agent.service.*;
import com.fdkankan.agent.util.ExcelErrorUtil;
import com.fdkankan.agent.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.util.ArrayListWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
/**
*
* TODO
*
*
* @author dengsixing
* @since 2022/6/6
**/
@Service
@Slf4j
public class ExcelServiceImpl implements IExcelService {
@Autowired
IAgentNewCameraService agentNewCameraService;
@Autowired
ICameraService cameraService;
@Autowired
ICameraDetailService cameraDetailService;
@Autowired
IAgentAuthorizeModelingService agentAuthorizeModelingService;
@Autowired
IAgentNewService agentNewService;
public void commonExport(HttpServletRequest request, HttpServletResponse response,String name,List> result,ExcelWriter excelWriter) throws Exception {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = name + ".xlsx";
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
WriteSheet writeSheet = EasyExcel.writerSheet(name).build();
excelWriter.write(result, writeSheet);
}
@Override
public Integer uploadExcel(MultipartFile file, Integer agentId,Integer subAgentId) {
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
String fileType=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
if (!fileType.equalsIgnoreCase("xlsx")) {
throw new BusinessException(ResultCode.FILE_TYPE_ERROR);
}
List> excelRowList = new ArrayList<>();
try {
excelRowList = ExcelUtil.getExcelRowList(file);
}catch (Exception e){
log.info("uploadExcel-error:{}",e);
throw new BusinessException(ResultCode.TEMPLATE_TYPE_ERROR);
}
List errorIndex = new ArrayList<>();
List snCodes = new ArrayList<>();
List cameraIds = new ArrayList<>();
Integer index = 0;
for (HashMap map : excelRowList) {
index ++;
if(map.isEmpty()){
continue;
}
if(index == 0 && !map.get(0).equals("分销商设备清单")){
throw new BusinessException(ResultCode.TEMPLATE_TYPE_ERROR);
}
if(index <4){ //从第四行开始
continue;
}
String snCode = map.get(0);
if(StringUtils.isBlank(snCode)){
errorIndex.add(index);
continue;
}
if(StringUtils.isNotBlank(snCode)){
Camera camera = cameraService.getBySnCode(snCode);
if(camera == null){
errorIndex.add(index);
continue;
}
CameraDetail cameraDetail = cameraDetailService.getByCameraId(camera.getId());
if(cameraDetail == null || cameraDetail.getAgentId() == null){
errorIndex.add(index);
continue;
}
if(!cameraDetail.getAgentId().equals(agentId)){
List bySubAgent = agentNewCameraService.getBySubAgent(camera.getId(), agentId);
if(bySubAgent.isEmpty()){
errorIndex.add(index);
continue;
}
}
cameraIds.add(camera.getId());
}
snCodes.add(snCode);
}
this.toExcelError(errorIndex);
if(!cameraIds.isEmpty()){
return agentNewCameraService.giveCameraBatch(cameraIds,agentId,subAgentId);
}
return 0;
}
@Override
public synchronized Integer uploadAuthModelExcel(MultipartFile file, Integer agentId) {
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
String fileType=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
if (!fileType.equalsIgnoreCase("xlsx")) {
throw new BusinessException(ResultCode.FILE_TYPE_ERROR);
}
List> excelRowList = new ArrayList<>();
List> excelRowListTemplate = new ArrayList<>();
try {
excelRowList = ExcelUtil.getExcelRowList(file);
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/authModel.xlsx");
excelRowListTemplate = ExcelUtil.getExcelRowList(inputStream);
}catch (Exception e){
log.info("uploadExcel-error:{}",e);
throw new BusinessException(ResultCode.TEMPLATE_TYPE_ERROR);
}
HashMap mapt = excelRowListTemplate.get(0);
HashMap map1 = excelRowList.get(0);
if(!mapt.equals(map1)){
throw new BusinessException(ResultCode.TEMPLATE_TYPE_ERROR);
}
HashMap agentMap = new HashMap<>();
List errorIndex = new ArrayList<>();
List params = new ArrayList();
HashSet authSet = new HashSet<>();
Integer index = 0;
for (HashMap map : excelRowList) {
index ++;
if(map.isEmpty()){
continue;
}
if(index <2){ //从第四行开始
continue;
}
String customerAccount = map.get(0);
String endCustomer = map.get(1);
String authSn = map.get(2);
String distributorName = map.get(3);
String createDate = map.get(4);
String acitvated = map.get(5);
String activateDate = map.get(6);
String expirationDay = map.get(7);
if(StringUtils.isBlank(authSn) || StringUtils.isBlank(customerAccount) || StringUtils.isBlank(endCustomer) || StringUtils.isBlank(activateDate) || StringUtils.isBlank(expirationDay)){
log.info("数据错误:{}",map);
errorIndex.add(index);
continue;
}
log.info("activateDate:{}",activateDate);
AuthModelingParam param = new AuthModelingParam();
if(StringUtils.isNotBlank(activateDate) && StringUtils.isNotBlank(expirationDay)){
try {
DateTime parse = DateUtil.parse(activateDate, "yyyy-MM-dd");
DateTime dateTime = DateUtil.offsetDay(parse, Integer.parseInt(expirationDay));
param.setStartTime(parse);
param.setEndTime(dateTime);
}catch (Exception e){
errorIndex.add(index);
log.info("解析激活时间错误:{},{}",activateDate,expirationDay);
}
}
if(authSet.contains(authSn)){
errorIndex.add(index);
continue;
}
param.setCreateAgentId(agentId);
if(StringUtils.isNotBlank(distributorName)){
AgentNewVo agentNewVo;
if(agentMap.containsKey(distributorName)){
agentNewVo = agentMap.get(distributorName);
}else {
agentNewVo =agentNewService.getByUserName(distributorName);
agentMap.put(distributorName,agentNewVo);
}
if(agentNewVo!=null){
param.setAgentId(agentNewVo.getId());
}
}
authSet.add(authSn);
param.setAuthCode(authSn);
param.setCustomerAccount(customerAccount);
param.setEndCustomer(endCustomer);
params.add(param);
}
if(!params.isEmpty()){
agentAuthorizeModelingService.addByParam(params);
}
this.toExcelError(errorIndex);
return 0;
}
public void toExcelError(List errorList) {
String resultIn = ExcelErrorUtil.getResultIn(errorList);
if(StringUtils.isNotBlank(resultIn)){
throw new BusinessException(ResultCode.UPLOAD_EXCEL_ERROR,resultIn);
}
}
}