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

import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomerOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.invoice.customer.fundrestream.InvoiceBankStatement;
import cn.superdesk.uniorder.dto.param.invoice.common.InvoiceBankCriteria;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedInvOrderCount;
import cn.superdesk.uniorder.dubbo.consumer.accounting.customer.AccountingUnifiedCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.fundrestream.InvoiceBankStatementDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.common.numerical.AnDateHelper;
import lombok.extern.slf4j.Slf4j;
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.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 java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 银行流水
 */
@Slf4j
@RestController
@RequestMapping("/invoiceBank")
public class InvoiceBankStatementController extends BaseController {


	@Autowired
	private InvoiceBankStatementDubboConsumerService      invoiceBankDubboService;
	@Autowired
	private AccountingUnifiedCustomerDubboConsumerService dzMainDubboConsumerService;
	@Autowired
	private UnifiedOrderDubboConsumerService              unifiedOrderDubboConsumerService;

	/**
	 * 银行流水列表
	 *
	 * @return
	 */
	@PostMapping("/findViewByPage")
	public R findViewByPage() {

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

		InvoiceBankCriteria invoiceBankFromVo = new InvoiceBankCriteria();

		/****************************************** 修改 为可以处理 多id start ******************************************/
		// 流水Id
		invoiceBankFromVo.setId(getLong("id"));

		/****************************************** 修改 为可以处理 多id start ******************************************/

		invoiceBankFromVo.setBankName(getString("bankName"));//银行名称
		invoiceBankFromVo.setStatus(getInteger("status"));//状态
		invoiceBankFromVo.setPayee(getString("payee"));//收款人
		invoiceBankFromVo.setPayeeAccount(getString("payeeAccount"));//收款人账号
		invoiceBankFromVo.setPayStartTime(getString("payStartTime"));//收款日期开始
		invoiceBankFromVo.setPayEndTime(getString("payEndTime"));//收款日期结束

		result = invoiceBankDubboService.findViewByPage(invoiceBankFromVo, getPageNum(), getPageSize());

		return result;
	}

	/**
	 * 导入银行流水Excel
	 *
	 * @param excelFile
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/importBankExcel")
	public R<?> importBankExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {

		R<?> result = 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<InvoiceBankStatement> list = new ArrayList<>();
		// 通过mobile分类
		for (int i = 1; i <= rowCounts; i++) {


			if (sheet.getRow(i) == null || sheet.getRow(i).getCell(0) == null) {
				continue;
			}

			InvoiceBankStatement invoiceBank = new InvoiceBankStatement();


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

			sheet.getRow(i).getCell(1).setCellType(CellType.NUMERIC);
			String payTime = AnDateHelper.formatDate(sheet.getRow(i).getCell(1).getDateCellValue(), AnDateHelper.CURRENT_DATE);

			sheet.getRow(i).getCell(2).setCellType(CellType.STRING);
			BigDecimal count = new BigDecimal(sheet.getRow(i).getCell(2).getStringCellValue());

			String remark = null;
			if (sheet.getRow(i).getCell(3) != null) {
				sheet.getRow(i).getCell(3).setCellType(CellType.STRING);
				remark = sheet.getRow(i).getCell(3).getStringCellValue();
			}

			sheet.getRow(i).getCell(4).setCellType(CellType.STRING);
			String payee = sheet.getRow(i).getCell(4).getStringCellValue();

			sheet.getRow(i).getCell(5).setCellType(CellType.STRING);
			String payeeAccount = sheet.getRow(i).getCell(5).getStringCellValue();

			sheet.getRow(i).getCell(6).setCellType(CellType.STRING);
			String mainname = sheet.getRow(i).getCell(6).getStringCellValue();

			invoiceBank.setBankName(bankName);
			invoiceBank.setPayTime(AnDateHelper.parseToDate(payTime));
			invoiceBank.setCount(count);
			invoiceBank.setRemark(remark);

			invoiceBank.setPayee(payee);
			invoiceBank.setPayeeAccount(payeeAccount);
			invoiceBank.setMainName(mainname);


			invoiceBank.setNoCheckCount(count);

			invoiceBank.setCreateTime(AnDateHelper.getNow());


			list.add(invoiceBank);
		}
		invoiceBankDubboService.importBankStatementExcel(getToken(), list);

		return result;
	}

	/**
	 * 客户结算 -> 收款核销 -> opt删除
	 * 删除银行流水(软删除 update enable = 0
	 * 是否删除 0-删除;1-未删除;
	 *
	 * @return
	 */
	@PostMapping("/delete")
	public R delete() {

		Map<String, Object> params = new HashMap<>();

		params.put("id", getString("id"));

		invoiceBankDubboService.delete(params);

		return new R();
	}


	/**
	 * 客户结算 -> 收款核销 -> opt回款登记
	 *
	 * @return
	 */
	@Deprecated
	@PostMapping("/backRegister")
	public R backRegister() {

		return ResponseResultOuterUtils.createErrorResult("500","歧义 at 20220722");

//		Map<String, Object> params = new HashMap<>();
//
//		params.put("id", getString("id"));
//		params.put("orderGoodIds", getString("orderGoodIds"));//商品Id,','隔开
//		params.put("bankId", getString("bankId"));//银行流水Id
//
//		invoiceBankDubboService.backRegister(params);
//
//
//		/****************************************** TODO 发现个问题 这里基于 AccountingUnifiedCustomerOrder 去反向更新回款状态 是错的 要分 创建维度 start ******************************************/
//		//dz add 20191121
//		List<UnifiedInvOrderCount> uocls = invoiceBankDubboService.getInvOrderCount(getLong("id"));
//
//		if (uocls != null && uocls.size() > 0) {
//			for (UnifiedInvOrderCount item : uocls) {
//
//				// TODO 写死 PayStatus
//				int payStatus = 2;
//
//				if (item.getGoodNums().equals(item.getStatusNums())) {
//					// TODO 写死
//					payStatus = 1;
//				} else {
//					// TODO 写死
//					payStatus = 3;
//				}
//
//				// TODO 发现个问题 这里基于 AccountingUnifiedCustomerOrder 去反向更新回款状态 是错的 要分 创建维度
//				AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder = dzMainDubboConsumerService.findOrderById(item.getDzOrderId());
//
//				if (accountingUnifiedCustomerOrder != null) {
//
//					UnifiedOrder unifiedOrder = unifiedOrderDubboConsumerService.findByOrderSn(accountingUnifiedCustomerOrder.getOrderSn());
//
//					if (unifiedOrder != null) {
//						UnifiedOrder updateObj = new UnifiedOrder();
//						updateObj.setId(unifiedOrder.getId());
//						updateObj.setPayState(payStatus);
//						unifiedOrderDubboConsumerService.updateObj(updateObj);
//					}
//				}
//			}
//		}
//		/****************************************** TODO 发现个问题 这里基于 AccountingUnifiedCustomerOrder 去反向更新回款状态 是错的 要分 创建维度   end ******************************************/
//
//		return new R();
	}

	/**
	 * 根据申请Id获取银行流水
	 *
	 * @return
	 */
	@PostMapping("/getBankByApplyId")
	public R getBankByApplyId() {

		Map<String, Object> params = new HashMap<>();
		params.put("id", getString("id"));

		return new R(invoiceBankDubboService.getBankStatementByApplyId(params));
	}

	/**
	 * 删除-回款登记
	 *
	 * @return
	 */
	@PostMapping("/deleteBackRegister")
	public R deleteBackRegister() {

		Map<String, Object> params = new HashMap<>();
		params.put("invoiceApplyId", getString("invoiceApplyId"));//发票申请Id
		params.put("bankId", getString("bankId"));//银行流水Id

		log.info("");

		invoiceBankDubboService.deleteBackRegister(params);

		return new R();
	}

}
