package com.cyksj.web.controller.manage.mirrorshop.manage;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.MirrorNoticeMapper;
import com.cyksj.mapper.mirrorshop.MirrorNoticeUserMapper;
import com.cyksj.mapper.mirrorshop.MirrorNoticeUserReviewRecordMapper;
import com.cyksj.model.entity.MirrorNotice;
import com.cyksj.model.entity.MirrorNoticeUser;
import com.cyksj.model.entity.MirrorNoticeUserReviewRecord;
import com.cyksj.model.request.BatchIdsReq;
import com.cyksj.service.mange.RefreshCacheService;
import com.cyksj.web.util.StpUserMirrorShopManageUser;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * admin/镜像店铺后台/公告
 * 项目名: yhlxj2
 * 文件名: CmsUserMirrorAdvertiseController
 * 创建者: JavaZou
 * 创建时间:2024/11/7 12:04
 */
@RestController
@RequestMapping("/mirrorShop/manage/notice")
@RequiredArgsConstructor
public class CmsUserMirrorNoticeController {

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final MirrorNoticeUserMapper noticeUserMapper;

	private final RefreshCacheService refreshCacheService;

	private final MirrorNoticeMapper mirrorNoticeMapper;

	private final MirrorNoticeUserReviewRecordMapper mirrorNoticeUserReviewRecordMapper;

	/**
	 * 店铺公告列表
	 */
	@GetMapping("/get")
	public Result<SearchResult> get(@RequestParam(defaultValue = "1") Boolean self) {
		long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (self) {
			SearchResult<MirrorNoticeUser> search = beanSearcher.search(MirrorNoticeUser.class, builder.field(MirrorNoticeUser::getUserId, userId).orderBy(MirrorNoticeUser::getUpdateTime).desc().build());
			return GatewayResponse.SUCCESS.newBuilder().toResult(search);
		}
		builder.put("ruid", String.format(" and myr.user_id = %s", userId));
		SearchResult<MirrorNotice> search = beanSearcher.search(MirrorNotice.class, builder.orderBy(MirrorNotice::getUpdateTime).desc().build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}


	/**
	 * 新增店铺公告
	 */
	@PostMapping("/post")
	public Result<String> post(@RequestBody MirrorNoticeUser notice) {
		long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		notice.setUserId(userId);
		noticeUserMapper.insert(notice);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 编辑店铺公告
	 */
	@PutMapping("/update")
	public Result<String> update(@RequestBody MirrorNoticeUser notice) {
		Long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		MirrorNoticeUser byId = noticeUserMapper.selectById(notice.getId());
		if (byId == null || !ObjectUtil.equal(userId, byId.getUserId())) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		noticeUserMapper.updateById(notice);
		refreshCacheService.refreshUserMirrorShopAdvertiseCache(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 上下架店铺公告
	 */
	@PutMapping("/update/status/{id}")
	public Result<String> updateStatusById(@PathVariable Long id) {
		Long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		Optional.ofNullable(noticeUserMapper.selectById(id))
				.ifPresent(en -> {
					en.setStatus(!en.getStatus());
					noticeUserMapper.updateById(en);
					refreshCacheService.refreshUserMirrorShopAdvertiseCache(userId);
				});
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除店铺公告
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteById(@PathVariable Long id) {
		Long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		noticeUserMapper.delete(Wrappers.lambdaQuery(MirrorNoticeUser.class)
				.eq(MirrorNoticeUser::getId, id)
				.eq(MirrorNoticeUser::getUserId, userId));
		refreshCacheService.refreshUserMirrorShopAdvertiseCache(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 标记公告已读
	 */
	@PostMapping("/mark/{id}")
	public Result<String> markNotice(@PathVariable Long id) {
		Long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		MirrorNoticeUserReviewRecord mirrorNoticeUserReviewRecord = Optional.ofNullable(mirrorNoticeUserReviewRecordMapper.selectOne(Wrappers.lambdaQuery(MirrorNoticeUserReviewRecord.class)
				.eq(MirrorNoticeUserReviewRecord::getNoticeId, id)
				.eq(MirrorNoticeUserReviewRecord::getUserId, userId)
				.last("limit 1"))).orElse(new MirrorNoticeUserReviewRecord());

		try {
			if (mirrorNoticeUserReviewRecord.getId() == null) {
				mirrorNoticeUserReviewRecord.setNoticeId(id);
				mirrorNoticeUserReviewRecord.setUserId(userId);
				mirrorNoticeUserReviewRecordMapper.insert(mirrorNoticeUserReviewRecord);
			}
		} catch (DuplicateKeyException e) {

		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 批量同步银河后台公告
	 */
	@PostMapping("/sync/background/notice")
	public Result<String> syncBackgroundNotice(@RequestBody @Validated BatchIdsReq batchIdsReq) {
		Long userId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		mirrorNoticeMapper.selectBatchIds(batchIdsReq.getIds()).forEach(backNotice -> {
			MirrorNoticeUser mirrorNoticeUser = noticeUserMapper.selectOne(Wrappers.lambdaQuery(MirrorNoticeUser.class)
					.eq(MirrorNoticeUser::getNoticeId, backNotice.getId())
					.eq(MirrorNoticeUser::getUserId, userId)
					.last("limit 1"));
			if (mirrorNoticeUser == null) {
				try {
					mirrorNoticeUser = new MirrorNoticeUser();
					mirrorNoticeUser.setNoticeId(backNotice.getId());
					mirrorNoticeUser.setPlatform(backNotice.getPlatform());
					mirrorNoticeUser.setTitle(backNotice.getTitle());
					mirrorNoticeUser.setText(backNotice.getText());
					mirrorNoticeUser.setUserId(userId);
					noticeUserMapper.insert(mirrorNoticeUser);

					MirrorNoticeUserReviewRecord mirrorNoticeUserReviewRecord = new MirrorNoticeUserReviewRecord();
					mirrorNoticeUserReviewRecord.setNoticeId(backNotice.getId());
					mirrorNoticeUserReviewRecord.setUserId(userId);
					mirrorNoticeUserReviewRecordMapper.insert(mirrorNoticeUserReviewRecord);
				} catch (DuplicateKeyException e) {

				}
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}
