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.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.upyuns.platform.rs.datacenter.fegin.DatacenterFeign;
import com.upyuns.platform.rs.datacenter.pojo.ImageDataVO;
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.NoticeTypeEnum;
import com.upyuns.platform.rs.website.type.OrderTypeEnum;
import com.upyuns.platform.rs.website.vo.ItemInfoVo;
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;
import java.util.Set;

/**
 * 购物车
 *
 * @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;

	@Autowired
	DatacenterFeign datacenterFeign;

	@Autowired
	NoticeInfoBiz noticeInfoBiz;

	/**
	 * 添加购物车
	 *
	 * @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 orderInfoDto
	 * @return
	 */
	public ObjectRestResponse getUserAllCart(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));
		}
		Example example = new Example(ShoppingCartInfo.class);
		example.createCriteria().andEqualTo("userId", appUserDTO.getUserid()).andEqualTo("isDel", 0);
		example.orderBy("updTime").desc();
		Query query = new Query(orderInfoDto);
		PageDataVO<ShoppingCartInfo> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
		return ObjectRestResponse.succ(pageDataVO);
	}

	/**
	 * 前端用户添加购物车
	 *
	 * @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())) {
			List<ImageDataVO> imageDataVOList = datacenterFeign.queryByIds(orderInfoDto.getDetailId() + "").getData();
			if (imageDataVOList != null && imageDataVOList.size() > 0) {
				ImageDataVO imageDataVO = imageDataVOList.get(0);
				ShoppingCartInfo old = selectByUser(appUserDTO.getUserid(), Long.valueOf(imageDataVO.getId()));
				if (old != null) {
					return ObjectRestResponse.succ();
					//return ObjectRestResponse.createFailedResult(ResultCode.ORDER_GOODS_EXIST, ResultCode.getMsg(ResultCode.ORDER_GOODS_EXIST));
				} else {
					ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
					shoppingCartInfo.setDetailId(Long.valueOf(imageDataVO.getId()));
					shoppingCartInfo.setDetailJson(JSONObject.toJSONString(imageDataVO));
					shoppingCartInfo.setPrice(imageDataVO.getPrice());
					shoppingCartInfo.setFilePath(orderInfoDto.getFilePath());
					shoppingCartInfo.setNumber(orderInfoDto.getNumber());
					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);
					//添加通知信息
					noticeInfoBiz.addObj("商品" + shoppingCartInfo.getName() + "已添加购物车", NoticeTypeEnum.ORDER_INFO.getType(), shoppingCartInfo.getUserId(), String.valueOf(shoppingCartInfo.getCartId()));
				}
			} else {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			}
		}

		//影像图库
		if (OrderTypeEnum.IMAGE_STORAGE.getType().equals(orderInfoDto.getType())) {
			ImageImgStorage imageImgStorage = imageImgStorageBiz.selectById(orderInfoDto.getDetailId());
			if (imageImgStorage != null) {
				ShoppingCartInfo old = selectByUser(appUserDTO.getUserid(), Long.valueOf(imageImgStorage.getId()));
				if (old != null) {
					return ObjectRestResponse.succ();
					//return ObjectRestResponse.createFailedResult(ResultCode.ORDER_GOODS_EXIST, ResultCode.getMsg(ResultCode.ORDER_GOODS_EXIST));
				} else {
					ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
					shoppingCartInfo.setDetailId(Long.valueOf(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);
					//添加通知信息
					noticeInfoBiz.addObj("商品" + shoppingCartInfo.getName() + "已添加购物车", NoticeTypeEnum.ORDER_INFO.getType(), shoppingCartInfo.getUserId(), String.valueOf(shoppingCartInfo.getCartId()));

				}
			} 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 old = selectByUser(appUserDTO.getUserid(), Long.valueOf(industryApplicationInfo.getId()));
				if (old != null) {
					return ObjectRestResponse.succ();
					//return ObjectRestResponse.createFailedResult(ResultCode.ORDER_GOODS_EXIST, ResultCode.getMsg(ResultCode.ORDER_GOODS_EXIST));
				} else {
					ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
					shoppingCartInfo.setDetailId(Long.valueOf(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);
					//添加通知信息
					noticeInfoBiz.addObj("商品" + shoppingCartInfo.getName() + "已添加购物车", NoticeTypeEnum.ORDER_INFO.getType(), shoppingCartInfo.getUserId(), String.valueOf(shoppingCartInfo.getCartId()));

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

		return ObjectRestResponse.succ();
	}

	public ShoppingCartInfo selectByUser(Integer userId, Long detailId) {
		Example example = new Example(ShoppingCartInfo.class);
		example.createCriteria().andEqualTo("detailId", detailId).andEqualTo("userId", userId);
		return mapper.selectOneByExample(example);
	}

	/**
	 * 购物车转为订单
	 *
	 * @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.stream().mapToDouble(shoppingCartInfo -> shoppingCartInfo.getTotalAmount().doubleValue()).sum();
		//总数量
		Integer totalNumber = cartInfoList.stream().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.stream().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);
	}

	/**
	 * 删除购物车
	 *
	 * @param id
	 * @return
	 */
	public ObjectRestResponse deleteOne(Integer id) {
		if (id == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		ShoppingCartInfo shoppingCartInfo = selectById(id);
		if (shoppingCartInfo == null || shoppingCartInfo.getIsDel() == 1) {
			return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
		}
		shoppingCartInfo.setIsDel(1);
		updateSelectiveByIdRe(shoppingCartInfo);
		return ObjectRestResponse.succ();
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	public ObjectRestResponse deleteBatch(String ids) {
		if (StringUtils.isBlank(ids)) {
			return ObjectRestResponse.paramIsEmpty();
		}
		String[] idArr = ids.split(",");
		if (idArr == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		for (String id : idArr) {
			if (StringUtils.isNotBlank(id)) {
				deleteOne(Integer.parseInt(id));
			}
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 根据ID List 查询所有购物车信息
	 * @param idList
	 * @return
	 */
	public List<ShoppingCartInfo> getAllByIds(Set<Integer> idList) {
		Example example = new Example(ShoppingCartInfo.class);
		example.createCriteria().andIn("id", idList);
		return mapper.selectByExample(example);
	}

}