package com.upyuns.platform.rs.website.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.upyuns.platform.rs.website.dto.CartOrderDto;
import com.upyuns.platform.rs.website.dto.OrderInfoDto;
import com.upyuns.platform.rs.website.entity.*;
import com.upyuns.platform.rs.website.type.OrderTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.upyuns.platform.rs.website.mapper.ShoppingCartInfoMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 购物车
 *
 * @author jiaoruizhen
 * @email jiaoruizhen@126.com
 * @date 2020-12-03 13:29:23
 */
@Service
public class ShoppingCartInfoBiz extends BaseBiz<ShoppingCartInfoMapper,ShoppingCartInfo> {

	@Autowired
	OrderInfoBiz orderInfoBiz;

	@Autowired
	OrderItemBiz orderItemBiz;

	@Autowired
	IndustryApplicationInfoBiz industryApplicationInfoBiz;

	@Autowired
	ImageImgStorageBiz imageImgStorageBiz;

	@Autowired
	UserFeign userFeign;

	@Autowired
	HttpServletRequest request;

	/**
	 * 添加购物车
	 * @param shoppingCartInfo
	 * @return
	 */
	public ObjectRestResponse addUpdate(ShoppingCartInfo shoppingCartInfo) {
		if (shoppingCartInfo == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		if (shoppingCartInfo.getCartId() == null) {
			insertSelectiveRe(shoppingCartInfo);
		} else {
			ShoppingCartInfo old = selectById(shoppingCartInfo.getCartId());
			BeanUtil.copyProperties(shoppingCartInfo, old, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
			updateSelectiveByIdRe(old);
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 获取用户所有购物车商品
	 * @param userId
	 * @return
	 */
	public ObjectRestResponse getUserAllCart(Integer userId) {
		Example example = new Example(ShoppingCartInfo.class);
		example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0);
		example.orderBy("updTime").desc();
		return ObjectRestResponse.succ(mapper.selectByExample(example));
	}

	/**
	 * 前端用户添加购物车
	 * @param orderInfoDto 商品详情ID
	 * @return
	 */
	public ObjectRestResponse addShoppingCart(OrderInfoDto orderInfoDto) {
		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 (orderInfoDto.getType() == null || orderInfoDto.getType() == null) {
			return ObjectRestResponse.paramIsEmpty();
		}

		//标准数据
		if (OrderTypeEnum.STANDARD_DATA.getType().equals(orderInfoDto.getType())) {

		}

		//影像图库
		if (OrderTypeEnum.IMAGE_STORAGE.getType().equals(orderInfoDto.getType())) {
			ImageImgStorage imageImgStorage = imageImgStorageBiz.selectById(orderInfoDto.getDetailId());
			if (imageImgStorage != null) {
				ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
				shoppingCartInfo.setDetailId(imageImgStorage.getId());
				shoppingCartInfo.setDetailJson(JSONObject.toJSONString(imageImgStorage));
				shoppingCartInfo.setPrice(orderInfoDto.getPrice());
				shoppingCartInfo.setFilePath(orderInfoDto.getFilePath());
				shoppingCartInfo.setNumber(orderInfoDto.getNumber());
				shoppingCartInfo.setItemPic(imageImgStorage.getCoverImg());
				shoppingCartInfo.setName(imageImgStorage.getName());
				shoppingCartInfo.setTotalAmount(orderInfoDto.getPrice().multiply(new BigDecimal(orderInfoDto.getNumber())));
				shoppingCartInfo.setType(orderInfoDto.getType());
				//添加用户信息
				shoppingCartInfo.setRealName(appUserDTO.getRealname());
				shoppingCartInfo.setNickname(appUserDTO.getNickname());
				shoppingCartInfo.setHeadImg(appUserDTO.getHeadimgurl());
				shoppingCartInfo.setPhone(appUserDTO.getUsername());
				shoppingCartInfo.setUserId(appUserDTO.getUserid());
				addUpdate(shoppingCartInfo);
			} else {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			}
		}

		//行业应用信息
		if (OrderTypeEnum.INDUSTRY_INFO.getType().equals(orderInfoDto.getType())) {
			IndustryApplicationInfo industryApplicationInfo = industryApplicationInfoBiz.selectById(orderInfoDto.getDetailId());
			if (industryApplicationInfo != null) {
				ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
				shoppingCartInfo.setDetailId(industryApplicationInfo.getId());
				shoppingCartInfo.setDetailJson(JSONObject.toJSONString(industryApplicationInfo));
				shoppingCartInfo.setPrice(orderInfoDto.getPrice());
				shoppingCartInfo.setFilePath(orderInfoDto.getFilePath());
				shoppingCartInfo.setNumber(orderInfoDto.getNumber());
				shoppingCartInfo.setItemPic(industryApplicationInfo.getCoverImg());
				shoppingCartInfo.setName(industryApplicationInfo.getTitle());
				shoppingCartInfo.setTotalAmount(orderInfoDto.getPrice().multiply(new BigDecimal(orderInfoDto.getNumber())));
				shoppingCartInfo.setType(orderInfoDto.getType());
				//添加用户信息
				shoppingCartInfo.setRealName(appUserDTO.getRealname());
				shoppingCartInfo.setNickname(appUserDTO.getNickname());
				shoppingCartInfo.setHeadImg(appUserDTO.getHeadimgurl());
				shoppingCartInfo.setPhone(appUserDTO.getUsername());
				shoppingCartInfo.setUserId(appUserDTO.getUserid());
				addUpdate(shoppingCartInfo);

			} else {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			}
		}

		return ObjectRestResponse.succ();
	}

	/**
	 * 购物车转为订单
	 * @param cartOrderDto
	 * @return
	 */
	public ObjectRestResponse convertShopCartToOrderInfo(CartOrderDto cartOrderDto) {
		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 (cartOrderDto == null || StringUtils.isBlank(cartOrderDto.getIds())) {
			return ObjectRestResponse.paramIsEmpty();
		}
		String[] cartIds = cartOrderDto.getIds().split(",");
		if (cartIds == null || cartIds.length <= 0) {
			return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
		}
		Example example = new Example(ShoppingCartInfo.class);
		example.createCriteria().andIn("cartId", Arrays.asList(cartIds)).andEqualTo("isDel", 0);
		List<ShoppingCartInfo> cartInfoList = mapper.selectByExample(example);
		if (cartInfoList != null && cartInfoList.size() > 0) {
			convertToOrderInfo(cartInfoList, cartOrderDto, appUserDTO);
			return ObjectRestResponse.succ();
		}
		return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
	}

	/**
	 * 购物车转订单实现
	 * @param cartInfoList
	 */
	private void convertToOrderInfo(List<ShoppingCartInfo> cartInfoList, CartOrderDto cartOrderDto, AppUserDTO appUserDTO) {
		//总金额
		double amount = cartInfoList.parallelStream().mapToDouble(shoppingCartInfo ->shoppingCartInfo.getTotalAmount().doubleValue()).sum();
		//总数量
		Integer totalNumber = cartInfoList.parallelStream().mapToInt(ShoppingCartInfo::getNumber).sum();
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAmount(new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
		orderInfo.setNumber(totalNumber);
		orderInfoBiz.generateOrder(orderInfo);
		cartInfoList.parallelStream().forEach(shoppingCartInfo -> {
			OrderItem orderItem = ShoppingCartInfo.convertToOrderItem(shoppingCartInfo);
			orderItem.setOrderId(orderInfo.getOrderId());
			orderItemBiz.insertSelectiveRe(orderItem);
		});
		//收货信息
		orderInfo.setReceiveName(cartOrderDto.getName());
		orderInfo.setReceivePhone(cartOrderDto.getPhone());
		orderInfo.setReceiveAddress(cartOrderDto.getAddress());

		//用户信息
		orderInfo.setHeadImg(appUserDTO.getHeadimgurl());
		orderInfo.setNickname(appUserDTO.getNickname());
		orderInfo.setPhone(appUserDTO.getUsername());
		orderInfo.setUserId(appUserDTO.getUserid());
		orderInfo.setRealName(appUserDTO.getRealname());

		orderInfoBiz.updateSelectiveByIdRe(orderInfo);
	}
}