package com.xxfc.platform.activity.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.xxfc.platform.activity.entity.TicketCollectionRecord;
import com.xxfc.platform.activity.mapper.TicketCollectionRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

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

@Service
@Slf4j
public class TicketCollectionRecordBiz extends BaseBiz<TicketCollectionRecordMapper, TicketCollectionRecord> {


	@Autowired
	UserFeign userFeign;

	@Autowired
	HttpServletRequest request;

	public ObjectRestResponse<List<TicketCollectionRecord>> selectAllByType(Integer type) {
		Integer newType = type == null ? 1 : type;
		List<TicketCollectionRecord> list = mapper.selectAllByType(new TicketCollectionRecord() {{
				setType(newType);
			}});
		return ObjectRestResponse.succ(list);
	}

	public ObjectRestResponse add(TicketCollectionRecord ticketCollectionRecord) {
		if (ticketCollectionRecord == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		if (ticketCollectionRecord.getPhone() == null && request.getHeader("Authorization") != null) {
			AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
			if (appUserDTO != null) {
				ticketCollectionRecord.setPhone(appUserDTO.getUsername());
			}
		}
		if (ticketCollectionRecord.getType() == null){
			ticketCollectionRecord.setType(1);
		}
		TicketCollectionRecord oldValue = selectByPhoneAndType(ticketCollectionRecord.getPhone(), ticketCollectionRecord.getType());
		if (oldValue == null) {
			insertSelectiveRe(ticketCollectionRecord);
		} else {
			BeanUtil.copyProperties(ticketCollectionRecord, oldValue, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
			updateSelectiveByIdRe(oldValue);
		}
		return ObjectRestResponse.succ();
	}

	public TicketCollectionRecord selectByPhoneAndType(String phone, Integer type) {
		Example example = new Example(TicketCollectionRecord.class);
		example.createCriteria().andEqualTo("phone", phone).andEqualTo("type", type);
		return mapper.selectOneByExample(example);
	}
}
