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

import cn.superdesk.uniorder.common.R;
import cn.superdesk.uniorder.common.enums.ExceptionMsg;
import cn.superdesk.uniorder.common.exception.SuperdeskUniOrderException;
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.fundrestream.InvoiceBank;
import cn.superdesk.uniorder.dto.vo.invoice.InvoiceBankFromVo;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedInvOrderCount;
import cn.superdesk.uniorder.dubbo.consumer.accounting.AccountingUnifiedCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.InvoiceBankDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.unified.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.utils.DateHelper;
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 InvoiceBankController extends BaseController {


	@Autowired
	InvoiceBankDubboConsumerService               invoiceBankDubboService;
	@Autowired
	AccountingUnifiedCustomerDubboConsumerService dzMainDubboConsumerService;
	@Autowired
	UnifiedOrderDubboConsumerService              unifiedOrderDubboConsumerService;

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

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

		InvoiceBankFromVo invoiceBankFromVo = new InvoiceBankFromVo();

		invoiceBankFromVo.setId(getLong("id"));//流水Id
		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 SuperdeskUniOrderException(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 SuperdeskUniOrderException(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<>();
			if (sheet.getRow(i) == null || sheet.getRow(i).getCell(0) == null) {
				continue;
			}
//			String     bankName     = "";
//			String     payTime      = "";
//			BigDecimal count        = BigDecimal.ZERO;
//			String     remark       = "";
//			String     payee        = "";
//			String     payeeAccount = "";
//			String     mainname     = "";


			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 = DateHelper.formatDate(sheet.getRow(i).getCell(1).getDateCellValue(), DateHelper.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();

			excelMap.put("bankName", bankName);
			excelMap.put("payTime", payTime);
			excelMap.put("count", count);
			excelMap.put("remark", remark);
			excelMap.put("payee", payee);
			excelMap.put("payeeAccount", payeeAccount);
			excelMap.put("mainName", mainname);

			list.add(excelMap);
		}
		invoiceBankDubboService.importBankExcel(getToken(), list);

		return result;
	}

	/**
	 * 删除银行流水(软删除 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();
	}


	/**
	 * 回款登记
	 *
	 * @return
	 */
	@PostMapping("/backRegister")
	public R backRegister() {

		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);

		//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;
				}
				AccountingUnifiedCustomerOrder dzOrder = dzMainDubboConsumerService.findOrderById(item.getDzOrderId());

				if (dzOrder != null) {

					UnifiedOrder unifiedOrder = unifiedOrderDubboConsumerService.findBySn(dzOrder.getOrderSn());

					if (unifiedOrder != null) {
						UnifiedOrder updateObj = new UnifiedOrder();
						updateObj.setId(unifiedOrder.getId());
						updateObj.setPayState(payStatus);
						unifiedOrderDubboConsumerService.updateObj(updateObj);
					}
				}
			}
		}

		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.getBankByApplyId(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();
	}

}
