package com.xxfc.platform.order.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
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.google.common.collect.Lists;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
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.universal.entity.OrderData;
import com.xxfc.platform.universal.entity.vo.InvoiceVo;
import com.xxfc.platform.universal.feign.ThirdFeign;
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 org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

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;

	@Autowired
	ThirdFeign thirdFeign;

	/**
	 * 添加发票记录
	 * @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(",");
		List<OrderData> list = Lists.newArrayList();
		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) { //不存在就添加
					OrderData orderData = new OrderData();
					if (baseOrder.getType() == OrderTypeEnum.RENT_VEHICLE.getCode()) {
						orderData.setOrderName(OrderTypeEnum.RENT_VEHICLE.getDesc());
					}
					if (baseOrder.getType() == OrderTypeEnum.TOUR.getCode()) {
						orderData.setOrderName(OrderTypeEnum.TOUR.getDesc());
					}
					if (baseOrder.getType() == OrderTypeEnum.MEMBER.getCode()) {
						orderData.setOrderName(OrderTypeEnum.MEMBER.getDesc());
					}
					orderData.setPrice(baseOrder.getRealAmount());
					list.add(orderData);
					continue;
				} else {//已开票
					log.info("该订单已经开票， {}", orderId);
					return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "该订单已经开票: orderId = " + orderId);
				}
			}
			orderInvoice.setUserId(appUserDTO.getUserid());
			insertSelectiveRe(orderInvoice);
			log.info("添加发票记录成功: {}", orderInvoice);
			List<OrderInvoice> invoiceList = selectByIds(orderInvoice.getOrderIds()).getData();
			if(invoiceList != null && invoiceList.size() > 0) {
				OrderInvoice newValue = invoiceList.get(0);
				//调用第三方开票接口
				InvoiceVo invoiceVo = new InvoiceVo();
				invoiceVo.setContent(newValue.getContentTitle());
				invoiceVo.setOrderId(newValue.getOrderIds());
				invoiceVo.setPurchaserAccountBank(newValue.getContentAccount());
				invoiceVo.setPurchaserAddressPhone(newValue.getContentContact());
				invoiceVo.setPurchaserEmail(newValue.getReceiveContent());
				invoiceVo.setPurchaserName(newValue.getTitleName());
				invoiceVo.setPurchaserTaxCode(newValue.getTaxCode());
				invoiceVo.setRemark(newValue.getContentRemark());
				invoiceVo.setOrderInvoiceId(newValue.getId());
				ObjectRestResponse objectRestResponse = thirdFeign.invoicing(invoiceVo);
				if (!objectRestResponse.isRel()) {
					return objectRestResponse;
				}
				//更新订单状态
				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);
					}
					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));
			}
		}
		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);
				}
			}
		}
		List<OrderInvoice> list = Lists.newArrayList();
		list.addAll(set);
		return ObjectRestResponse.succ(list);
	}

	/**
	 * 获取用户的发票记录列表
	 * @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);
	}

	public ObjectRestResponse update(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 || orderInvoice.getId() == null) {
			return  ObjectRestResponse.paramIsEmpty();
		}
		OrderInvoice oldValue = mapper.selectByPrimaryKey(orderInvoice.getId());
		if (oldValue != null) {
			BeanUtil.copyProperties(orderInvoice, oldValue, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
			updateSelectiveByIdRe(oldValue);
			return ObjectRestResponse.succ();
		}
		return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "发票不存在！");
	}


	@Transactional(rollbackFor = Exception.class)
	public boolean updateByOrderId(OrderInvoice orderInvoice) {
		try {
			Example example = new Example(OrderInvoice.class);
			example.createCriteria().andEqualTo("orderIds",orderInvoice.getOrderIds());
			mapper.updateByExample(orderInvoice,example);
			return true;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error("修改状态异常={}",e);
			return false;
		}
	}
}
