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.UserInvoiceDto;
import com.upyuns.platform.rs.website.entity.OrderEInvoice;
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.UserInvoice;
import com.upyuns.platform.rs.website.mapper.UserInvoiceMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;

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

/**
 * 用户发票信息
 *
 * @author jiaoruizhen
 * @email jiaoruizhen@126.com
 * @date 2020-12-03 13:29:23
 */
@Service
public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {

	@Autowired
	UserFeign userFeign;
	@Autowired
	HttpServletRequest request;
	/**
	 * 添加用户发票
	 * @param userInvoice
	 * @return
	 */
	public ObjectRestResponse addUpdate(UserInvoice userInvoice) {
		if (userInvoice == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		if (userInvoice.getId() == null) {
			UserInvoice old = getOneByTax(userInvoice.getTaxCode(), userInvoice.getUserId());
			if (old != null) {
				userInvoice.setId(old.getId());
				updateData(userInvoice);
			} else {
				insertSelectiveRe(userInvoice);
			}
		} else {
			updateData(userInvoice);
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 添加用户发票
	 * @param userInvoice
	 * @return
	 */
	public ObjectRestResponse userAddUpdate(UserInvoice userInvoice) {
		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 (userInvoice == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		userInvoice.setUserId(appUserDTO.getUserid());
		if (userInvoice.getId() == null) {
			UserInvoice old = getOneByTax(userInvoice.getTaxCode(), userInvoice.getUserId());
			if (old != null && StringUtils.isNotBlank(userInvoice.getTaxCode())) {
				userInvoice.setId(old.getId());
				updateData(userInvoice);
			} else {
				insertSelectiveRe(userInvoice);
			}
		} else {
			updateData(userInvoice);
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 查询发票信息
	 * @param tax
	 * @param userId
	 * @return
	 */
	public UserInvoice getOneByTax(String tax, Integer userId) {
		Example example = new Example(UserInvoice.class);
		example.createCriteria().andEqualTo("taxCode", tax).andEqualTo("userId", userId).andEqualTo("isDel", 0);
		return mapper.selectOneByExample(example);
	}

	/**
	 * 分页查询用户发票信息
	 * @param userInvoiceDto
	 * @return
	 */
	public ObjectRestResponse<PageDataVO<UserInvoice>> getList(UserInvoiceDto userInvoiceDto) {
		Example example = new Example(UserInvoice.class);
		Example.Criteria criteria = example.createCriteria();
		if (userInvoiceDto.getUserId() != null) {
			criteria.andEqualTo("userId", userInvoiceDto.getUserId());
		}
		if (userInvoiceDto.getTitleType() != null) {
			criteria.andEqualTo("titleType", userInvoiceDto.getTitleType());
		}
		if (StringUtils.isNotBlank(userInvoiceDto.getTitleName())) {
			criteria.andEqualTo("titleName", "%" + userInvoiceDto.getTitleName() + "%");
		}
		if (StringUtils.isNotBlank(userInvoiceDto.getTaxCode())) {
			criteria.andEqualTo("taxCode", "%" + userInvoiceDto.getTaxCode() + "%");
		}
		criteria.andEqualTo("isDel", 0);
		example.orderBy("isDefault").desc();
		Query query = new Query(userInvoiceDto);
		PageDataVO<UserInvoice> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
		return ObjectRestResponse.succ(pageDataVO);
	}

	/**
	 * 查询用户所有发票信息
	 * @param userInvoiceDto
	 * @return
	 */
	public ObjectRestResponse<PageDataVO<UserInvoice>> getUserInvoiceInfo(UserInvoiceDto userInvoiceDto) {
		AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
		if (appUserDTO == null) {
			return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
		}
		userInvoiceDto.setUserId(appUserDTO.getUserid());
		return getList(userInvoiceDto);
	}

	/**
	 * 更新发票信息
	 * @param userInvoice
	 * @return
	 */
	public ObjectRestResponse updateData(UserInvoice userInvoice) {
		UserInvoice old = selectById(userInvoice.getId());
		BeanUtil.copyProperties(userInvoice, old, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
		updateSelectiveByIdRe(old);
		return ObjectRestResponse.succ();
	}

	/**
	 * 设置发票为默认值
	 * @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();
		}
		UserInvoice userInvoice = selectById(id);
		if (userInvoice == null || userInvoice.getIsDel() == 1) {
			return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
		}
		generateDefault(appUserDTO.getUserid());

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


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

}