package com.cyksj.web.controller.manage.corp.wxkf;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.corp.kf.CorpKfUserMapper;
import com.cyksj.model.entity.CorpKfUser;
import com.cyksj.model.kf.CorpKfUserInfo;
import com.cyksj.model.request.CorpKfUserMarkReq;
import com.cyksj.model.views.CustomerConsultationRecordView;
import com.cyksj.service.corp.WxCorpOps;
import com.cyksj.service.user.UserBindRelationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

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

/**
 * admin/企业微信/微信客服
 * 项目名: yhlxj2
 * 文件名: CorpKfUserController
 * 创建者: JavaZou
 * 创建时间:2025/1/15 18:27
 */
@RestController
@RequestMapping("/manage/corp/kf/user")
@RequiredArgsConstructor
public class CorpKfUserController {
	private final CorpKfUserMapper corpKfUserMapper;

	private final WxCorpOps wxCorpOps;

	private final UserBindRelationService userBindRelationService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	/**
	 * 微信客户详情
	 */
	@GetMapping("/get/detail")
	public Result<CorpKfUser> getCorpKfUserInfo(String externalUserid) throws Exception {
		CorpKfUser user = getCorpUser(externalUserid);
		return GatewayResponse.SUCCESS.newBuilder().toResult(user);
	}

	/**
	 * 设置备注
	 */
	@PostMapping("/set/remark")
	public Result<String> setUserRemark(@RequestBody CorpKfUser corpKfUser) throws Exception {
		CorpKfUser user = getCorpUser(corpKfUser.getExternalUserid());
		user.setRemark(corpKfUser.getRemark());
		corpKfUserMapper.updateById(user);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 标记为设备用户
	 */
	@PostMapping("/mark/device")
	public Result<String> markUserDevice(@RequestBody CorpKfUserMarkReq corpKfUserMarkReq) throws Exception {
		String externalUserid = corpKfUserMarkReq.getExternalUserid();
		String followId = corpKfUserMarkReq.getFollowId();
		CorpKfUser user = getCorpUser(externalUserid);
		if (user.getIsDevice()) {
			user.setFollowId(null);
		} else {
			user.setFollowId(followId);
		}
		user.setIsDevice(!user.getIsDevice());
		corpKfUserMapper.updateById(user);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 用户当日咨询问题列表
	 */
	@GetMapping("/get/consultation/questions")
	public Result<List<CustomerConsultationRecordView>> getUserConsultationQuestions(Long userId) throws Exception {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		List<CustomerConsultationRecordView> customerConsultationRecords = beanSearcher.searchAll(CustomerConsultationRecordView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(CustomerConsultationRecordView::getUserId, userIdList).op(Operator.InList)
				.field(CustomerConsultationRecordView::getCreatedTime, DateUtil.beginOfDay(DateTime.now()), DateUtil.endOfDay(DateTime.now())).op(Operator.Between)
				.orderBy(CustomerConsultationRecordView::getId).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(customerConsultationRecords);
	}

	public CorpKfUser getCorpUser(String externalUserid) throws Exception {
		CorpKfUser corpKfUser = corpKfUserMapper.selectOne(Wrappers.lambdaQuery(CorpKfUser.class)
				.eq(CorpKfUser::getExternalUserid, externalUserid)
				.last("limit 1"));
		if (corpKfUser == null) {
			CorpKfUserInfo corpKfUserInfo = wxCorpOps.getCorpKfUserInfo(externalUserid);
			try {
				corpKfUser = new CorpKfUser();
				BeanUtil.copyProperties(corpKfUserInfo, corpKfUser);
				corpKfUserMapper.insert(corpKfUser);
			} catch (DuplicateKeyException e) {
			}
		}
		return corpKfUser;
	}
}
