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

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.UUID;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.excel.converters.szhtxx.CustomStringBigDecimalConverter;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
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.excel.TaxationSzhtxxE6ExcelRow;
import cn.superdesk.uniorder.dubbo.consumer._common.ProviderEnvConstantDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.InvoiceApplyCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.invoiced.InvoiceInvoicedDubboConsumerService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.Objects;


/**
 * @Description: 第三方-szhtxx-深圳航天信息有限公司-e6软件
 * @Author: linjinyu
 * @CreateDate: 2021/3/17 上午9:45
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/3/17 上午9:45
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "第三方-szhtxx-深圳航天信息有限公司-e6软件", tags = {"第三方-szhtxx-深圳航天信息有限公司-e6软件"})
@Slf4j
@RestController
@RequestMapping("/thirdpart/szhtxx/invoice/")
public class ThirdPartTaxationSzhtxxE6Controller extends BaseController {

	@Autowired
	private InvoiceApplyCustomerDubboConsumerService invoiceApplyDubboConsumerService;

	@Autowired
	private InvoiceInvoicedDubboConsumerService invoiceInvoicedDubboConsumerService;

	@Resource
	private ProviderEnvConstantDubboCustomerService providerEnvConstantDubboCustomerService;
	@Resource
	private Snowflake                               snowflake;

	/**
	 * mark excelImport
	 * http://192.168.6.223:8089/web/thirdpart/szhtxx/invoice/import/excel/e6
	 *
	 * @param multipartFile
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "E6软件发票导出的Excel-导入不存储(测试用)- * 税务管理软件E6\n" +
			" * 深圳航天信息研制\n" +
			" * 版本号 3.0.21.112\n" +
			" * 版本类型 Excel&Txt组件接口版")
	@RequestMapping(value = "import/excel/e6", method = RequestMethod.POST)
	@ResponseBody
	public R<String> excelImport(@RequestParam("excelFile") MultipartFile multipartFile) throws Exception {

		// 有个很重要的点 InvoiceInvoicedImportDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去

		// 写法1:
//		String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
//		// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
//		EasyExcel.read(fileName, InvoiceInvoicedParam.class, new InvoiceInvoicedImportDataListener()).sheet().doRead();

		// 写法2:
//		String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";

		// TODO 这个要整改
		String fileName = multipartFile.getOriginalFilename();

		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "上传文件格式不正确");
		}
		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}


		ExcelReader excelReader = null;

		try {
			excelReader = EasyExcel.read(
					multipartFile.getInputStream(),
					TaxationSzhtxxE6ExcelRow.class,
					new ThirdPartTaxationSzhtxxE6ExcelRowImportDataListener(invoiceInvoicedDubboConsumerService, snowflake, getToken())
			).build();
			ReadSheet readSheet = EasyExcel.readSheet(0).build();
			excelReader.read(readSheet);

		} finally {

			if (excelReader != null) {
				// 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
				excelReader.finish();
			}
		}

		return ResponseResultOuterUtils.createSuccesResult();
	}

	/**
	 * http://192.168.6.223:8089/web/thirdpart/szhtxx/invoice/import/excel/and/store/e6
	 *
	 * @param multipartFile
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "E6软件发票导出的Excel-存储并导入- * 税务管理软件E6\n" +
			" * 深圳航天信息研制\n" +
			" * 版本号 3.0.21.112\n" +
			" * 版本类型 Excel&Txt组件接口版")
	@RequestMapping(value = "import/excel/and/store/e6", method = RequestMethod.POST)
	@ResponseBody
	public R<String> excelImportAndStore(@RequestParam("excelFile") MultipartFile multipartFile) throws Exception {

		// 有个很重要的点 InvoiceInvoicedImportDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去

		// 写法1:
//		String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
//		// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
//		EasyExcel.read(fileName, InvoiceInvoicedParam.class, new InvoiceInvoicedImportDataListener()).sheet().doRead();

		// 写法2:
//		String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";

		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 + "szhtxx" + 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)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "上传文件格式不正确");
		}
		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}


		ExcelReader excelReader = null;

		try {
			excelReader = EasyExcel.read(
					multipartFile.getInputStream(),
					TaxationSzhtxxE6ExcelRow.class,
					new ThirdPartTaxationSzhtxxE6ExcelRowImportDataListener(invoiceInvoicedDubboConsumerService, snowflake, getToken()))
					.registerConverter(new CustomStringBigDecimalConverter())
					.build();
			ReadSheet readSheet = EasyExcel.readSheet(0).build();
			excelReader.read(readSheet);

		} finally {

			if (excelReader != null) {
				// 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
				excelReader.finish();
			}
		}

		return ResponseResultOuterUtils.createSuccesResult();
	}


	/**
	 * http://192.168.6.223:8089/web/thirdpart/szhtxx/invoice/export/excel/invoice/register/e6/{id}
	 *
	 * @param invoiceApplyId
	 * @return
	 */
	@ApiOperation(value = "E6软件发票登记导出接口-导出的excel供E6开票导入- * 税务管理软件E6\n" +
			" * 深圳航天信息研制\n" +
			" * 版本号 3.0.21.112\n" +
			" * 版本类型 Excel&Txt组件接口版")
	@RequestMapping(value = "export/excel/invoice/register/e6/{id}", method = RequestMethod.POST)
	@ResponseBody
	public R<String> exportExcelInvoiceRegister4e6(@PathVariable("id") Long invoiceApplyId) {

		return new R<String>(invoiceApplyDubboConsumerService.exportExcelDimUnifiedInvoiceRegister4E6(invoiceApplyId, getToken()));

	}
}
