package com.upyuns.platform.rs.website.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.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.website.dto.UserAddressDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiaoruizhen
 * @email jiaoruizhen@126.com
 * @date 2020-11-28 14:15:32
 */
@Service
public class UserAddressBiz extends BaseBiz<UserAddressMapper, UserAddress> {

	@Autowired
	UserFeign userFeign;

	@Autowired
	HttpServletRequest request;

	/**
	 * 分页查询 用户地址信息
	 * @param userAddressDto
	 * @return
	 */
	public ObjectRestResponse<PageDataVO<UserAddress>> selectList(UserAddressDto userAddressDto) {
		Example example = new Example(UserAddress.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(userAddressDto.getName())) {
			criteria.andLike("consigneeName", "%" + userAddressDto.getName() + "%");
		}
		if (StringUtils.isNotBlank(userAddressDto.getPhone())) {
			criteria.andLike("consigneePhone", "%" + userAddressDto.getPhone() + "%");
		}
		if (userAddressDto.getUserId() != null) {
			criteria.andEqualTo("userId", userAddressDto.getUserId());
		}
		criteria.andEqualTo("isDel", 0);
		example.orderBy("updTime").desc();
		Query query = new Query(userAddressDto);
		PageDataVO<UserAddress> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
		return ObjectRestResponse.succ(pageDataVO);
	}

	/**
	 * 新增用户地址
	 * @param userAddress
	 * @return
	 */
	public ObjectRestResponse addUpdate(UserAddress userAddress) {
		AppUserDTO appUserVo = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
		if (appUserVo == null) {
			return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
		}
		if (userAddress == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		if (userAddress.getId() != null) {
			UserAddress old = selectById(userAddress.getId());
			if (old != null && old.getIsDel() != 1) {
				BeanUtil.copyProperties(userAddress, old, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
				updateSelectiveByIdRe(old);
			} else {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			}
		} else {
			insertSelectiveRe(userAddress);
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 查询用户所有收货地址
	 *
	 * @return
	 */
	public List<UserAddress> getUserAddress() {
		AppUserDTO appUserVo = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
		if (appUserVo == null) {
			return new ArrayList<>();
		}
		Example example = new Example(UserAddress.class);
		example.createCriteria().andEqualTo("userId", appUserVo.getUserid()).andEqualTo("isDel", 0);
		example.orderBy("isDefault").desc();
		return mapper.selectByExample(example);
	}


	/**
	 * 设置地址为默认值
	 * @param id
	 * @return
	 */
	public ObjectRestResponse setDefault(Integer id) {
		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 (id == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		UserAddress userAddress = selectById(id);
		if (userAddress == null || userAddress.getIsDel() == 1) {
			return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
		}
		generateDefault(appUserDTO.getUserid());

		userAddress.setIsDefault(1);
		updateSelectiveByIdRe(userAddress);
		return ObjectRestResponse.succ();
	}


	private void generateDefault(Integer userId) {
		Example example = new Example(UserAddress.class);
		example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0).andEqualTo("isDefault", 1);
		List<UserAddress> list = mapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			list.parallelStream().forEach(userAddress -> {
				userAddress.setIsDefault(0);
				updateSelectiveByIdRe(userAddress);
			});
		}
	}
}