package org.springblade.gateway.active_gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.gateway.active_gateway.service.ProductSearchService;
import org.springblade.sing.active.entity.ActiveProductRecord;
import org.springblade.sing.active.service.IActiveProductRecordService;
import org.springblade.sing.active.vo.ActiveProductRecordVO;
import org.springblade.sing.user.entity.LoginUser;
import org.springblade.sing.user.service.ILoginUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class ProductSearchServiceImpl implements ProductSearchService {

	@Autowired
	private IActiveProductRecordService activeProductRecordService;

	@Autowired
	private ILoginUserService loginUserService;

	@Override
	public List<ActiveProductRecordVO> search(String keyword,Long activeId) {

		List<ActiveProductRecordVO> list = new ArrayList<>();

		LambdaQueryWrapper<ActiveProductRecord> wrapper = new LambdaQueryWrapper<>();

		wrapper.eq(!StringUtil.isEmpty(activeId),ActiveProductRecord::getActiveId,activeId);

		//判断keyword的类型,手机号or编号or标题
		if (StringUtil.hasLength(keyword)){
			if (Pattern.matches("[1][35789]\\d{9}",keyword)){
				wrapper.eq(ActiveProductRecord::getPhone,keyword);
			}else if (keyword.length() < 11 && Pattern.matches("[0-9]*",keyword)){
				wrapper.eq(ActiveProductRecord::getProductNo,keyword);
			}else {
				wrapper.like(ActiveProductRecord::getTitle,keyword);
			}
		}

		//拼接wrapper,并且查出作品
		List<ActiveProductRecord> activeProductRecords = activeProductRecordService.list(wrapper);

		//遍历list
		for (ActiveProductRecord activeProductRecord : activeProductRecords) {
			ActiveProductRecordVO activeProductRecordVO = new ActiveProductRecordVO();

			//封装数据到VO
			BeanUtils.copyProperties(activeProductRecord,activeProductRecordVO);

			LoginUser loginUser = loginUserService.getOne(new LambdaQueryWrapper<LoginUser>().eq(LoginUser::getPhone,activeProductRecord.getPhone()));

			if (!StringUtil.isEmpty(loginUser)){
				activeProductRecordVO.setUsername(loginUser.getNickName());

				activeProductRecordVO.setUserImg(loginUser.getAvatar());
			}

			list.add(activeProductRecordVO);
		}

		return list;
	}
}
