package cn.superdesk.uniorder.controller._thirdpart.aisino;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.lang.UUID;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.invoice.txt.TaxationAisinoTxtRow;
import cn.superdesk.uniorder.dubbo.consumer._common.ProviderEnvConstantDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseExtInvoiceDubboConsumerService;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2021/5/6 上午11:45
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/5/6 上午11:45
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "第三方-aisino-航天信息股份有限公司-增值税发票税控开票软件(金税盘版)", tags = {"第三方-aisino-航天信息股份有限公司-增值税发票税控开票软件(金税盘版)"})
@Slf4j
@RestController
@RequestMapping("/thirdpart/aisino/invoice/")
public class ThirdPartTaxationAisinoController extends BaseController {

	@Resource
	private ProviderEnvConstantDubboCustomerService providerEnvConstantDubboCustomerService;

	@Autowired
	private SysEnterpriseExtInvoiceDubboConsumerService sysEnterpriseExtInvoiceDubboConsumerService;

	/**
	 * 此不是excel
	 * http://192.168.6.223:8089/web/thirdpart/aisino/invoice/import/txt/and/store
	 *
	 * @param multipartFile
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "增值税发票税控开票软件(金税盘版)导出的Doc-存储并导入- * 增值税发票税控开票软件(金税盘版)\n" +
			" * 研发单位:   航天信息股份有限公司\n" +
			" * 内部版本号: V2.3.11.210102\n" +
			" * 税收分类编码表版本号: 39.0" +
			" * 智税集成:   V2.3.11.201230")
	@RequestMapping(value = "import/txt/and/store", method = RequestMethod.POST)
	@ResponseBody
	public R<String> importTxtAndStore(@RequestParam("excelFile") MultipartFile multipartFile) throws Exception {


		ResourceConstant excelExportConstant = providerEnvConstantDubboCustomerService.getResourceConstant();

		String excelExportPathRoot             = excelExportConstant.getPathRoot();
		String excelExportRelativePathTemplate = excelExportConstant.getPathTemplate();
		String excelExportRelativePathStorage  = excelExportConstant.getPathStorage();

		String relativePath = File.separator + "upload" + File.separator + "thirdpart" + File.separator + "aisino" + File.separator + "import" + File.separator + "e6" + File.separator;

		String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

		String targetFullPath = excelExportPathRoot + relativePath + currentDate + File.separator;

		if (!FileUtil.exist(targetFullPath)) {
			FileUtil.mkdir(targetFullPath);
		}

		String fileName = UUID.randomUUID().toString() + "@" + multipartFile.getOriginalFilename();
		String suffix   = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
		File   file1    = FileUtil.writeBytes(multipartFile.getBytes(), targetFullPath + fileName);

		if (!fileName.matches("^.+\\.(?i)(md)$")
				&& !fileName.matches("^.+\\.(?i)(txt)$")
				&& !fileName.matches("^.+\\.(?i)(cvs)$")
		) {
			throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "上传文件格式不正确");
		}

		FileReader fileReader = new FileReader(file1);

		List<String> lines = fileReader.readLines();

		List<TaxationAisinoTxtRow> processList = new ArrayList<>();

//		{客户编码}[分隔符]"~~"
//		// 每行格式 :
//		// 编码~~名称~~简码~~税号~~地址电话~~银行账号~~邮件地址~~备注~~身份证校验
		lines.forEach(AnLamdaUtils.consumerWithIndex((line, index) -> {


			log.info("{} -> {}", index, line);

			if (index > 2) {
				String[] lineSpile = line.split("~~");

				TaxationAisinoTxtRow param = new TaxationAisinoTxtRow();
				param.setAisinoInvoiceSn(lineSpile[0]);
				param.setPurchaserCompanyName(lineSpile[1]);
				param.setShortCode(lineSpile[2]);
				param.setPurchaserTaxpayersIDCode(lineSpile[3]);

				param.setPurchaserAddressPhone(lineSpile[4]);

				if (StringUtils.isNotBlank(lineSpile[4])) {

					String[] line4Spile = lineSpile[4].split(" ");

					if (line4Spile.length == 2) {
						param.setPurchaserAddress(line4Spile[0]);
						param.setPurchaserPhone(line4Spile[1]);
					}


				}


				param.setPurchaserBankAccountNumber(lineSpile[5]);
				if (StringUtils.isNotBlank(lineSpile[5])) {

					String[] line5Spile = lineSpile[5].split(" ");

					if (line5Spile.length == 2) {
						param.setInvoiceBank(line5Spile[0]);
						param.setInvoiceAccount(line5Spile[1]);
					}
				}


				param.setEmail(lineSpile[6]);
				param.setRemark(lineSpile[7]);
				param.setVerificationOfIdCard(lineSpile[8]);

				processList.add(param);
			}


		}));
		log.info("{}", AnJsonUtils.toPrettyJson(processList));

		sysEnterpriseExtInvoiceDubboConsumerService.saveOrUpdate4TaxationAisinoTxtRowParamListByPurchaserTaxpayersIDCode(processList, getToken());


//		boolean isExcel2003 = true;
//		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
//			isExcel2003 = false;
//		}


//		ExcelReader excelReader = null;
//
//		try {
//			excelReader = EasyExcel.read(multipartFile.getInputStream(), TaxationAisinoE6ExcelRowParam.class, new ThirdPartTaxationSzhtxxE6ExcelRowImportDataListener(invoiceInvoicedDubboConsumerService, getToken()))
//					.registerConverter(new CustomStringBigDecimalConverter())
//					.build();
//			ReadSheet readSheet = EasyExcel.readSheet(0).build();
//			excelReader.read(readSheet);
//
//		} finally {
//
//			if (excelReader != null) {
//				// 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
//				excelReader.finish();
//			}
//		}

		return ResponseResultOuterUtils.createSuccesResult();
	}
}
