package cn.superdesk.uniorder.controller.invoice.supplier.state;

import cn.hutool.core.collection.CollUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.enums.invoice.supplier.InvoiceApplySupplierInvoiceProgressingStatusEnum;
import cn.superdesk.uniorder.common.enums.invoice.supplier.InvoiceApplySupplierReceiveInvoiceStatusEnum;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.invoice.supplier.InvoiceApplySupplier;
import cn.superdesk.uniorder.dto.param.invoice.supplier.status.InvoiceApplySupplierOpReceiveInvoiceStatusForm;
import cn.superdesk.uniorder.dto.param.invoice.supplier.status.InvoiceApplySupplierOpReceiveInvoiceStatusFormInnerListItem;
import cn.superdesk.uniorder.dubbo.consumer.invoice.supplier.InvoiceApplySupplierDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.supplier.InvoiceApplySupplierFieldReceiveInvoiceStatusDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 简易状态机 星型结构
 * @Author: linjinyu
 * @CreateDate: 10/12/20 4:28 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 10/12/20 4:28 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "InvoiceApplySupplier - ReceiveInvoiceStatus", tags = {"InvoiceApplySupplier - ReceiveInvoiceStatus"})
@Slf4j
@RestController
@RequestMapping("/invoice/apply/supplier/score/state/receiveInvoiceStatus")
public class InvoiceApplySupplierScoreFieldReceiveInvoiceStatusController extends BaseController {

	@Autowired
	private InvoiceApplySupplierDubboConsumerService                          invoiceApplySupplierDubboConsumerService;
	@Autowired
	private InvoiceApplySupplierFieldReceiveInvoiceStatusDubboConsumerService invoiceApplySupplierFieldReceiveInvoiceStatusDubboConsumerService;

	@ApiOperation(value = "InvoiceApplySupplier - ReceiveInvoiceStatus - 操作 供应商|商户 开票后 发票 寄出 寄给 侨城汇-运营 此时侨城汇-运营 未收票 状态改变为 未收票_0")
	@RequestMapping(value = "/opInit/{id}", method = RequestMethod.POST)
	@ResponseBody
	public R<?> opInit(@PathVariable("id") Long id) {

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

		try {
			InvoiceApplySupplier entity = invoiceApplySupplierDubboConsumerService.findById(id);
			invoiceApplySupplierFieldReceiveInvoiceStatusDubboConsumerService.opInit(entity, getToken());
			result.setSuccess(true);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}

	@ApiOperation(value = "InvoiceApplySupplier - ReceiveInvoiceStatus - 单个开票申请 -操作 侨城汇-运营 op收票登记 发票 寄到后 侨城汇-运营 收到邮件后 此时侨城汇-运营 登记收票 填写发票号 上传凭证等等资料 此时侨城汇-运营 已收票 状态改变为 已收票_1")
	@RequestMapping(value = "/opReceive/{id}", method = RequestMethod.POST)
	@ResponseBody
	public R<?> opReceive(@PathVariable("id") Long id) {

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

		try {
			InvoiceApplySupplier entity = invoiceApplySupplierDubboConsumerService.findById(id);
			invoiceApplySupplierFieldReceiveInvoiceStatusDubboConsumerService.opReceive(entity, getToken());
			result.setSuccess(true);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}

	@ApiOperation(value = "InvoiceApplySupplier - ReceiveInvoiceStatus - 对账单维度 -操作 侨城汇-运营 op收票登记 发票 寄到后 侨城汇-运营 收到邮件后 此时侨城汇-运营 登记收票 填写发票号 上传凭证等等资料 此时侨城汇-运营 已收票 状态改变为 已收票_1")
	@RequestMapping(value = "/opReceive/dim/accountingOrder", method = RequestMethod.POST)
	@ResponseBody
	public R<?> opReceiveDimAccountingOrder(@RequestBody InvoiceApplySupplierOpReceiveInvoiceStatusForm form) { // 以对账单维度自动补全 - 20220111

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

		// TODO 简单验证

		if (CollUtil.isEmpty(form.getSubmitList())) {
			return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
		}

		try {

			/****************************************** 对账单编号 start ******************************************/

			List<String> accountingOrderSns = form.getSubmitList().stream().filter(AnLamdaUtils.distinctByKey(o -> o.getAccountingOrderSn())).map(InvoiceApplySupplierOpReceiveInvoiceStatusFormInnerListItem::getAccountingOrderSn).collect(Collectors.toList());

			if (CollUtil.isEmpty(accountingOrderSns)) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
			}

			if (accountingOrderSns.size() > 1) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
			}

			/****************************************** 开票申请 - 数据库 start ******************************************/

			List<InvoiceApplySupplier> entitysExistDb = invoiceApplySupplierDubboConsumerService.findByAccountingOrderSn(accountingOrderSns.get(0));

			if (CollUtil.isEmpty(entitysExistDb)) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常");
			}

			/****************************************** 传入的开票申请信息判定 start ******************************************/

			List<Long> invoiceApplyIds = form.getSubmitList().stream().map(InvoiceApplySupplierOpReceiveInvoiceStatusFormInnerListItem::getInvoiceApplyId).collect(Collectors.toList());

			List<InvoiceApplySupplier> entitysQueryBySubmit = invoiceApplySupplierDubboConsumerService.findByIds(invoiceApplyIds);

			if (CollUtil.isEmpty(invoiceApplyIds)) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [开票申请] 异常 发票申请Ids为空");
			}
			if (CollUtil.isEmpty(entitysQueryBySubmit)) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [开票申请] 异常 发票申请实体为空");
			}
			if (entitysExistDb.size() != entitysQueryBySubmit.size()) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [开票申请] 异常");
			}

			/****************************************** 申请状态判定 进展 start ******************************************/

			List<Integer> invoiceProgressingStatusList = entitysExistDb.stream().filter(AnLamdaUtils.distinctByKey(o -> o.getInvoiceStatus())).map(InvoiceApplySupplier::getInvoiceStatus).collect(Collectors.toList());

			if (CollUtil.isEmpty(invoiceProgressingStatusList)) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [申请状态] 异常");
			}
			if (invoiceProgressingStatusList.size() > 1) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [申请状态] 异常");
			}

			InvoiceApplySupplierInvoiceProgressingStatusEnum invoiceApplySupplierInvoiceProgressingStatusEnum = InvoiceApplySupplierInvoiceProgressingStatusEnum.get(invoiceProgressingStatusList.get(0));

			if (invoiceApplySupplierInvoiceProgressingStatusEnum != InvoiceApplySupplierInvoiceProgressingStatusEnum.待收票) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [申请状态] 异常, 要求申请状态为 [待收票]");
			}

			/****************************************** 申请状态判定 进展   end ******************************************/

			/****************************************** 收票状态判定 start ******************************************/

			List<Integer> receiveInvoiceStatusList = entitysExistDb.stream().filter(AnLamdaUtils.distinctByKey(o -> o.getReceiveInvoiceStatus())).map(InvoiceApplySupplier::getReceiveInvoiceStatus).collect(Collectors.toList());

			if (CollUtil.isEmpty(receiveInvoiceStatusList)) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [收票状态] 异常");
			}
			if (receiveInvoiceStatusList.size() > 1) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据 [收票状态] 异常");
			}

			InvoiceApplySupplierReceiveInvoiceStatusEnum invoiceApplySupplierReceiveInvoiceStatusEnum = InvoiceApplySupplierReceiveInvoiceStatusEnum.get(receiveInvoiceStatusList.get(0));

			if (invoiceApplySupplierReceiveInvoiceStatusEnum != InvoiceApplySupplierReceiveInvoiceStatusEnum.未收票) {
				return ResponseResultOuterUtils.createErrorResult("500", "提交的数据异常,要求状态为[未收票]");
			}

			/****************************************** 收票状态判定   end ******************************************/

			invoiceApplySupplierFieldReceiveInvoiceStatusDubboConsumerService.opReceive(entitysQueryBySubmit, form, getToken());

			result.setSuccess(true);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
		return result;
	}
}
