package cn.superdesk.uniorder.controller.invoice.customer.bak;

import cn.superdesk.uniorder.common.enums.ExceptionMsg;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.rest.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto.param.invoice.ExportExcelInvoiceApplyQueryCriteria;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyPage;
import cn.superdesk.uniorder.dubbo.consumer.invoice.InvoiceApplyDubboConsumerService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 7/29/20 7:31 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 7/29/20 7:31 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "[开票发票] - 积分结算 - 发票管理", tags = {"[开票发票] - 积分结算 - 发票管理"})
@Slf4j
@RestController
@RequestMapping("/invoice/manager/customer/score")
public class InvoiceManagerCustomerScoreController extends BaseController {

	@Autowired
	private InvoiceApplyDubboConsumerService invoiceApplyDubboConsumerService;

	/**
	 * 积分结算 - 发票管理 - 列表
	 * <p>
	 * /invoice/manager/customer/score/findInvoiceListByPage
	 *
	 * @return
	 */
	@RequestMapping(value = "/findInvoiceListByPage", method = RequestMethod.POST)
	public R<List<InvoiceApplyPage>> findInvoiceByPage(@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria) {

		R<List<InvoiceApplyPage>> result = new R<>();

//		Map<String, Object> params = new HashMap<>();
//
//		params.put("invNumber", getString("invNumber"));
//		params.put("timeField", getString("timeField"));//时间查询字段
//
//		params.put("startTime", getString("startTime"));//开始时间
//		params.put("endTime", getString("endTime"));//结束时间
//
//		params.put("invoiceStatus", getBtye("invoiceStatus"));//发票状态 0未邮寄 1已邮寄 2已作废
//		params.put("backAccountStatus", getBtye("backAccountStatus"));//回款状态 0未回款 1部分回款 2全部回款
//		params.put("keywordsField", getString("keywordsField"));//关键字查询字段
//		params.put("keywords", getString("keywords"));//关键字查询字段
//		params.put("invoiceTitle", getString("invoiceTitle"));//开票抬头
//		params.put("companyName", getString("companyName"));//企业名称
//		params.put("makeInvoiceStatus", new String[]{"1", "2"});//开票状态
//		//addressRealname
//		params.put("addressRealname", getString("addressRealname"));//收件人
//		params.put("merchName", getString("merchName"));//商户名称
//		params.put("purchaser", getString("purchaser"));//采购人/买家信息
//
//		params.put("backtimestar", getString("backtimestar"));
//		params.put("backtimeend", getString("backtimeend"));

		criteria.setMakeInvoiceStatus(Arrays.asList(1, 2));

		result = invoiceApplyDubboConsumerService.findViewByPageFocusScore(getToken(), criteria, criteria.getPageNumber(), criteria.getPageSize());
		return result;
	}

	/**
	 * 积分结算 - 发票管理 - 头
	 * <p>
	 * /invoice/manager/customer/score/findInvoiceHeadData
	 *
	 * @return
	 */
	@RequestMapping(value = "/findInvoiceHeadData", method = RequestMethod.POST)
	public R findInvoiceHeadData(@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria) {

//		Map<String, Object> params = new HashMap<>();
//
//		params.put("invNumber", getString("invNumber"));
//		params.put("timeField", getString("timeField"));//时间查询字段
//		params.put("startTime", getString("startTime"));//开始时间
//		params.put("endTime", getString("endTime"));//结束时间
//		params.put("invoiceStatus", getBtye("invoiceStatus"));//发票状态 0未邮寄 1已邮寄 2已作废
//		params.put("backAccountStatus", getBtye("backAccountStatus"));//回款状态 0未回款 1部分回款 2全部回款
//		params.put("keywordsField", getString("keywordsField"));//关键字查询字段
//		params.put("keywords", getString("keywords"));//关键字查询字段
//		params.put("invoiceTitle", getBtye("invoiceTitle"));//开票抬头
//		params.put("companyName", getBtye("companyName"));//企业名称
//		params.put("makeInvoiceStatus", new String[]{"1", "2"});//开票状态
//		params.put("backtimestar", getString("backtimestar"));
//		params.put("backtimeend", getString("backtimeend"));

		criteria.setMakeInvoiceStatus(Arrays.asList(1, 2));

		return new R(invoiceApplyDubboConsumerService.findViewHeadDataFocusScore(getToken(), criteria));
	}

	/**
	 * opt 寄票登记
	 * /invoice/manager/customer/score/sendInvoiceRegister
	 *
	 * @return
	 */
	@RequestMapping(value = "/sendInvoiceRegister", method = RequestMethod.POST)
	public R sendInvoiceRegister() {

		String sendInvoiceRegisterListJson = request.getParameter("mailTickRegisterList");

//		mailTickRegisterList: [{"id":6412,"expressCompanyId":-1,"expressNo":"dd"}]

		log.info("sendInvoiceRegister params :\n{}", sendInvoiceRegisterListJson);

		List<Map> sendInvoiceRegisterList = com.alibaba.fastjson.JSON.parseArray(sendInvoiceRegisterListJson, Map.class);

		invoiceApplyDubboConsumerService.sendInvoiceRegister(getToken(), sendInvoiceRegisterList);

		return new R();
	}

	/**
	 * opt 重新开票 (过 20200730 1711)
	 * /invoice/manager/customer/score/invoiceAgain
	 *
	 * @return
	 */
	@RequestMapping(value = "/invoiceAgain", method = RequestMethod.POST)
	public R invoiceAgain() {

		Map<String, Object> params = new HashMap<>();
		// 发票申请Id
		params.put("id", getString("id"));

		log.info("sendInvoiceRegister params :\n{}", params);

		invoiceApplyDubboConsumerService.opAgain(getToken(), params);
		return new R();
	}


	/**
	 * 积分结算 - 发票管理 - 导入发票信息(批量操作)
	 * /invoice/manager/customer/score/importInvoiceExcel
	 *
	 * @param excelFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/importInvoiceExcel", method = RequestMethod.POST)
	public R<String> importInvoiceExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {

		R<String> response = new R<>();

		String fileName = excelFile.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;
		}
		InputStream is = excelFile.getInputStream();
		Workbook    wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is);
		} else {
			wb = new XSSFWorkbook(is);
		}
		Sheet sheet = wb.getSheetAt(0);
		if (sheet == null) {
			throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "Excel文件无内容");
		}
		int rowCounts = sheet.getLastRowNum();

		List<Map<String, Object>> list = new ArrayList<>();
		// 通过mobile分类
		for (int i = 1; i <= rowCounts; i++) {
			Map<String, Object> excelMap = new HashMap<>();

			sheet.getRow(i).getCell(0).setCellType(CellType.STRING);
			String invoiceNo = sheet.getRow(i).getCell(0).getStringCellValue();

			sheet.getRow(i).getCell(1).setCellType(CellType.STRING);
			String invoiceNumber = sheet.getRow(i).getCell(1).getStringCellValue();

			excelMap.put("invoiceNo", invoiceNo);
			excelMap.put("invoiceNumber", invoiceNumber);

			list.add(excelMap);
		}
		String errorMsg = invoiceApplyDubboConsumerService.importInvoiceExcel(getToken(), list);

		if (StringUtils.isBlank(errorMsg)) {
			response.setCode(200);
			response.setSuccess(true);
			response.setMessage("操作成功");
		} else {
			response.setCode(500);
			response.setSuccess(false);
			response.setData(errorMsg);
			response.setMessage(errorMsg);
		}

		return response;
	}

	/**
	 * 积分结算 - 发票管理 - 导入寄票信息(批量操作)
	 * /invoice/manager/customer/score/importSendInvoiceExcel
	 *
	 * @param excelFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/importSendInvoiceExcel", method = RequestMethod.POST)
	public R<String> importSendInvoiceExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {

		R<String> response = new R<>();

		String fileName = excelFile.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;
		}

		InputStream is = excelFile.getInputStream();

		Workbook wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is);
		} else {
			wb = new XSSFWorkbook(is);
		}
		Sheet sheet = wb.getSheetAt(0);
		if (sheet == null) {
			throw new UnifiedOrderRuntimeException(ExceptionMsg.SYS_ERROR.getCode(), "Excel文件无内容");
		}
		int rowCounts = sheet.getLastRowNum();

		List<Map<String, Object>> list = new ArrayList<>();
		// 通过mobile分类
		for (int i = 1; i <= rowCounts; i++) {
			Map<String, Object> excelMap = new HashMap<>();
			sheet.getRow(i).getCell(0).setCellType(CellType.STRING);
			String invoiceNumber = sheet.getRow(i).getCell(0).getStringCellValue();

			sheet.getRow(i).getCell(1).setCellType(CellType.STRING);
			String expressCompanyName = sheet.getRow(i).getCell(1).getStringCellValue();
			try {
				sheet.getRow(i).getCell(2).setCellType(CellType.STRING);
				String expressNo = sheet.getRow(i).getCell(2).getStringCellValue();
				excelMap.put("expressNo", expressNo);
			} catch (Exception e) {
				if (!expressCompanyName.equals("超级前台")) {
					response.setCode(String.valueOf(e.hashCode()));
					response.setSuccess(false);
					response.setMessage("发票单号不可为空！");
					return response;
				}
			}
			excelMap.put("invoiceNumber", invoiceNumber);
			excelMap.put("expressCompanyName", expressCompanyName);
			list.add(excelMap);
		}


		String errorMsg = invoiceApplyDubboConsumerService.importSendInvoiceExcel(getToken(), list);

		if (StringUtils.isBlank(errorMsg)) {
			response.setCode(200);
			response.setSuccess(true);
			response.setMessage("操作成功");
		} else {
			response.setCode(500);
			response.setSuccess(false);
			response.setData(errorMsg);
			response.setMessage(errorMsg);
		}

		return response;
	}
}
