package com.cyksj.web.controller.sys;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.util.Jsons;
import com.cyksj.config.corp.YHLXWxCorpConfig;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.SysCorpFollowRelateMapper;
import com.cyksj.mapper.corp.CorpUserFollowRelationMapper;
import com.cyksj.mapper.corp.kf.CorpKfAccountFollowMapper;
import com.cyksj.model.entity.CorpKfAccountFollow;
import com.cyksj.model.entity.SysCorpFollow;
import com.cyksj.model.request.sys.SysCorpFollowReq;
import com.cyksj.model.views.CorpKfAccountChildView;
import com.cyksj.model.views.CorpKfTransUserView;
import com.cyksj.model.views.SysCorpFollowView;
import com.cyksj.model.views.SysCorpMasterFollowView;
import com.cyksj.service.corp.CorpService;
import com.cyksj.service.corp.WxCorpOps;
import com.cyksj.service.corp.kf.CorpKfService;
import com.cyksj.service.sys.SysCorpFollowService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 项目名: yhlxj
 * 文件名: SysCorpFollowController
 * 创建者: JavaZou
 * 创建时间:2024/6/12 11:54
 * 系统客服配置
 */
@Slf4j
@RequestMapping("/sys/corp/follow")
@RestController
@RequiredArgsConstructor
public class SysCorpFollowController {
	private final SysCorpFollowService sysCorpFollowService;

	private final BeanSearcher beanSearcher;

	private final YHLXWxCorpConfig yhlxWxCorpConfig;

	private final CorpService corpService;

	private final CorpUserFollowRelationMapper corpUserFollowRelationMapper;

	private final HttpServletRequest request;

	private final WxCorpOps wxCorpOps;

	private final YHLXWxCorpConfig corpConfig;

	private final CorpKfService corpKfService;

	private final SysCorpFollowRelateMapper sysCorpFollowRelateMapper;

	private final CorpKfAccountFollowMapper corpKfAccountFollowMapper;

	/**
	 * 新增客服
	 */
	@PostMapping("/post")
	public Result<String> post(@RequestBody SysCorpFollowReq req) throws Exception {
		sysCorpFollowService.saveOrUpdateFollow(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除客服
	 */
	@DeleteMapping("/del/{sid}")
	public Result<String> delBySId(@PathVariable Long sid) throws Exception {
		sysCorpFollowService.delBySid(sid);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 修改客服
	 */
	@PutMapping("/put")
	public Result<String> update(@RequestBody SysCorpFollowReq req) throws Exception {
		sysCorpFollowService.saveOrUpdateFollow(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 客服列表
	 */
	@GetMapping("/get")
	public Result<List<SysCorpFollowView>> get(@RequestParam(required = false) Boolean isOpen) throws Exception {
		List<String> res = wxCorpOps.getPermitUserList(corpConfig.getCorpId(), null);
		List<SysCorpFollowView> sysCorpFollowViews = beanSearcher.searchAll(SysCorpFollowView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		sysCorpFollowViews.forEach(e -> {
			Integer num = corpUserFollowRelationMapper.selectNumOfCorpuserByFollowId(e.getFollowId());
			e.setNumOfCorpUser(num);
			//是否开启企业会话
			if (CollUtil.isNotEmpty(res) && res.contains(e.getFollowId())) {
				e.setIsOpen(true);
			}
		});
		if (isOpen != null) {
			sysCorpFollowViews = sysCorpFollowViews.stream().filter(e -> e.getIsOpen() == isOpen).collect(Collectors.toList());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(sysCorpFollowViews);
	}

	/**
	 * 主客服列表
	 */
	@GetMapping("/get/master")
	public Result<List<SysCorpMasterFollowView>> getMasterFollow() {
		List<SysCorpMasterFollowView> sysCorpMasterFollowViews = beanSearcher.searchAll(SysCorpMasterFollowView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(sysCorpMasterFollowViews);
	}

	/**
	 * 同步企业客服
	 */
	@GetMapping("/dataInit")
	public Result<String> dataInitByCorpId(String corpId) throws Exception {
		corpId = Optional.ofNullable(corpId).orElse(yhlxWxCorpConfig.getCorpId());
		return GatewayResponse.SUCCESS.newBuilder().toResult(corpService.dataInitByCorpId(corpId));
	}

	/**
	 * 客服绑定登录账号
	 */
	@PutMapping("/bind/loginAccount")
	public Result<String> bindLoginAccount(@RequestBody SysCorpFollow sysCorpFollow) {
		sysCorpFollowService.bindLoginAccount(sysCorpFollow);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 转接客户
	 */
	@PostMapping("/tans/customer")
	public Result<String> transCustomer(@RequestBody SysCorpFollowReq req) throws Exception {
		String followId = req.getFollowId();
		String toFollowId = req.getToFollowId();
		corpKfService.transCustomer(followId, toFollowId, req.getTransNum(), req.getTransUserIds(), req.getOpenKfId());
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 转接客户列表
	 */
	@GetMapping("/get/trans/users")
	public Result<SearchResult<CorpKfTransUserView>> getTransUsers() {
		SearchResult<CorpKfTransUserView> search = beanSearcher.search(CorpKfTransUserView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 客服账号级联
	 */
	@GetMapping("/get/corp/kf/account/users")
	public Result<List<CorpKfAccountChildView>> getCorpKfAccountUsers() throws Exception {
		List<CorpKfAccountChildView> corpKfAccountChildViews = beanSearcher.searchAll(CorpKfAccountChildView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		for (CorpKfAccountChildView data : corpKfAccountChildViews) {
			List<CorpKfAccountFollow> corpKfAccountFollows = corpKfAccountFollowMapper.selectList(Wrappers.lambdaQuery(CorpKfAccountFollow.class)
					.eq(CorpKfAccountFollow::getOpenKfId, data.getOpenKfId()));
			Set<String> followIds = new HashSet<>();
			for (CorpKfAccountFollow corpKfAccountFollow : corpKfAccountFollows) {
				followIds.addAll(Jsons.parseList(corpKfAccountFollow.getUserIdList(), String.class));
			}
			List<CorpKfAccountChildView.CorpKfFollowView> corpKfFollowViews = beanSearcher.searchAll(CorpKfAccountChildView.CorpKfFollowView.class, MapUtils.builder()
					.field(CorpKfAccountChildView.CorpKfFollowView::getFollowId, followIds).op(Operator.InList)
					.build());
			data.setChild(corpKfFollowViews);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(corpKfAccountChildViews);
	}
}
