package com.xxfc.platform.order.biz;

import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderInvoice;
import com.xxfc.platform.order.mapper.OrderInvoiceMapper;
import com.xxfc.platform.order.pojo.dto.OrderInvoiceDto;
import com.xxfc.platform.vehicle.constant.ResCode.ResCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 订单发票记录
 */
@Service
@Slf4j
public class OrderInvoiceBiz extends BaseBiz<OrderInvoiceMapper, OrderInvoice> {

	@Autowired
	BaseOrderBiz baseOrderBiz;

	@Autowired
	UserFeign userFeign;

	@Autowired
	HttpServletRequest request;
	/**
	 * 添加发票记录
	 * @return
	 */
	@Transactional
	public ObjectRestResponse add(OrderInvoice orderInvoice) {
		AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
		if (appUserDTO == null) {
			return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
		}
		if (orderInvoice == null || StringUtils.isBlank(orderInvoice.getOrderIds())) {
			return  ObjectRestResponse.paramIsEmpty();
		}
		String[] orderIdArray = orderInvoice.getOrderIds().split(",");
		if (orderIdArray.length > 0) {
			for (int a = 0; a <= orderIdArray.length - 1; a ++) {
				String orderId = StringUtils.isBlank(orderIdArray[a])? "0" : orderIdArray[a];
				BaseOrder baseOrder = baseOrderBiz.selectById(Integer.parseInt(orderId));
				if (baseOrder == null) {
					return ObjectRestResponse.createFailedResult(ResCode.ORDER_IS_NOT_EXIST.getCode(), ResCode.ORDER_IS_NOT_EXIST.getDesc() + ", 订单Id = " + orderId);
				}
				//查询是否已开票
				OrderInvoice oldValue = selectByUserIdAndOrderId(appUserDTO.getUserid(), Integer.parseInt(orderId)).getData();
				if (oldValue == null) { //不存在就添加
					orderInvoice.setUserId(appUserDTO.getUserid());
					insertSelectiveRe(orderInvoice);
					log.info("添加发票记录成功: {}", orderInvoice);
					OrderInvoice newValue = selectByUserIdAndOrderId(appUserDTO.getUserid(), Integer.parseInt(orderId)).getData();
					if(newValue != null) {
						baseOrder.setInvoiceStatus(1);
						baseOrder.setInvoiceId(newValue.getId());
						baseOrderBiz.updateBaseOrder(baseOrder);
					} else {
						return ObjectRestResponse.createFailedResult(ResultCode.DB_OPERATION_FAIL_CODE, ResultCode.getMsg(ResultCode.DB_OPERATION_FAIL_CODE));
					}
				} else {//已开票
					log.info("该订单已经开票， {}", orderId);
					return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "该订单已经开票: orderId = " + orderId);
				}
			}
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 根据orderIds字符串查询对应的发票记录
	 * @param orderIds
	 * @return
	 */
	public ObjectRestResponse<List<OrderInvoice>> selectByIds(String orderIds) {
		AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
		if (appUserDTO == null) {
			return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
		}
		if (StringUtils.isBlank(orderIds)) {
			return ObjectRestResponse.paramIsEmpty();
		}
		Set<OrderInvoice> set = new HashSet<>();
		String[] orderIdArray = orderIds.split(",");
		if (orderIdArray.length > 0) {
			for (int a = 0; a <= orderIdArray.length -1; a++) {
				OrderInvoice orderInvoice = selectByUserIdAndOrderId(appUserDTO.getUserid(), Integer.parseInt(orderIdArray[a])).getData();
				if(orderInvoice != null) {
					set.add(orderInvoice);
				}
			}
		}
		return ObjectRestResponse.succ(set);
	}

	/**
	 * 获取用户的发票记录列表
	 * @return
	 */
	public ObjectRestResponse selectByToken(OrderInvoiceDto orderInvoiceDto) {
		AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
		if (appUserDTO == null) {
			return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
		}
		orderInvoiceDto.setUserId(appUserDTO.getUserid());
		return getByParam(orderInvoiceDto);
	}

	/**
	 * 根据用户Id获取用户发票记录
	 * @param
	 * @return
	 */
	public ObjectRestResponse selectByUserId(OrderInvoiceDto orderInvoiceDto) {
		return getByParam(orderInvoiceDto);
	}

	public ObjectRestResponse<OrderInvoice> selectByUserIdAndOrderId(Integer userId, Integer orderId) {

		return ObjectRestResponse.succ(mapper.selectByUserIdAndOrderId(new OrderInvoice(){{
			setUserId(userId);
			setOrderIds(orderId + "");
		}}));
	}

	public ObjectRestResponse<PageDataVO<OrderInvoice>> getByParam(OrderInvoiceDto orderInvoiceDto) {
		Query query = new Query(orderInvoiceDto);
		PageDataVO<OrderInvoice> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.getByParam(query.getSuper()));
		return ObjectRestResponse.succ(pageDataVO);
	}

}
