package com.tourism.webadmin.app.website.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyOrderParam;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.webadmin.app.website.dto.PageDto;
import com.tourism.webadmin.app.website.dto.TourTourismProjectSearchRecordsDto;
import com.tourism.webadmin.app.website.service.TourismProjectSearchRecordsService;
import com.tourism.webadmin.app.website.vo.TourismProjectSearchRecordsVo;
import com.tourism.webadmin.back.model.TourTourismProjectSearchRecords;
import com.tourism.webadmin.back.service.TourTourismProjectSearchRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * 游记列表搜索Service
 */
@Slf4j
@SuppressWarnings("all")
@Service("tourismProjectSearchRecordsService")
public class TourismProjectSearchRecordsServiceImpl implements TourismProjectSearchRecordsService {

	@Autowired
	private TourTourismProjectSearchRecordsService tourismProjectSearchRecordsService;

	/**
	 * 用过游记搜索记录id删除记录
	 * @param idString 搜索记录id
	 * @return 结果
	 */
	@Override
	public ResponseResult<Void> removeProjectSearchRecordsById(String idString) {
		//为空返回
		if (MyCommonUtil.isBlankOrNull(idString)) {
			return ResponseResult.error(ErrorCodeEnum.ARGUMENT_PK_ID_NULL);
		}
		//获取id
		JSONObject jsonObject = JSON.parseObject(idString);
		Object rawId = jsonObject.get("id");
		if (MyCommonUtil.isBlankOrNull(rawId)) {
			return ResponseResult.error(ErrorCodeEnum.ARGUMENT_PK_ID_NULL);
		}
		String id = (String) rawId;
		//获取搜索记录
		TourTourismProjectSearchRecords searchRecordsServiceById = tourismProjectSearchRecordsService.getById(id);
		String errorMessage;
		//校验数据合法性
		if (Objects.isNull(searchRecordsServiceById)){
			errorMessage = "数据操作失败，删除的记录不存在，请刷新后重试！";
			return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
		}
		//判断是否为自己的记录
		Long userId = TokenData.takeFromRequest().getUserId();
		if (!searchRecordsServiceById.getCreateUserId().equals(userId)){
			errorMessage = "数据操作失败，不允许删除当前记录，请刷新后重试！";
			return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
		}
		if (!tourismProjectSearchRecordsService.remove(Long.valueOf(id))){
			errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
			return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
		}
		return ResponseResult.success();
	}

	/**
	 * 清空游记历史搜索记录
	 * @return 结果
	 */
	@Override
	public ResponseResult<Void> clearProjectSearchRecords(String searchType) {
		if (MyCommonUtil.isBlankOrNull(searchType)){
			return ResponseResult.error(ErrorCodeEnum.TOUR_ORDER_USER_ERROR,"参数错误");
		}
		//获取用户登录id
		Long userId = TokenData.takeFromRequest().getUserId();
		//获取类型
		JSONObject searchJSONObject = JSON.parseObject(searchType);
		Integer type;
		try {
			type = Integer.valueOf(searchJSONObject.get("searchType").toString());
		}catch (Exception e){
			return ResponseResult.error(ErrorCodeEnum.TOUR_ORDER_USER_ERROR,"参数类型错误");
		}

		//通过用户id进行清空
		boolean remove = tourismProjectSearchRecordsService
				.remove(new LambdaQueryWrapper<TourTourismProjectSearchRecords>()
						.eq(TourTourismProjectSearchRecords::getSearchType,type)
						.eq(TourTourismProjectSearchRecords::getCreateUserId, userId));
		return remove?ResponseResult.success():ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
	}

	/**
	 * 获取游记搜索记录列表
	 * @param pageDto 参数DTO对象
	 * @return 结果
	 */
	@Override
	public ResponseResult<MyPageData<TourismProjectSearchRecordsVo>> getSearchRecordList(TourTourismProjectSearchRecordsDto tourTourismProjectSearchRecordsDto) {
		//获取登入用户id
		Long userId = TokenData.takeFromRequest().getUserId();
		//分页参数
		Integer pageSize = tourTourismProjectSearchRecordsDto.getPageSize();
		Integer pageNum = tourTourismProjectSearchRecordsDto.getPageNum();
		if (pageNum == null){
			pageNum = 1;
		}
		if (pageSize == null){
			pageSize = 20;
		}

		//分页查询
		PageMethod.startPage(pageNum, pageSize);

		//构建查询排序条件
		MyOrderParam myOrderParam = new MyOrderParam();
		//默认降序
		MyOrderParam.OrderInfo orderInfo = new MyOrderParam.OrderInfo("searchTime",false,null);
		myOrderParam.add(orderInfo);
		//排序参数
		String orderBy = myOrderParam.buildOrderBy(myOrderParam, TourTourismProjectSearchRecords.class);
		//构建过滤条件
		TourTourismProjectSearchRecords searchRecordFilter = new TourTourismProjectSearchRecords();
		searchRecordFilter.setCreateUserId(userId);
		searchRecordFilter.setSearchType(tourTourismProjectSearchRecordsDto.getSearchType());
		//得到结果集
		List<TourTourismProjectSearchRecords> tourTourismSearchRecordsList = tourismProjectSearchRecordsService.getTourTourismSearchRecordsList(searchRecordFilter, orderBy);
		//获取历史搜索总数
		long count = tourismProjectSearchRecordsService.getCountByFilter(searchRecordFilter);
		//将结果集复制到VO对象
		List<TourismProjectSearchRecordsVo> searchRecordsVos = MyModelUtil.copyCollectionTo(tourTourismSearchRecordsList, TourismProjectSearchRecordsVo.class);
		//封装为分页对象
		MyPageData<TourismProjectSearchRecordsVo> projectSearchRecordsVoMyPageData = MyPageUtil.makeResponseData(searchRecordsVos);
		projectSearchRecordsVoMyPageData.setTotalCount(count);
		return ResponseResult.success(projectSearchRecordsVoMyPageData);
	}
}
