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

import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderTypeDimEnum;
import cn.superdesk.uniorder.common.json.JsonUtils;
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 cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseExtInvoiceDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 积分订单 产生的 结算单 开票
 * @Author: linjinyu
 * @CreateDate: 7/1/20 11:37 AM
 * @UpdateUser: linjinyu
 * @UpdateDate: 7/1/20 11:37 AM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "[开票发票] - 积分结算 - 开票申请", tags = {"[开票发票] - 积分结算 - 开票申请"})
@Slf4j
@RestController
@RequestMapping("/invoice/apply/customer/score")
public class InvoiceApplyCustomerScoreController extends BaseController {


	@Autowired
	private InvoiceApplyDubboConsumerService            invoiceApplyDubboConsumerService;
	@Autowired
	private SysEnterpriseDubboConsumerService           sysEnterpriseDubboConsumerService;
	@Autowired
	private SysEnterpriseExtInvoiceDubboConsumerService sysEnterpriseExtInvoiceDubboConsumerService;


	@ApiOperation(value = "积分结算 - 发票申请管理 - List")
	@RequestMapping(value = "/findViewByPage", method = RequestMethod.POST)
	public R<List<InvoiceApplyPage>> findViewByPage(@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria) {

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

//		Map<String, Object> params = new HashMap<>();
//
//		/**
//		 * 时间查询字段
//		 * 申请时间
//		 * 审核时间
//		 */
//		params.put("timeField", getString("timeField"));
//		// 开始时间
//		params.put("startTime", getString("startTime"));
//		// 结束时间
//		params.put("endTime", getString("endTime"));
//		// 审核状态
//		params.put("auditStatus", getInteger("auditStatus"));
//
//		// 开票状态
//		String makeInvoiceStatus = getString("makeInvoiceStatus");
//		if (StringUtils.isNotBlank(makeInvoiceStatus)) {
//			params.put("makeInvoiceStatus", makeInvoiceStatus.split(","));
//		}
//
//		// 企业名称
//		params.put("companyName", getString("companyName"));
//
//		// 关键字查询字段
//		params.put("keywordsField", getString("keywordsField"));
//
//		// 关键字查询字段
//		params.put("keywords", getString("keywords"));
//
//		// 发票申请包含 对账单编号 add at 20201022
//		params.put("accountingOrderSn", getString("accountingOrderSn"));


		log.info("\n\n\nfindViewByPage\nparams \n{}\ntoken  \n{}\n\n\n\n", JsonUtils.toJson(criteria), getToken());

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

		return result;
	}

	@ApiOperation(value = "积分结算 - 发票申请管理 - Head")
	@RequestMapping(value = "/findViewHeadData", method = RequestMethod.POST)
	public R findViewHeadData(@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria) {

//		Map<String, Object> params = new HashMap<>();
//
//		params.put("timeField", getString("timeField"));//时间查询字段
//
//		params.put("startTime", getString("startTime"));//开始时间
//		params.put("endTime", getString("endTime"));//结束时间
//
//		params.put("auditStatus", getInteger("auditStatus"));//审核状态 未审核1 已同意2 已拒绝3
//
//		String makeInvoiceStatus = getString("makeInvoiceStatus");
//		if (StringUtils.isNotBlank(makeInvoiceStatus)) {
//			params.put("makeInvoiceStatus", makeInvoiceStatus.split(","));//开票状态 0未开票 1 已开票 2重新开票
//		}
//
//		params.put("keywordsField", getString("keywordsField"));//关键字查询字段
//		params.put("keywords", getString("keywords"));//关键字查询字段
//
//		// 发票申请包含 对账单编号 add at 20210222
//		params.put("accountingOrderSn", getString("accountingOrderSn"));

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


	@ApiOperation(value = "积分结算 - 发票申请管理|发票管理 - opt 查看详情")
	@RequestMapping(value = "/getDetail", method = RequestMethod.POST)
	public R invoiceOptApplyDetail(@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria) {

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


		log.info("积分结算 - 发票申请管理 - opt 查看详情 params : \n{}", JsonUtils.toJson(criteria));

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

	/**
	 * /invoice/apply/customer/score/deleteInvoiceApply
	 *
	 * @return
	 */
	@ApiOperation(value = "积分结算 - 发票申请管理|发票管理 - opt 删除")
	@RequestMapping(value = "/deleteInvoiceApply", method = RequestMethod.POST)
	public R invoiceOptApplyDelete() {

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

		// 发票申请Id
		params.put("id", getLong("id"));


		log.info("积分结算 - 发票申请管理 - opt 删除 params : \n{}", JsonUtils.toJson(params));

		invoiceApplyDubboConsumerService.deleteInvoiceApply(getLong("id"));

		return new R("200", "删除成功", true);
	}

	/**
	 * /invoice/apply/customer/score/exportInvoiceApplyExcel
	 *
	 * @param criteria
	 * @throws IOException
	 */
	@ApiOperation(value = "积分结算 - 发票申请管理 - opt 导出报表")
	@RequestMapping(value = "/exportInvoiceApplyExcel", method = RequestMethod.POST)
	public R<String> exportExcelInvoiceApply(
//			HttpServletResponse response
			@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria
	) throws IOException {

		log.info("{}", JsonUtils.toJson(criteria));

//		Integer mode = 1; // 1 结果 2 选择

//		try {

//			Map<String, Object> params = new HashMap<>();
//
//			String invoiceApplyIdsStr = getString("invoiceApplyIds");
//
//			if (StringUtils.isNotBlank(invoiceApplyIdsStr)) {
//
//				Object[] invoiceApplyIds = AnStringUtils.stringArrayConvertToLongList(invoiceApplyIdsStr, ",").toArray();
//
//				if (invoiceApplyIds.length > 0) {
//					// 发票申请 Ids
//					params.put("ids", invoiceApplyIds);
//
//					mode = 2; // 2 选择
//				} else {
//					return;
//				}
//
//			} else {
//				// 时间查询字段
//				params.put("timeField", getString("timeField"));
//
//				// 开始时间
//				params.put("startTime", getString("startTime"));
//				// 结束时间
//				params.put("endTime", getString("endTime"));
//				// 审核状态
//				params.put("auditStatus", getInteger("auditStatus"));
//
//				// 开票状态
//				String makeInvoiceStatus = getString("makeInvoiceStatus");
//				if (StringUtils.isNotBlank(makeInvoiceStatus)) {
//					params.put("makeInvoiceStatus", makeInvoiceStatus.split(","));
//				}
//				// 关键字查询字段
//				params.put("keywordsField", getString("keywordsField"));
//				// 关键字查询字段
//				params.put("keywords", getString("keywords"));
//
//				// 发票申请包含 对账单编号 add at 20201022
//				params.put("accountingOrderSn", getString("accountingOrderSn"));
//			}


		/****************************************** 重构 当中的方法已经迁移 mark by linjinyu at 20210318 start ******************************************/

//			List<ExportExcelInvoiceApplyForceScoreDimCreditVo> result = invoiceApplyDubboConsumerService.findInvoiceApplyFocusScoreDimCredit(getToken(), params);
//
//			HSSFWorkbook workbook = null;
//
//			// 结果导出 数据为流水维度数据
//			if (mode.equals(1)) {
//				workbook = ExcelExportModePoiHssfUtils.createWorkbook(result, fieldHeadMode1, fieldValueMode1, "发票申请-结果模式");
//			}
//			// 勾选导出 数据为流水维度数据 基于 开票申请编号 IN2021022300002 来分组 每一份数据 有合并前 合并后
//			else if (mode.equals(2)) {
//				workbook = mergeResultByExcelDebugAndCreateWorkbook(result);
//			}
//
//			ExcelResponse.out(workbook, "客户结算(对账)" + "_" + "发票(开票申请)" + "_" + "导出报表", response);
		/****************************************** 重构 当中的方法已经迁移 mark by linjinyu at 20210318 start ******************************************/

//		return ResponseResultUtil.createSuccesResult();

		return new R<>(invoiceApplyDubboConsumerService.exportExcelInvoiceApplyFocusScoreDimCredit(getToken(), criteria));
//
//		} catch (Exception e) {
//
//			log.error(ExceptionUtils.getMessage(e));
//			e.printStackTrace();
//		}
	}


	/**
	 * 对映一般订单 开票申请 搜索
	 *
	 * @return
	 */
	@ApiOperation(value = "积分结算 - 开票申请页面 - opt 搜索")
	@PostMapping("/invoiceApplySelect")
	public R opApplySelect(@RequestBody ExportExcelInvoiceApplyQueryCriteria criteria) {

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

		// getString("accountingScoreCustomerId")
		if (null == criteria.getAccountingScoreCustomerId()) {
			return new R("500", "参数错误,对账单Id号不能为空", false);
		}
		// getString("accountingOrderSn")
		if (null != criteria.getAccountingOrderSn()) {
			return new R("500", "参数错误,不支持对账单Sn号", false);
		}
//
//		// 下拉 start
////		params.put("accountingOrderSn", getString("accountingOrderSn"));//对账单编号 20201022 按这个功能 不能支付 对账单编号了
//		params.put("accountingScoreCustomerId", getString("accountingScoreCustomerId"));//对账单Id
//		// 下拉 end
////		params.put("accountingStatus", 1);// 对账单状态，0-未确认，1-已确认，-1-已取消

		// 实际xml上是没有的
//		criteria.setAccountingStatus(1);

		return new R(invoiceApplyDubboConsumerService.invoiceApplySelectFocusScoreDimCredit(criteria));
	}

	/**
	 * TODO 一般订单
	 * 客户结算 > 开票申请管理 > opt 申请开票 -> 编辑页面 opt 提交
	 * 发票申请
	 *
	 * @return
	 */
	@ApiOperation(value = "积分结算 - 开票申请页面 - opt 搜索")
	@PostMapping("/invoiceApply")
	public R opApply() {

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

//		orderGoodsObj
//		{
//			'unifiedOrderCreditId' : "对映 接口 invoiceApplySelect 返回数据 .unifiedOrderCreditId",
//			'unifiedOrderGoodsId' : "对映 接口 invoiceApplySelect 返回数据 .unifiedOrderGoodsId",
//			'unifiedOrderId' : "对映 接口 invoiceApplySelect 返回数据 .unifiedOrderId",
//			'accountingOrderId' : "对映 接口 invoiceApplySelect 返回数据 .accountingOrderId",
//		}


		/**
		 * 商品Id列表，','隔开 弃用 20200716 by linjinyu
		 */
//		params.put("orderGoodIds", getString("orderGoodIds"));


		params.put("accountingOrderTypeDim", AccountingOrderTypeDimEnum.积分订单.getKey());
		params.put("dimCreateBy", AccountingOrderDimCreateByEnum.流水.getKey());

		/**
		 * InvoiceApplyOrderGoodsParams
		 */
		params.put("orderGoodsObj", getString("orderGoodsObj"));
		/**
		 * 添加一个 企业ID 20200716 by linjinyu 如果这个开票不是以企业维度开， 这个想法就是错的了
		 */
		params.put("purchaseVirtId", getLong("purchaseVirtId"));
		/**
		 * 发票抬头
		 */
		params.put("invoiceCompanyName", getString("invoiceCompanyName"));
		/**
		 * 发票类型
		 */
		params.put("invoiceType", getString("invoiceType"));
		/**
		 * 备注
		 */
		params.put("remark", getString("remark"));
		/**
		 * 税率Id
		 */
		params.put("taxRate", getString("taxRate"));

		if (StringUtils.isEmpty(getString("freeAmount"))
				|| StringUtils.isEmpty(getString("realAmount"))) {
			return new R("400", "金额错误！", false);
		}

		params.put("freeAmount", getString("freeAmount"));
		params.put("realAmount", getString("realAmount"));

		log.info("客户结算 > 开票申请管理 > opt 申请开票 -> 编辑页面 opt 提交 params: \n{}", JsonUtils.toJson(params));

		return invoiceApplyDubboConsumerService.invoiceApplyFocusScore(getToken(), params);
	}


	/**
	 * 客户结算 - 开票申请管理 - opt row 审核 (申请开票) 按扭 同意 拒绝
	 * /invoice/apply/customer/score/audit
	 *
	 * @return
	 */
	@ApiOperation(value = "积分结算 - 开票申请管理 - opt row 审核 (申请开票) 按扭 同意 拒绝")
	@PostMapping("/audit")
	public R opAudit() {

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

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

		log.info("客户结算 - 开票申请管理 - opt row 审核 (申请开票) 按扭 同意 拒绝 params : \n{}", JsonUtils.toJson(params));

		invoiceApplyDubboConsumerService.check(getToken(), params);

		return new R();
	}


	/**
	 * 客户结算 - 开票申请管理 - opt 开票登记
	 * TODO 标记 可以共用
	 * /invoice/apply/customer/score/invoiceRegister
	 *
	 * @return
	 */
	@ApiOperation(value = "积分结算 - 开票申请管理 - opt 开票登记")
	@PostMapping("/invoiceRegister")
	public R opRegister() {

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

		/**
		 * 发票申请Id
		 */
		params.put("id", getString("id"));
		/**
		 * 开票日期 手动填写
		 */
		params.put("datestr", getString("datestr"));
		/**
		 * 发票号
		 */
		params.put("invoiceNumber", getString("invoiceNumber"));

		invoiceApplyDubboConsumerService.invoiceRegister(getToken(), params);

		return new R();
	}
}