package org.springblade.audit.controller;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.util.StrUtil;
import org.springblade.audit.dto.AuditFileDTO;
import org.springblade.audit.dto.IntBalanceDetailDTO;
import org.springblade.audit.dto.IntFzzDisconutDTO;
import org.springblade.audit.dto.IntProvinceIrregularDTO;
import org.springblade.audit.dto.IntProvinceViolationDTO;
import org.springblade.audit.dto.YksytRefundForCpDTO;
import org.springblade.audit.entity.AuditUploadFile;
import org.springblade.audit.entity.AuditUploadUser;
import org.springblade.audit.entity.IntBalanceDetail;
import org.springblade.audit.entity.IntFzzDiscount;
import org.springblade.audit.entity.IntProvinceIrregular;
import org.springblade.audit.entity.IntProvinceViolation;
import org.springblade.audit.entity.IntTmpAccountList;
import org.springblade.audit.entity.YksytRefundForCp;
import org.springblade.audit.enums.AuditsEnum;
import org.springblade.audit.listener.IntBalanceDetailListener;
import org.springblade.audit.listener.IntFzzDiscountListener;
import org.springblade.audit.listener.IntProvinceIrregularListener;
import org.springblade.audit.listener.IntProvinceViolationListener;
import org.springblade.audit.listener.YksytRefundForCpListener;
import org.springblade.audit.query.AuditFilePageQuery;
import org.springblade.audit.service.IAuditUploadFileService;
import org.springblade.audit.service.IAuditUploadUserService;
import org.springblade.audit.service.IIntBalanceDetailService;
import org.springblade.audit.service.IIntFzzDiscountService;
import org.springblade.audit.service.IIntProvinceIrregularService;
import org.springblade.audit.service.IIntProvinceViolationService;
import org.springblade.audit.service.IIntTmpAccountListService;
import org.springblade.audit.service.IYksytRefundForCpService;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author zbc
 * @since 2021-12-02
 */
@RestController
@RequestMapping("/audit/file")
@Api(value = "审核上传文件管理", tags = "审核上传文件接口")
@Slf4j
public class AuditUploadFileController {

	@Autowired
	private IAuditUploadFileService auditUploadFileService;

	@Autowired
	private IAuditUploadUserService auditUploadUserService;

	@Autowired
	private IIntFzzDiscountService intFzzDiscountService;

	@Autowired
	private IIntBalanceDetailService intBalanceDetailService;

	@Autowired
	private IIntProvinceViolationService intProvinceViolationService;

	@Autowired
	private IIntProvinceIrregularService intProvinceIrregularService;

	@Autowired
	private IIntTmpAccountListService intTmpAccountListService;

	@Autowired
	private IYksytRefundForCpService yksytRefundForCpService;

	@Autowired
	private UserClient userClient;

	private static String REGEX_CHINESE = "[\u4e00-\u9fa5]";


	@Value("${blade.file.uploadPath}")
	private String picDir;


	@PostMapping("/uploadFile")
	@ApiOperation("结算表文件上传")
	public R uploadFile(AuditFileDTO file) throws IOException {
		if (null == file || file.getFile() == null) {
			return R.fail("参数异常");
		}
		Long userId = SecureUtil.getUserId();
		AuditUploadUser audit = auditUploadUserService.getOne(new LambdaQueryWrapper<AuditUploadUser>()
			.eq(AuditUploadUser::getReportType, file.getReportType())
			.apply(userId != null,"find_in_set('"+userId+"',upload_id)")
		);
		if(audit == null){
			return R.fail("您没有上传权限");
		}

		String oFileName = file.getFile().getOriginalFilename();
		String fileSuffix = oFileName.substring(oFileName.lastIndexOf("."));
		log.info("结算表文件上传文件信息 oFileName = {}，fileSuffix = {}",oFileName,fileSuffix);
		if (
			!".xls".equalsIgnoreCase(fileSuffix) &&
			!".xlsx".equalsIgnoreCase(fileSuffix) &&
			!".txt".equalsIgnoreCase(fileSuffix) &&
			!".csv".equalsIgnoreCase(fileSuffix)
		) {
			return R.fail("只能上传xlsx/xls/txt/csv类型的文件");
		}

		String excelCode = file.getReportType();
		if(StringUtils.isBlank(excelCode)){
			return R.fail("导入报表编码不能为空");
		}
		//400 扣罚
		if (AuditsEnum.INT_400_KF.getCode().equals(excelCode)) {
			log.info("400 扣罚 上传校验");

			/*IntFzzDiscountListener easyExcelListener = new IntFzzDiscountListener();
			InputStream inputStream = file.getFile().getInputStream();
			EasyExcel.read(inputStream, IntFzzDisconutDTO.class, easyExcelListener).sheet().doRead();
			if(!easyExcelListener.sysHead){
				return R.fail("报表格式错误");
			}*/
			//BalanceDetail(PRM发布)
		} else if (AuditsEnum.INT_BALANCE_FB.getCode().equals(excelCode)) {
			log.info("BalanceDetail(PRM发布) 上传校验");
			try {
				String excelName = oFileName.substring(0,oFileName.lastIndexOf("."));
				String theCode = excelName.replaceAll("\\s*", "");
				String substring = theCode.substring(theCode.length() - 11, theCode.length());
				String theMonth = substring.substring(0, 6);
				log.info("BalanceDetail(PRM发布)校验月份 = {}",theMonth);
				if(!file.getTheMonth().equals(Long.valueOf(theMonth))){
					return R.fail("报表时间与选择的导入时间不一致");
				}

				/*IntBalanceDetailListener easyExcelListener = new IntBalanceDetailListener();
				InputStream inputStream = file.getFile().getInputStream();
				EasyExcel.read(inputStream, IntBalanceDetailDTO.class, easyExcelListener).sheet().doRead();

				if(!easyExcelListener.sysHead){
					return R.fail("报表格式错误");
				}*/

			}catch (Exception e){
				e.printStackTrace();
				return R.fail("报表名不符合导入要求");
			}
			//省分违约明细
		} else if (AuditsEnum.INT_VIOLATION_WY.getCode().equals(excelCode)) {
			log.info("省分违约明细 上传校验");
			try {
				String excelName = oFileName.substring(0,oFileName.lastIndexOf("."));
				Pattern pat = Pattern.compile(REGEX_CHINESE);
				Matcher mat = pat.matcher(excelName);
				String str = mat.replaceAll("");
				String strMonth = "";
				if(str.length() > 6){
					strMonth = str.substring(0,6);
				}else {
					strMonth = str;
				}
				String theMonth = strMonth;
				log.info("省分违约明细校验月份 = {}",theMonth);
				if(!file.getTheMonth().equals(Long.valueOf(theMonth))){
					return R.fail("报表时间与选择的导入时间不一致");
				}

				/*IntProvinceViolationListener easyExcelListener = new IntProvinceViolationListener();
				InputStream inputStream = file.getFile().getInputStream();
				EasyExcel.read(inputStream, IntProvinceViolationDTO.class, easyExcelListener).sheet().doRead();
				if(!easyExcelListener.sysHead){
					return R.fail("报表格式错误");
				}*/
			}catch (Exception e){
				e.printStackTrace();
				return R.fail("报表名不符合导入要求");
			}
			//不规范定制处罚明细
		} else if (AuditsEnum.INT_IRREGULAR_CF.getCode().equals(excelCode)) {
			log.info("不规范定制处罚明细 上传校验");
			try {
				String excelName = oFileName.substring(0,oFileName.lastIndexOf("."));
				Pattern pat = Pattern.compile(REGEX_CHINESE);
				Matcher mat = pat.matcher(excelName);
				String str = mat.replaceAll("");
				String strMonth = "";
				if(str.length() > 6){
					strMonth = str.substring(0,6);
				}else {
					strMonth = str;
				}
				String theMonth = strMonth;
				log.info("不规范定制处罚明细校验月份 = {}",theMonth);
				if(!file.getTheMonth().equals(Long.valueOf(theMonth))){
					return R.fail("报表时间与选择的导入时间不一致");
				}

				/*IntProvinceIrregularListener easyExcelListener = new IntProvinceIrregularListener();
				InputStream inputStream = file.getFile().getInputStream();
				EasyExcel.read(inputStream, IntProvinceIrregularDTO.class, easyExcelListener).sheet().doRead();
				if(!easyExcelListener.sysHead){
					return R.fail("报表格式错误");
				}*/
			}catch (Exception e){
				e.printStackTrace();
				return R.fail("报表名不符合导入要求");
			}
			//出账清单
		} else if (AuditsEnum.YKSYT_REFUND_FOR_CP.getCode().equals(excelCode)) {
			log.info("cp退费 上传校验");

			/*YksytRefundForCpListener easyExcelListener = new YksytRefundForCpListener();
			List<YksytRefundForCpDTO> excelList = easyExcelListener.list;
			InputStream inputStream = file.getFile().getInputStream();
			EasyExcel.read(inputStream, YksytRefundForCpDTO.class, easyExcelListener).sheet().doRead();
			if(!easyExcelListener.sysHead){
				return R.fail("报表格式错误");
			}*/
		}

		String tempFileName = UUID.randomUUID().toString() + fileSuffix;
		File f = new File(picDir + excelCode + "/" + tempFileName);
		try {
			cn.hutool.core.io.FileUtil.writeFromStream(file.getFile().getInputStream(), f);
//			FileUtils.copyInputStreamToFile(file.getFile().getInputStream(), f);
		} catch (IOException e) {
			e.printStackTrace();
			return R.fail("文件上传失败");
		}
		//String path = "uploads/" + excelCode + "/"+ tempFileName;
		//数据库取消存储uploads 前缀
		String path = excelCode + "/"+ tempFileName;
		String paths = picDir + excelCode + "/" + tempFileName;
		byte[] bytes = FileUtil.readBytes(paths);
//		byte[] bytes = FileUtil.readFileByBytes(paths);
		if(bytes == null || bytes.length == 0){
			return R.fail("上传失败，请重新上传");
		}

		AuditUploadFile auditFile = new AuditUploadFile();
		auditFile.setUploadId(userId);
		auditFile.setReportPath(path);
		auditFile.setReportType(file.getReportType());
		auditFile.setReportName(oFileName);
		auditFile.setStatus(1);
		auditFile.setTheMonth(file.getTheMonth());
		auditFile.setCreateTime(new Date());
		return R.data(auditUploadFileService.save(auditFile));
	}



	@GetMapping("/withdraw")
	@ApiOperation(value = "撤回上传文件")
	public R withdraw(Long id){
		Long userId = SecureUtil.getUserId();
		AuditUploadFile auditUploadFile = auditUploadFileService.getById(id);
		if(auditUploadFile == null){
			return R.fail("撤回数据不存在");
		}
		if(auditUploadFile.getUploadId() == null || !auditUploadFile.getUploadId().equals(userId)){
			return R.fail("只有上传人可以撤回");
		}

		if(auditUploadFile.getStatus() == null || auditUploadFile.getStatus() != 1){
			return R.fail("只有待审核的数据可以撤回");
		}
		if(removeFile(auditUploadFile.getReportPath())){
			return R.status(auditUploadFileService.removeById(id));
		}
		return R.fail("撤回失败");
	}


	private boolean removeFile(String path) {
        //path = "C:/Users/zero/Pictures/Saved Pictures/1.txt";
        System.out.println("removeFile the path = " + path);
        log.info("removeFile the path = {}",path);
		if(StrUtil.isBlank(path)){
			return false;
		}
        File file = new File(picDir + path);
        System.out.println("url = " + picDir + path);
        System.out.println("isFile = " + file.isFile());
        System.out.println("exists = " + file.exists());
        //文件
        if(file.isFile()){
            if(file.exists()){
                System.out.println("删除文件 exists = " + file.exists());
                log.info("删除文件 exists = {}",file.exists());
                return file.delete();
            }
        }
		return false;
	}


	@GetMapping("/page")
	@ApiOperation(value = "审核/上传列表")
	public R<IPage<AuditUploadFile>> page(AuditFilePageQuery pageQuery, Query query) {
		IPage<AuditUploadFile> page = Condition.getPage(query);
		IPage<AuditUploadFile> pages = auditUploadFileService.getPageByQuery(page, pageQuery);
		List<AuditUploadFile> records = pages.getRecords();
		for (AuditUploadFile record : records) {
			if(record.getAuditId() != null){
				UserModel userModel = userClient.getById(record.getAuditId());
				record.setAuditName(userModel.getRealName());
			}
			if(record.getUploadId() != null){
				UserModel userModel = userClient.getById(record.getUploadId());
				record.setUploadName(userModel.getRealName());
			}
			AuditsEnum[] values = AuditsEnum.values();
			for (AuditsEnum value : values) {
				if(value.getCode().equals(record.getReportType())){
					record.setReportTypeName(value.getName());
				}
			}
		}
		return R.data(pages);
	}


	@PostMapping("/submitAgain")
	@ApiOperation(value = "重新提交")
	public R submitAgain(AuditFileDTO file){
		Long userId = SecureUtil.getUserId();
		AuditUploadUser audit = auditUploadUserService.getOne(new LambdaQueryWrapper<AuditUploadUser>()
			.eq(AuditUploadUser::getReportType, file.getReportType())
			.in(AuditUploadUser::getAuditId, userId)
		);
		if(audit == null){
			return R.fail("您没有上传权限");
		}

		AuditUploadFile auditUploadFile = auditUploadFileService.getById(file.getAuditId());
		if(auditUploadFile == null){
			return R.fail("重新上传数据不存在");
		}
		auditUploadFile.setRemark(file.getRemark());
		auditUploadFile.setAuditTime(new Date());
		auditUploadFile.setAuditId(userId);
		auditUploadFile.setStatus(1);
		return R.status(auditUploadFileService.updateById(auditUploadFile));
	}



	@PostMapping("/reject")
	@ApiOperation(value = "驳回接口")
	public R<String> reject(AuditFileDTO file){
		Long userId = SecureUtil.getUserId();
		AuditUploadUser audit = auditUploadUserService.getOne(new LambdaQueryWrapper<AuditUploadUser>()
			.eq(AuditUploadUser::getReportType, file.getReportType())
			.eq(AuditUploadUser::getAuditId, userId)
		);
		if(audit == null){
			return R.fail("您没有驳回权限");
		}

		AuditUploadFile auditUploadFile = auditUploadFileService.getById(file.getAuditId());
		if(auditUploadFile == null){
			return R.fail("驳回数据不存在");
		}
		auditUploadFile.setRemark(file.getRemark());
		auditUploadFile.setAuditTime(new Date());
		auditUploadFile.setAuditId(userId);
		auditUploadFile.setStatus(3);
		return R.status(auditUploadFileService.updateById(auditUploadFile));
	}



	@PostMapping("/audit")
	@ApiOperation(value = "审核接口")
	public R audit(AuditFileDTO file) throws IOException {
		if(StringUtils.isBlank(file.getReportType())){
			return R.fail("报表类型不能为空");
		}
		if(file.getAuditId() == null){
			return R.fail("审核报表ID不能为空");
		}
		Long userId = SecureUtil.getUserId();
		AuditUploadUser audit = auditUploadUserService.getOne(new LambdaQueryWrapper<AuditUploadUser>()
			.eq(AuditUploadUser::getReportType, file.getReportType())
			.eq(AuditUploadUser::getAuditId, userId)
		);
		if(audit == null){
			return R.fail("您没有审核权限");
		}

		AuditUploadFile auditUploadFile = auditUploadFileService.getById(file.getAuditId());
		if(auditUploadFile == null){
			return R.fail("审核数据不存在");
		}
		auditUploadFile.setAuditId(userId);
		auditUploadFile.setAuditTime(new Date());
		auditUploadFile.setStatus(2);

		String paths = picDir + auditUploadFile.getReportPath();
//		byte[] bytes = FileUtil.readFileByBytes(paths);
		byte[] bytes = FileUtil.readBytes(paths);
		if(bytes == null || bytes.length == 0){
			return R.fail("文件不存在");
		}
		boolean res = auditUploadFileService.updateById(auditUploadFile);
		if(res){
			new Thread(new Runnable() {
				@Override
				public void run() {
					String excelCode = auditUploadFile.getReportType();
					//400 扣罚
					if (AuditsEnum.INT_400_KF.getCode().equals(excelCode)) {
						IntFzzDiscountImport(bytes,auditUploadFile.getTheMonth());
					}
					//BalanceDetail(PRM发布)
					if (AuditsEnum.INT_BALANCE_FB.getCode().equals(excelCode)) {
						IntBalanceDetailImport(bytes,auditUploadFile.getId());
					}
					//省分违约明细
					if (AuditsEnum.INT_VIOLATION_WY.getCode().equals(excelCode)) {
						IntProvinceViolationImport(bytes,auditUploadFile.getId());
					}
					//不规范定制处罚明细
					if (AuditsEnum.INT_IRREGULAR_CF.getCode().equals(excelCode)) {
						IntProvinceIrregularImport(bytes,auditUploadFile.getId());
					}
					//出账清单
					if (AuditsEnum.INT_ACCOUNT_CZ.getCode().equals(excelCode)) {
						intAccountlistImport(paths,auditUploadFile.getTheMonth());
					}
					//替CP退费
					if (AuditsEnum.YKSYT_REFUND_FOR_CP.getCode().equals(excelCode)) {
						yksytRefundForCpimport(bytes,auditUploadFile.getTheMonth());
					}
				}
			}).start();
		}
		return R.status(res);
	}

	private void yksytRefundForCpimport(byte[] bytes, Long theMonth) {
		log.info("替CP退费审核导入 --- 导入月份 = {}", theMonth);
		YksytRefundForCpListener easyExcelListener = new YksytRefundForCpListener();
		List<YksytRefundForCpDTO> excelList = easyExcelListener.list;

		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			EasyExcel.read(inputStream, YksytRefundForCpDTO.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());

			if(excelList.size() > 0 && theMonth != excelList.get(0).getThemonth()){
				log.info("替CP退费审核导入传入月份与数据月份不同 = {},{}", theMonth,excelList.get(0).getThemonth());
				theMonth = excelList.get(0).getThemonth();
			}
			List<YksytRefundForCp> voList = new ArrayList<YksytRefundForCp>();
			if (excelList != null && !excelList.isEmpty()) {
				for (YksytRefundForCpDTO obj : excelList) {
					try {
						YksytRefundForCp bean = new YksytRefundForCp();
						BeanUtils.copyProperties(obj, bean);
						//退费总金额
						if (org.apache.commons.lang3.StringUtils.isNotBlank(obj.getRefundMoney())) {
							String money = obj.getRefundMoney().replaceAll(",", "");
							bean.setRefundMoney(new BigDecimal(money));
						}
						voList.add(bean);
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			}

			//去除同月份数据
			yksytRefundForCpService.remove(new LambdaQueryWrapper<YksytRefundForCp>()
				.eq(YksytRefundForCp::getThemonth, theMonth)
			);

			boolean sa = yksytRefundForCpService.saveBatch(voList);
			if (sa) {
				//替CP退费spid赋值
				yksytRefundForCpService.giveSpidSoul(theMonth.toString());
				log.info("替CP退费spid赋值 处理完成");
				//替CP退费spid赋值2
				yksytRefundForCpService.giveSpidSoulTwo(theMonth.toString());
				log.info("替CP退费spid赋值2 处理完成");
				//替CP退费设置文件导入标记
				yksytRefundForCpService.settingFileTag(theMonth.toString());
				log.info("替CP退费设置文件导入标记 处理完成");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("审核数据处理异常");
		}
	}


	/**
	 * 出账清单 数据导入
	 * @param path
	 * @param theMonth
	 */
	private void intAccountlistImport(String path,Long theMonth) {
		log.info("出账清单审核导入 --- 导入月份 = {}", theMonth);
		BufferedReader input;
		try {
			String s = new String();
			ArrayList<IntTmpAccountList> list = new ArrayList<>();
			input = new BufferedReader(new FileReader(path));
			while ((s = input.readLine()) != null) { // 判断是否读到了最后一行
				try {
					String info[] = s.replaceAll("\"","").split(",");
					IntTmpAccountList entity = new IntTmpAccountList();
					if(StringUtils.isBlank(info[2])){
						continue;
					}
					entity.setThemonth(Long.valueOf(info[0]));
					entity.setVacproductid(info[1]);
					entity.setUserid(info[2]);
					list.add(entity);
				}catch (Exception e){
					log.info("出账清单审核导入异常数据信息 = {}",s);
					e.printStackTrace();
				}
			}
			input.close();
			//去除同月份数据
			intTmpAccountListService.remove(new LambdaQueryWrapper<IntTmpAccountList>()
				.eq(IntTmpAccountList::getThemonth, theMonth)
			);
			log.info("出账清单 - 去除临时表同月份数据 处理完成");
			boolean sa = intTmpAccountListService.saveBatch(list);
			if(sa){
				//在临时表中删除手机号码无效数据
				intTmpAccountListService.removePhoneIsBad(theMonth.toString());
				log.info("出账清单 - 在临时表中删除手机号码无效数据 处理完成");
				//清空出账清单表该月分区
				intTmpAccountListService.callThisMonth(theMonth.toString());
				log.info("出账清单 - 清空当月分区 处理完成");
				//从临时表插入数据到出账清单表
				intTmpAccountListService.saveToIntAccount(theMonth.toString());
				log.info("出账清单 - 从临时表插入数据到出账清单表 处理完成");
				//设置文件导入标记
				intTmpAccountListService.settingFileTag(theMonth.toString());
				log.info("出账清单 - 设置文件导入标记 处理完成");
				//从临时表删除已经导完的数据
				intTmpAccountListService.removeTemporaryData(theMonth.toString());
				log.info("出账清单 - 从临时表删除已经导完的数据 处理完成");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}




	/**
	 * 社会渠道结算 400 扣罚数据审核导入
	 * @param bytes
	 * @param theMonth
	 */
	private void IntFzzDiscountImport(byte[] bytes, Long theMonth) {
		log.info("400 扣罚数据审核导入 --- 导入月份 = {}", theMonth);
		IntFzzDiscountListener easyExcelListener = new IntFzzDiscountListener();
		List<IntFzzDisconutDTO> excelList = easyExcelListener.list;
		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			EasyExcel.read(inputStream, IntFzzDisconutDTO.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());

			List<IntFzzDiscount> voList = new ArrayList<IntFzzDiscount>();
			if (excelList != null && !excelList.isEmpty()) {
				for (IntFzzDisconutDTO obj : excelList) {
					try {
					IntFzzDiscount bean = new IntFzzDiscount();
					BeanUtils.copyProperties(obj, bean);
					bean.setThemonth(theMonth);
					//受理时间
					if (org.apache.commons.lang3.StringUtils.isNotBlank(obj.getAcceptTime())) {
						bean.setAcceptTime(unifiedate(obj.getAcceptTime()));
					}
					//退费总金额
					if (org.apache.commons.lang3.StringUtils.isNotBlank(obj.getApplyMoney())) {
						String money = obj.getApplyMoney().replaceAll(",", "");
						bean.setApplyMoney(Double.valueOf(money));
					}
					voList.add(bean);
					}catch (Exception e){
						log.info("400 扣罚数据审核导入异常数据信息 = {}",obj.toString());
						e.printStackTrace();
					}
				}
			}

			//去除同月份数据
			intFzzDiscountService.remove(new LambdaQueryWrapper<IntFzzDiscount>()
				.eq(IntFzzDiscount::getThemonth, theMonth)
			);

			boolean sa = intFzzDiscountService.saveBatch(voList);
			if (sa) {
				//给400themonth为空的数据赋值
				intFzzDiscountService.giveTheMonthSoul();
				log.info("给400themonth为空的数据赋值 处理完成");
				//400spcode赋值
				intFzzDiscountService.editSpCode(theMonth.toString());
				log.info("400spcode赋值 处理完成");
				//400spid赋值
				intFzzDiscountService.giveSpidSoul(theMonth.toString());
				log.info("400spid赋值 处理完成");
				//400spid赋值2
				intFzzDiscountService.giveSpidSoulTwo(theMonth.toString());
				log.info("400spid赋值2 处理完成");
				//清除400 空数据
				intFzzDiscountService.removeEmptyData(theMonth.toString());
				log.info("清除400 空数据 处理完成");
				//400设置文件导入标记
				intFzzDiscountService.settingFileTag(theMonth.toString());
				log.info("400设置文件导入标记 处理完成");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("审核数据处理异常");
		}
	}

	private Date sysDate(String time) {
		if(StringUtils.isNotBlank(time)){
			time = time.replaceAll("[^\\d]","");
			SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			int length = time.length();
			if(length == 14){
				SimpleDateFormat simple2 = new SimpleDateFormat("yyyyMMddHHmmss");
				try {
					Date parse = simple2.parse(time);
					String format = simple.format(parse);
					Date date = simple.parse(format);
					return date;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}else if(length == 8){
				SimpleDateFormat simple3 = new SimpleDateFormat("yyyyMMdd");
				try {
					Date parse = simple3.parse(time);
					String format = simple.format(parse);
					Date date = simple.parse(format);
					return date;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}else {
				log.info("时间格式错误 = {}",time);
			}
		}
		log.info("异常数据，时间为空 = {}",time);
		return null;
	}


	private Date unifiedate(String time) {
		String yyyy="";
		String mm="";
		String dd="";
		String hh24="";
		String mi="";
		String ss="";

		String outs="";

		//统一分隔符
		time = time.replaceAll("/","-");
		time = time.replaceAll("年","-");
		time = time.replaceAll("月","-");
		time = time.replaceAll("：",":");

		//多个连续空格合一
		outs="";
		char cf=0;

		//去除汉字等其它不合规字符,只保留数字、空格、冒号
		for(int i=0;i<time.length(); i++)
		{
			char c = time.charAt(i);

			if(i==0) cf=c;
			if( (c>='0' && c<='9') || c=='-' || c==' ' || c==':' ){
				//非连续空格，则拼接
				if(!(i>0 && c==' ' && cf==' ')){
					outs+=c;
					cf=c;
				}
			}
		}

		//分隔日期和时间
		String[] split_date_time = outs.split(" ");

		//没有时间部分
		if(split_date_time.length==1){
			hh24="00";
			mi="00";
			ss="00";
		}else{
			//分隔时间
			String[] split_time = split_date_time[1].split(":");
			if(split_time.length==1) {
				hh24=split_time[0];
				mi="00";
				ss="00";
			}else if(split_time.length==2) {
				hh24=split_time[0];
				mi=split_time[1];
				ss="00";
			}else if(split_time.length>=3) {
				hh24=split_time[0];
				mi=split_time[1];
				ss=split_time[2];
			}

			//补0
			if(hh24.length()==1) hh24="0"+hh24;
			if(mi.length()==1) mi="0"+mi;
			if(ss.length()==1) ss="0"+ss;
		}

		//分隔日期
		String[] split_date = split_date_time[0].split("-");
		if(split_date.length==1) {
			yyyy=split_date[0];
			mm="01";
			dd="01";
		}else if(split_date.length==2) {
			yyyy=split_date[0];
			mm=split_date[1];
			dd="01";
		}else if(split_date.length>=3) {
			yyyy=split_date[0];
			mm=split_date[1];
			dd=split_date[2];
		}

		//年月日补足
		if(yyyy.length()==2) yyyy="20"+yyyy;
		if(mm.length()==1) mm="0"+mm;
		if(dd.length()==1) dd="0"+dd;

		String outformat = "yyyy-mm-dd hh24:mi:ss";
		outformat = outformat.replaceAll("yyyy",yyyy);
		outformat = outformat.replaceAll("mm",mm);
		outformat = outformat.replaceAll("dd",dd);
		outformat = outformat.replaceAll("hh24",hh24);
		outformat = outformat.replaceAll("mi",mi);
		outformat = outformat.replaceAll("ss",ss);
		System.out.println("out format time = " + outformat);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			Date parse = format.parse(outformat);
			System.out.println("parse = " + parse);
			return parse;
		} catch (ParseException e) {
			e.printStackTrace();
			log.info("time format is error  = {}",time);
		}
		return null;
	}



	/**
	 * 社会渠道结算 BalanceDetail(PRM发布) 数据审核导入
	 * @param bytes
	 * @param auditId 文件审核表主键ID
	 */
	private void IntBalanceDetailImport(byte[] bytes,Long auditId){
		log.info("BalanceDetail(PRM发布) 数据审核导入 --- 导入文件ID = {}", auditId);
		IntBalanceDetailListener easyExcelListener = new IntBalanceDetailListener();
		List<IntBalanceDetailDTO> excelList = easyExcelListener.list;
		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			EasyExcel.read(inputStream, IntBalanceDetailDTO.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());
			if(excelList.isEmpty() || excelList.size() < 1){
				log.info("没有可导入的数据");
			}
			AuditUploadFile auditUploadFile = auditUploadFileService.getById(auditId);
			if(auditUploadFile == null){
				log.info("审核数据不存在");
			}
			String excelName = auditUploadFile.getReportName().substring(0,auditUploadFile.getReportName().lastIndexOf("."));
			String theCode = excelName.replaceAll("\\s*", "");
			String substring = theCode.substring(theCode.length() - 11, theCode.length());
			String theMonth = substring.substring(0, 6);
			String spCode = substring.substring(6, substring.length());

			List<IntBalanceDetail> voList = new ArrayList<IntBalanceDetail>();
			for (IntBalanceDetailDTO obj : excelList) {
				try {
					if(StringUtils.isBlank(obj.getProvince()) || StringUtils.isBlank(obj.getSpname())){
						continue;
					}
					IntBalanceDetail bean = new IntBalanceDetail();
					BeanUtils.copyProperties(obj, bean);
					bean.setThemonth(Long.valueOf(theMonth));
					bean.setSpcode(spCode);
					//客服退赔付费(元)
					if (StringUtils.isNotBlank(obj.getMoney1())) {
						bean.setMoney1(new BigDecimal(obj.getMoney1().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//省分违约扣款(元)
					if (StringUtils.isNotBlank(obj.getMoney2())) {
						bean.setMoney2(new BigDecimal(obj.getMoney2().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//调帐金额(元)
					if (StringUtils.isNotBlank(obj.getMoney3())) {
						bean.setMoney3(new BigDecimal(obj.getMoney3().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//不规范定制处罚费（元）
					if (StringUtils.isNotBlank(obj.getMoney4())) {
						bean.setMoney4(new BigDecimal(obj.getMoney4().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}

					//应收信息费(元)
					if (StringUtils.isNotBlank(obj.getFee1())) {
						bean.setFee1(new BigDecimal(obj.getFee1().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//省分实收信息费(元)
					if (StringUtils.isNotBlank(obj.getFee2())) {
						bean.setFee2(new BigDecimal(obj.getFee2().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//实际结算金额(元)
					if (StringUtils.isNotBlank(obj.getFee3())) {
						bean.setFee3(new BigDecimal(obj.getFee3().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					voList.add(bean);
				} catch (Exception e) {
					log.info("BalanceDetail(PRM发布) 数据 审核导入异常数据信息 = {}",obj.toString());
					e.printStackTrace();
				}
			}

			//去除同月份数据
			intBalanceDetailService.remove(new LambdaQueryWrapper<IntBalanceDetail>()
				.eq(IntBalanceDetail::getSpcode,spCode)
				.eq(IntBalanceDetail::getThemonth,theMonth)
			);

			boolean sa = intBalanceDetailService.saveBatch(voList);
			if(sa){
				//spid赋值
				intBalanceDetailService.giveSpidSoul(theMonth);
				log.info("spid赋值 处理完成");
				//删除7个金额均为0的数据
				intBalanceDetailService.deleteZeroMoney(theMonth);
				log.info("删除7个金额均为0的数据 处理完成");
				//spid赋值2
				intBalanceDetailService.giveSpidSoulTwo(theMonth);
				log.info("spid赋值2 处理完成");
				//删除spid为空的数据
				intBalanceDetailService.deleteNoSpid(theMonth);
				log.info("删除spid为空的数据 处理完成");
				//设置文件导入标记
				intBalanceDetailService.settingFileTag(theMonth);
				log.info("设置文件导入标记 处理完成");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("审核数据处理异常");
		}
	}


	/**
	 * 省分违约明细 数据审核导入
	 * @param bytes
	 * @param auditId
	 */
	private void IntProvinceViolationImport(byte[] bytes,Long auditId){
		log.info("省分违约明细 数据审核导入 --- 导入文件ID = {}", auditId);
		IntProvinceViolationListener easyExcelListener = new IntProvinceViolationListener();
		List<IntProvinceViolationDTO> excelList = easyExcelListener.list;
		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			EasyExcel.read(inputStream, IntProvinceViolationDTO.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());
			AuditUploadFile auditUploadFile = auditUploadFileService.getById(auditId);
			if(auditUploadFile == null){
				log.info("审核数据不存在");
			}
			String excelName = auditUploadFile.getReportName().substring(0,auditUploadFile.getReportName().lastIndexOf("."));
			Pattern pat = Pattern.compile(REGEX_CHINESE);
			Matcher mat = pat.matcher(excelName);
			String str = mat.replaceAll("");
			String strMonth = "";
			if(str.length() > 6){
				strMonth = str.substring(0,6);
			}else {
				strMonth = str;
			}
			String theMonth = strMonth;
			if(excelList.isEmpty() || excelList.size() < 1){
				intProvinceViolationService.settingFileTag(theMonth);
				log.info("没有可导入的数据 设置文件导入标记 处理完成");
			}else {
				List<IntProvinceViolation> voList = new ArrayList<IntProvinceViolation>();
				for (IntProvinceViolationDTO obj : excelList) {

					try {
						if(StringUtils.isBlank(obj.getUserid())){
							continue;
						}
						IntProvinceViolation bean = new IntProvinceViolation();
						BeanUtils.copyProperties(obj, bean);
						bean.setThemonth(Long.valueOf(theMonth));
						//投诉发生月份
						if (StringUtils.isNotBlank(obj.getTsMonth())) {
							String expression = expression(obj.getTsMonth());
							if(expression.equals(obj.getTsMonth())){
								String month = obj.getTsMonth().replace("月", "");
								bean.setTsMonth(Long.valueOf(month));
							}else {
								bean.setTsMonth(Long.valueOf(expression));
							}
						}
						//平均扣款金额（元）
						if (StringUtils.isNotBlank(obj.getAvgDiscount())) {
							bean.setAvgDiscount(new BigDecimal(obj.getAvgDiscount().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
						}
						voList.add(bean);
					}catch (Exception e){
						log.info("省分违约明细数据 审核导入异常数据信息 = {}",obj.toString());
						e.printStackTrace();
					}
				}
				//去除同月份数据
				intProvinceViolationService.remove(new LambdaQueryWrapper<IntProvinceViolation>()
					.eq(IntProvinceViolation::getThemonth,theMonth)
				);

				boolean sa = intProvinceViolationService.saveBatch(voList);
				if(sa){
					//spid赋值
					intProvinceViolationService.giveSpidSoul(theMonth);
					log.info("s省分违约明细数据  pid赋值 处理完成");
					//spid赋值2
					intProvinceViolationService.giveSpidSoulTwo(theMonth);
					log.info("省分违约明细数据  spid赋值2 处理完成");
					//删除重复数据
					//intProvinceViolationService.deleteRepeatData(theMonth);
					//log.info("省分违约明细数据  删除重复数据 处理完成");
					//设置文件导入标记
					intProvinceViolationService.settingFileTag(theMonth);
					log.info("省分违约明细数据  设置文件导入标记 处理完成");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("审核数据处理异常");
		}
	}


	/**
	 * 不规范定制处罚明细 数据审核导入
	 * @param bytes
	 * @param auditId
	 */
	private void IntProvinceIrregularImport(byte[] bytes,Long auditId){
		log.info("不规范定制处罚明细 数据审核导入 --- 导入文件ID = {}", auditId);
		IntProvinceIrregularListener easyExcelListener = new IntProvinceIrregularListener();
		List<IntProvinceIrregularDTO> excelList = easyExcelListener.list;
		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			EasyExcel.read(inputStream, IntProvinceIrregularDTO.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());
			if(excelList.isEmpty() || excelList.size() < 1){
				log.info("没有可导入的数据");
			}
			AuditUploadFile auditUploadFile = auditUploadFileService.getById(auditId);
			if(auditUploadFile == null){
				log.info("审核数据不存在");
			}
			String excelName = auditUploadFile.getReportName().substring(0,auditUploadFile.getReportName().lastIndexOf("."));
			Pattern pat = Pattern.compile(REGEX_CHINESE);
			Matcher mat = pat.matcher(excelName);
			String str = mat.replaceAll("");
			String strMonth = "";

			if(str.length() > 6){
				strMonth = str.substring(0,6);
			}else {
				strMonth = str;
			}
			String theMonth = strMonth;

			List<IntProvinceIrregular> voList = new ArrayList<IntProvinceIrregular>();
			for (IntProvinceIrregularDTO obj : excelList) {
				try {
					if(StringUtils.isBlank(obj.getUserid())){
						continue;
					}
					if(StringUtils.isNotBlank(obj.getUserid())){
						String regex = "^(1[3-9]\\d{9}$)";
						if (obj.getUserid().length() == 11) {
							Pattern p = Pattern.compile(regex);
							Matcher m = p.matcher(obj.getUserid());
							if (!m.matches()) {
								continue;
							}
						}else {
							continue;
						}
					}
					IntProvinceIrregular bean = new IntProvinceIrregular();
					BeanUtils.copyProperties(obj, bean);
					bean.setThemonth(Long.valueOf(theMonth));
					//投诉发生月份
					if (StringUtils.isNotBlank(obj.getAccMonth())) {
						String expression = expression(obj.getAccMonth());
						if(expression.equals(obj.getAccMonth())){
							String monthStr = obj.getAccMonth().replace("年", "").replace("月","");
							if(monthStr.length() == 5){
								String year = monthStr.substring(0, 4);
								String month = "0"+monthStr.substring(4);
								monthStr = year+month;
							}
							bean.setAccMonth(Long.valueOf(monthStr));
						}else {
							bean.setAccMonth(Long.valueOf(expression));
						}
					}
					voList.add(bean);
				}catch (Exception e){
					log.info("不规范定制处罚明细  审核导入异常数据信息 = {}",obj.toString());
					e.printStackTrace();
				}
			}

			//去除同月份数据
			intProvinceIrregularService.remove(new LambdaQueryWrapper<IntProvinceIrregular>()
				.eq(IntProvinceIrregular::getThemonth,theMonth)
			);

			boolean sa = intProvinceIrregularService.saveBatch(voList);
			if(sa){
				//spid赋值
				intProvinceIrregularService.giveSpidSoul(theMonth);
				log.info("不规范定制处罚明细  spid赋值 处理完成");
				//spid赋值2
				intProvinceIrregularService.giveSpidSoulTwo(theMonth);
				log.info("不规范定制处罚明细  spid赋值2 处理完成");
				//删除重复数据
				//intProvinceIrregularService.deleteRepeatData(theMonth);
				//log.info("不规范定制处罚明细  删除重复数据 处理完成");
				//设置文件导入标记
				intProvinceIrregularService.settingFileTag(theMonth);
				log.info("不规范定制处罚明细  设置文件导入标记 处理完成");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("审核数据处理异常");
		}
	}


	private String expression(String date) {
		String result = "";
		//2022/1/29
		String pattern = "^(\\d{4})[\\/](\\d{1}|1[0-2])[\\/]((\\d{1}|0\\d{1}|[1-2][0-9]|3[0-1]))*$";
		if(Pattern.matches(pattern, date)){
			String[] split = date.split("/");
			if(split.length >= 2){
				result = split[0] + "0" +split[1];
			}
			return result;
		}
		//2022-01
		String pattern2 = "^(\\d{4})-(0\\d{1}|1[0-2])*$";
		if(Pattern.matches(pattern2, date)){
			String[] split = date.split("-");
			if(split.length >= 2){
				result = split[0]+split[1];
			}
			return result;
		}
		return date;
	}

}

