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

import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.DzMainAutoParam;
import cn.superdesk.uniorder.dto.vo.inv.ViewInvoiceDetailsHead;
import cn.superdesk.uniorder.dto.vo.inv.ViewInvoiceDetailsList;
import cn.superdesk.uniorder.dto.vo.inv.ViewInvoiceManage;
import cn.superdesk.uniorder.dto.vo.inv.ViewconfirmInvoiceHead;
import cn.superdesk.uniorder.dubbo.consumer.order._leaveover.SysInvoiceDubboConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/invoice")
public class SysInvoiceController extends BaseController {


	@Autowired
	SysInvoiceDubboConsumerService sysInvoiceDubboConsumerService;


	/**
	 * 发票管理或寄票登记列表 订单级显示
	 * 已登记过发票的订单
	 * 不管帐单 订单级接入选择后的发票表ID
	 * 寄票登记   重新开票 都是订单级的
	 *
	 * @return
	 */
	@PostMapping("/findInvoiceManageByPage")
	@ResponseBody
	public R<List<ViewInvoiceManage>> findInvoiceManageByPage() {
		R<List<ViewInvoiceManage>> result = new R<>();
		try {

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

			//1下单时间 2开票时间 3对帐时间 4寄票时间
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));

			params.put("enterpriseName", getString("enterpriseName"));//企业名称
			params.put("dzSn", getString("dzSn"));//帐单编码
			params.put("orderSn", getString("orderSn"));//订单编码

			if (StringUtils.isNotEmpty(getString("backStatus"))) {//0未回款\1部分回款\2全部回款
				params.put("backStatus", Byte.valueOf(getString("backStatus")));
			}

			if (StringUtils.isNotEmpty(getString("invoiceStatus"))) {//发票状态 0未邮寄 1已邮寄 2已作废
				params.put("invoiceStatus", Byte.valueOf(getString("invoiceStatus")));
			}

			params.put("companyName", getString("companyName"));//开票抬头
			params.put("merchName", getString("merchName"));//商户名称	1

			params.put("realname", getString("realname"));//下单人
			params.put("address_realname", getString("address_realname"));//收件人
			params.put("invoiceNumberNotNull", "true");//发票号不为空


			String invoiceIds = request.getParameter("invoiceIds");//invoiceId,invoiceId
			if (StringUtils.isNotEmpty(invoiceIds)) {
				params.put("invoiceIds", invoiceIds.split(","));//Array
			}


			result = sysInvoiceDubboConsumerService.findInvoiceManageViewPage(getToken(), params, getPageNum(), getPageSize());

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 开票登记界面
	 *
	 * @return
	 */
	@PostMapping("/findConfirmInvoice")
	@ResponseBody
	public R<ViewconfirmInvoiceHead> findConfirmInvoice() {

		R<ViewconfirmInvoiceHead> result = new R<>();

		try {

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

			String mdzIds = request.getParameter("mdzIds");

			headParams.put("mdzIds", mdzIds.split(","));
			ViewconfirmInvoiceHead viewconfirmInvoiceHead = new ViewconfirmInvoiceHead();

			List<ViewInvoiceManage> listViewInvoiceDetailsHeads = sysInvoiceDubboConsumerService.findInvoiceManageList(getToken(), headParams);

			if (listViewInvoiceDetailsHeads.size() >= 1) {
				ViewInvoiceManage viewInvoiceManage = listViewInvoiceDetailsHeads.get(0);
				viewconfirmInvoiceHead.setCompanyName(viewInvoiceManage.getCompanyName());
				viewconfirmInvoiceHead.setEnterpriseName(viewInvoiceManage.getEnterpriseName());
			}

			BigDecimal billAccount = BigDecimal.ZERO;
			Integer    billNum     = 0;
			if (listViewInvoiceDetailsHeads.size() >= 1) {
				ViewInvoiceManage vm = listViewInvoiceDetailsHeads.get(0);
				billNum = vm.getOrderNum();
				billAccount = vm.getInvoiceAccount();
			}

			viewconfirmInvoiceHead.setBillNum(billNum);
			viewconfirmInvoiceHead.setBillAccount(billAccount);


			viewconfirmInvoiceHead.setListInvoiceManage(listViewInvoiceDetailsHeads);//开票登记 账单信息

			result.setData(viewconfirmInvoiceHead);
		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}

		return result;
	}


	/**
	 * 发票详情
	 *
	 * @return
	 */
	@PostMapping("/invoiceDetails")
	@ResponseBody
	public R<ViewInvoiceDetailsHead> invoiceDetails() {

		R<ViewInvoiceDetailsHead> result = new R<>();

		try {

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

			String invoiceId = request.getParameter("invoiceId");

			headParams.put("invoiceId", invoiceId);
			ViewInvoiceDetailsHead viewInvoiceDetailsHead = new ViewInvoiceDetailsHead();

			List<ViewInvoiceDetailsHead> listViewInvoiceDetailsHeads = sysInvoiceDubboConsumerService.getInvoiceDetailByInvoiceId(getToken(), headParams);
			if (listViewInvoiceDetailsHeads.size() == 1) {
				viewInvoiceDetailsHead = listViewInvoiceDetailsHeads.get(0);
			}

			//没有分页
			//String mdzId=viewInvoiceDetailsHead.getMdzId();
			headParams = new HashMap<>();
			headParams.put("invoiceId", invoiceId);//根据发票来查

			List<ViewInvoiceDetailsList> listInvoices = sysInvoiceDubboConsumerService.findInvoiceDetailsList(getToken(), headParams);

			viewInvoiceDetailsHead.setListViewInvoiceManage(listInvoices);//发票明细

			result.setData(viewInvoiceDetailsHead);

		} catch (Exception e) {
			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 寄票登记或确认开票
	 * 只有已确认未开票,已确认部分开票的账单可以进行开票登记 前端控制
	 *
	 * @param role
	 * @return
	 */
	@PostMapping("/mailTickRegister")
	@ResponseBody
	public R mailTickRegister(DzMainAutoParam model) {

		R result = new R<>();


		/*mdzId
		orderId
		expressCompanyId
		express_no*/

		String mailTickRegisterListJson = request.getParameter("mailTickRegisterList");//申请放行物品列表
		String operationStr             = request.getParameter("operationStr");

		log.info("mailTickRegister==>mailTickRegisterListJson:" + mailTickRegisterListJson);

		List<Map> mailTickRegisterList = com.alibaba.fastjson.JSON.parseArray(mailTickRegisterListJson, Map.class);
		try {

			//String operationStr="mailTickRegister";//confirmInvoice
			Map<String, Object> returnMap = sysInvoiceDubboConsumerService.mailTickRegister(getToken(), mailTickRegisterList, operationStr);

			result.setData(returnMap);

			log.info("mailTickRegister==>returnMap:" + returnMap.toString());

			result.setSuccess(true);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}

		return result;
	}


	/**
	 * 重新开票
	 *
	 * @param role
	 * @return
	 */
	@PostMapping("/reInvoiceRegister")
	@ResponseBody
	public R reInvoiceRegister(DzMainAutoParam model) {
		R result = new R<>();


		/*mdzId
		orderId
		expressCompanyId
		express_no*/

		String mdzId   = request.getParameter("mdzId");
		String orderId = request.getParameter("orderId");


		try {

			//String operationStr="mailTickRegister";//confirmInvoice
			Map<String, Object> returnMap = sysInvoiceDubboConsumerService.reInvoiceRegister(getToken(), mdzId, orderId);

			result.setData(returnMap);

			result.setSuccess(true);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}

		return result;
	}


	/**
	 * 发票管理-导入寄票信息
	 *
	 * @param role
	 * @return
	 */
	@PostMapping("/importDZExcel")
	@ResponseBody
	public R importDZExcel(@RequestParam("excelFile") MultipartFile excelFile) {

		R result = new R<>();


		/*mdzId
		orderId
		expressCompanyId
		express_no*/

		//String mdzId=request.getParameter("mdzId");
		//String orderId=request.getParameter("orderId");


		try {

			HSSFWorkbook workbook = new HSSFWorkbook(excelFile.getInputStream());
			//XSSFWorkbook workbook=new XSSFWorkbook(ins);
			//Workbook workbook = WorkbookFactory.create(excelFile.getInputStream());
			Sheet sheet = workbook.getSheet("Sheet1");


			int                       rowCounts = sheet.getLastRowNum();
			List<Map<String, String>> list      = new ArrayList<Map<String, String>>(rowCounts-1);

			//List<String> excelColumnNames=new ArrayList<String>();

			//双重for循环取出数据
			for (int i = 1; i <= rowCounts; i++) {

				Map<String, String> excelMap = new HashMap<String, String>();

	        	/*sheet.getRow(i).getCell(0).setCellType(CellType.STRING);
	        	String  mdzId=sheet.getRow(i).getCell(0).getStringCellValue();

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

	        	sheet.getRow(i).getCell(2).setCellType(CellType.STRING);
	        	String  invoiceNumber=sheet.getRow(i).getCell(2).getStringCellValue();*/


				int myOrderSnColIndex = 33;//二级订单编码
				sheet.getRow(i).getCell(myOrderSnColIndex).setCellType(CellType.STRING);
				String myOrderSn = sheet.getRow(i).getCell(myOrderSnColIndex).getStringCellValue();


				int invoiceNumberColIndex = 5;//发票号
				sheet.getRow(i).getCell(invoiceNumberColIndex).setCellType(CellType.STRING);
				String invoiceNumber = sheet.getRow(i).getCell(invoiceNumberColIndex).getStringCellValue();

				excelMap.put("myOrderSn", myOrderSn);
				excelMap.put("invoiceNumber", invoiceNumber);
				list.add(excelMap);
			}

			log.info("importDZExcel==>list:" + list.toString());
			Map<String, Object> returnMap = sysInvoiceDubboConsumerService.importDZExcel(getToken(), list);
			result.setData(returnMap);
			result.setSuccess(true);

		} catch (Exception e) {
			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * 开票登记记录
	 * 有分页 可以不页记录设置大点
	 *
	 * @return
	 */
	@PostMapping("/invoiceRegisterByPage")
	@ResponseBody
	public R<List<ViewInvoiceManage>> invoiceRegister() {

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

		try {

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

			//帐单ID
			String mdzId = request.getParameter("mdzId");

			params.put("mdzId", mdzId);

			result = sysInvoiceDubboConsumerService.findInvoiceManageViewPage(getToken(), params, getPageNum(), getPageSize());

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}

		return result;
	}


	/**
	 * 确认开票
	 *
	 * @param role
	 * @return
	 */
	@PostMapping("/confirmInvoice")
	@ResponseBody
	public R confirmInvoice(DzMainAutoParam model) {
		R result = new R<>();


		/*mdzId
		orderId
		expressCompanyId
		express_no*/

		String    mailTickRegisterListJson = request.getParameter("mailTickRegisterList");//申请放行物品列表
		List<Map> mailTickRegisterList     = com.alibaba.fastjson.JSON.parseArray(mailTickRegisterListJson, Map.class);
		try {

			String              operationStr = "mailTickRegister";
			Map<String, Object> returnMap    = sysInvoiceDubboConsumerService.mailTickRegister(getToken(), mailTickRegisterList, operationStr);
			result.setData(returnMap);
			result.setSuccess(true);
		} catch (Exception e) {
			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return result;
	}

	//未回款**************************************************************************


	//未回款**************************************************************************

}
