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

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.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.TaxationYqzs17WinV30ExcelRow;
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;

@Api(value = "第三方-yqzs17winV30-亿企助手3.0-软件", tags = {"第三方-yqzs17winV30-亿企助手3.0-软件"})
@Slf4j
@RestController
@RequestMapping("/thirdpart/yqzs17win/invoice/")
public class ThirdPartTaxationYqzs17WinController 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/yqzs17win/invoice/import/excel/and/store/yqzs17winV30
	 *
	 * @param multipartFile
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "亿企助手3.0 软件发票导出的Excel-存储并导入-税务管理软件 亿企助手3.0")
	@RequestMapping(value = "import/excel/and/store/yqzs17winV30", method = RequestMethod.POST)
	@ResponseBody
	public R<String> excelImportAndStore(@RequestParam("excelFile") MultipartFile multipartFile) throws Exception {

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

		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 + "yqzs17win" + File.separator + "import" + File.separator + "yqzs17winV30" + 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(),
					TaxationYqzs17WinV30ExcelRow.class,
					new ThirdPartTaxationYqzs17WinV30ExcelRowImportDataListener(invoiceInvoicedDubboConsumerService, snowflake, getToken()))
//					.registerConverter(new CustomStringBigDecimalConverter())
					.build();
			ReadSheet readSheet = EasyExcel.readSheet(0).headRowNumber(2).build();
			excelReader.read(readSheet);

		} finally {

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

		return ResponseResultOuterUtils.createSuccesResult("", targetFullPath + fileName);
	}
}
