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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GroupsRelationCustomerServiceFollowRecordMapper;
import com.cyksj.mapper.GroupsRelationExpiryRecordMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.corp.CorpUserMapper;
import com.cyksj.mapper.market.task.UserBindDetailMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.RenewFollowStatisticsView;
import com.cyksj.service.user.UserBackService;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/*
 *项目名: netflix
 *文件名: CmsGroupsRelationExpiryController
 *创建者: JavaZou
 *创建时间:2023/9/5 12:08
 */
@RestController
@RequestMapping("/manage/relation/track")
@RequiredArgsConstructor
public class CmsGroupsRelationExpiryController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserBackService userBackService;

	private final GroupsRelationExpiryRecordMapper groupsRelationExpiryRecordMapper;

	private final GroupsRelationCustomerServiceFollowRecordMapper relationCustomerServiceFollowRecordMapper;

	private final UserMapper userMapper;

	private final UserBindDetailMapper userBindDetailMapper;

	private final CorpUserMapper corpUserMapper;

	/**
	 * 到期用户 客服跟进续费列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<GroupsRelationExpiryRecord>> get(String showId) {
		long adminId = StpUtil.getLoginIdAsLong();
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (userBackService.isCustomer(adminId)) {
			builder.field(GroupsRelationExpiryRecord::getCustomerServiceId, adminId);
		}
		if (StrUtil.isNotBlank(showId)) {
			User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getShowId, showId).last("limit 1"));
			if (user != null) {
				builder.field(GroupsRelationExpiryRecord::getUserId, user.getId());
			}
		}
		SearchResult<GroupsRelationExpiryRecord> search = beanSearcher.search(GroupsRelationExpiryRecord.class, builder
				.field(GroupsRelationExpiryRecord::getIsFollow, false)
				.orderBy(GroupsRelationExpiryRecord::getAssignTime).desc()
				.orderBy(GroupsRelationExpiryRecord::getIsFollow).asc()
				.build());
		search.getDataList().forEach(data -> {
			if (Constant.TRACK_RENEW_TYPE.contains(data.getRegister())) {
				UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
						.eq(Constant.TRACK_RENEW_TYPE.get(0).equals(data.getRegister()), UserBindDetail::getEmailUserId, data.getUserId())
						.eq(Constant.TRACK_RENEW_TYPE.get(1).equals(data.getRegister()), UserBindDetail::getUserId, data.getUserId())
						.ne(UserBindDetail::getPhone, StrUtil.EMPTY)
						.last("limit 1"));
				if (userBindDetail != null) {
					data.setContact(userBindDetail.getPhone());
				}
				if (Constant.TRACK_RENEW_TYPE.get(1).equals(data.getRegister())) {
					//实时获取企业微信昵称
					Optional.ofNullable(corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class)
									.eq(CorpUser::getUserId, data.getUserId()).last("limit 1")))
							.ifPresent(cu -> {
								data.setCorpUserName(cu.getName());
								data.setCorpHeadImgUrl(cu.getAvatar());
							});
				}
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 跟进记录列表
	 */
	@GetMapping("/get/reBuy/record/{trackId}")
	public Result<SearchResult<GroupsRelationCustomerServiceFollowRecord>> getReBuyRecord(@PathVariable Long trackId) {
		SearchResult<GroupsRelationCustomerServiceFollowRecord> search = beanSearcher.search(GroupsRelationCustomerServiceFollowRecord.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(GroupsRelationCustomerServiceFollowRecord::getEcId, trackId)
				.orderBy(GroupsRelationCustomerServiceFollowRecord::getId).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 客服进行跟进
	 */
	@PostMapping("/reBuy")
	@Transactional(rollbackFor = Throwable.class)
	public Result<String> recordReBuy(@RequestBody GroupsRelationCustomerServiceFollowRecord record) {
		Long ecId = record.getEcId();
		if (ecId == null) {
			throw BusinessRuntimeException.getInstance("请选择对应的跟进车票");
		}
		GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordMapper.selectById(ecId);
		if (groupsRelationExpiryRecord == null) {
			throw BusinessRuntimeException.getInstance("请选择对应的跟进车票");
		}
		if (StrUtil.isAllBlank(record.getContent(), record.getImgs())) {
			throw BusinessRuntimeException.getInstance("请完善对应跟进信息");
		}
		relationCustomerServiceFollowRecordMapper.insert(record);
		groupsRelationExpiryRecord.setIsFollow(true);
		groupsRelationExpiryRecordMapper.updateById(groupsRelationExpiryRecord);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 跟进统计
	 */
	@GetMapping("/get/renewFollow/statistics")
	public Result<List<RenewFollowStatisticsView>> getRenewFollowStatisticsData(String startTime, String endTime) {
		MapBuilder builder = MapUtils.builder();
		String timeSql = StrUtil.EMPTY;
		if (StrUtil.isNotEmpty(startTime)) {
			timeSql += String.format("assign_time >= '%s'", startTime);
		}
		if (StrUtil.isNotEmpty(endTime)) {
			if (StrUtil.isNotEmpty(timeSql)) {
				timeSql += " and ";
			}
			timeSql += String.format("assign_time < '%s'", endTime);
		}
		List<RenewFollowStatisticsView> renewFollowStatisticsViews = beanSearcher.searchAll(RenewFollowStatisticsView.class, builder
				.put("time", timeSql)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(renewFollowStatisticsViews);
	}

}
