package org.springblade.audit.controller;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.audit.dto.FctCsComplaintDetailDTO;
import org.springblade.audit.entity.AuditComplaintDetail;
import org.springblade.audit.entity.MidCsComplaintDetail;
import org.springblade.audit.listener.FctCsComplaintDetailListener;
import org.springblade.audit.service.IAuditComplaintDetailService;
import org.springblade.audit.service.IFctCsComplaintDetailService;
import org.springblade.audit.service.IMidCsComplaintDetailService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 投诉回传数据表 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-12-08
 */
@RestController
@RequestMapping("/audit/complaint")
@Api(value = "投诉数据回传管理", tags = "投诉数据回传接口")
@Slf4j
public class FctCsComplaintDetailController {

	@Autowired
	private IFctCsComplaintDetailService fctCsComplaintDetailService;

	@Autowired
	private IMidCsComplaintDetailService midCsComplaintDetailService;

	@Autowired
	private IAuditComplaintDetailService auditComplaintDetailService;

	@Autowired
	private UserClient userClient;

	private static final Pattern MONEY_PATTERN = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");


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


	@PostMapping("/entrance")
	@ApiOperation(value = "报表导入", notes = "报表导入")
	public R entrance(@RequestParam(required = true, name = "file") MultipartFile file,
					  @RequestParam(required = true, name = "excelCode") String excelCode
	) {
		if (file == null) {
			return R.fail("导入文件不能为空");
		}
		if (StringUtils.isBlank(excelCode)) {
			return R.fail("excelCode不能为空");
		}
		//400
		if ("400".equals(excelCode)) {
			return FctCsComplaintDetailImport(file, excelCode);
		}
		//省分
		if ("省分".equals(excelCode)) {
			//return FctCsIrregularMoneyImport(file, beginTime,reportUrl,excelCode,batchNum);
		}
		return R.fail("excelCode 参数异常");
	}


	/**
	 * 400 报表导入
	 * @param file
	 * @return
	 */
	private R FctCsComplaintDetailImport(MultipartFile file, String excelCode) {
		Long userId = SecureUtil.getUserId();
		String oFileName = file.getOriginalFilename();
		String fileSuffix = oFileName.substring(oFileName.lastIndexOf("."));
		if (
			!".xls".equalsIgnoreCase(fileSuffix) &&
				!".xlsx".equalsIgnoreCase(fileSuffix)
		) {
			return R.fail("只能上传xlsx/xls类型的文件");
		}
		String tempFileName = UUID.randomUUID().toString() + fileSuffix;
		File f = new File(picDir + tempFileName);
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String path = "uploads/" + tempFileName;


		FctCsComplaintDetailListener easyExcelListener = new FctCsComplaintDetailListener();
		List<FctCsComplaintDetailDTO> excelList = easyExcelListener.list;
		UserModel user = userClient.getById(userId);
		try {
			InputStream inputStream = file.getInputStream();
			EasyExcel.read(inputStream, FctCsComplaintDetailDTO.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());

			List<MidCsComplaintDetail> voList = new ArrayList<MidCsComplaintDetail>();
			SimpleDateFormat simple = new SimpleDateFormat("yyyyMM");
			SimpleDateFormat simple2 = new SimpleDateFormat("yyyyMMdd");
			if (excelList != null && !excelList.isEmpty()) {
				for (FctCsComplaintDetailDTO obj : excelList) {
					try {
						MidCsComplaintDetail bean = new MidCsComplaintDetail();
						BeanUtils.copyProperties(obj, bean);
						bean.setDataSource(excelCode);
						bean.setImportTime(new Date());
						bean.setImportDay(Long.valueOf(simple2.format(bean.getImportTime())));

						//受理时间
						if (StringUtils.isNotBlank(obj.getAcceptTime())) {
							bean.setAcceptTime(sysDate(obj.getAcceptTime()));
							bean.setThemonth(Long.valueOf(simple.format(sysDate(obj.getAcceptTime()))));
							bean.setAcceptDay(Long.valueOf(simple2.format(sysDate(obj.getAcceptTime()))));
						}

						//受理号码处理
						if (StringUtils.isNotBlank(obj.getAcceptPhonenum())) {
							String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， ·、？]";
							String regEx_cha = "[\u4e00-\u9fa5]";
							String replace = "";
							String trim = obj.getAcceptPhonenum().replaceAll(regEx, replace).trim();
							String trim_cha = trim.replaceAll(regEx_cha, replace).trim();
							if (trim_cha.length() <= 11) {
								bean.setAcceptPhonenum(trim_cha);
							} else {
								bean.setAcceptPhonenum(trim_cha.substring(0, 11));
							}
						}

						//工单类型处理
						if (StringUtils.isNotBlank(obj.getComplaintType())) {
							if (obj.getComplaintType().startsWith("办理")) {
								bean.setComplaintType("办理");
							} else if (obj.getComplaintType().startsWith("咨询")) {
								bean.setComplaintType("咨询");
							} else if (obj.getComplaintType().startsWith("投诉")) {
								bean.setComplaintType("投诉");
							} else {
								bean.setComplaintType(obj.getComplaintType().length() >= 10 ? obj.getComplaintType().substring(0, 10) : obj.getComplaintType());
							}
						}

						//退费金额处理
						if (StringUtils.isNotBlank(obj.getRefundMoney())) {
							String regEx_cha = "[\u4e00-\u9fa5]";
							String replace = "";
							String trim_cha = obj.getRefundMoney().replaceAll(regEx_cha, replace).trim();
							String money = trim_cha.replaceAll(",", replace);
							bean.setRefundMoney(Double.valueOf(money));
						}

						//完结时间处理
						if (StringUtils.isNotBlank(obj.getOverTime())) {
							bean.setOverTime(sysDate(obj.getOverTime()));
						}
						voList.add(bean);
					} catch (Exception e) {
						e.printStackTrace();
						log.info("obj = {}",obj);
					}
				}
			}
			//清空临时表
			midCsComplaintDetailService.remove(new QueryWrapper<>());
			List<MidCsComplaintDetail> finalVoList = voList;
			new Thread(new Runnable() {
				@Override
				public void run() {
					boolean fct = midCsComplaintDetailService.saveBatch(finalVoList);
					log.info("临时表导入数据结果 === {}",fct);
					if(fct){
						AuditComplaintDetail entity = new AuditComplaintDetail();
						entity.setCategoryCode(excelCode);
						entity.setReportName(file.getOriginalFilename());
						entity.setCreateUser(user.getName());
						entity.setReportUrl(path);
						entity.setCreateTime(new Date());
						boolean save = auditComplaintDetailService.save(entity);
						log.info("导入记录保存完成 === {}",save);
						//更新spid字段 1
						midCsComplaintDetailService.updateSpidf();
						log.info("更新spid字段1完成");
						//更新spid字段 (原1现2)
						midCsComplaintDetailService.updateSpid();
						log.info("更新spid字段2完成");
						//去除正式表中和临时表中重复的工单号
						fctCsComplaintDetailService.deleteWorkSheet();
						log.info("去除正式表中和临时表中重复的工单号完成");
						//将临时表数据复制到正式表
						fctCsComplaintDetailService.fctCopyMid();
						log.info("将临时表数据复制到正式表完成");
					}
				}
			}).start();
			return R.success("导入成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("导入失败");
		}
	}


	private Date sysDate(String time) {
		String format = "yyyy-MM-dd";
		String format1 = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat simple = null;
		if(time.replaceAll("\\s*", "").length() == format.replaceAll("\\s*", "").length()){
			simple = new SimpleDateFormat(format);
		}else if(time.replaceAll("\\s*", "").length() == format1.replaceAll("\\s*", "").length()){
			simple = new SimpleDateFormat(format1);
		}
		try {
			Date parse = simple.parse(time);
			return parse;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}

