package com.cyksj.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.enums.GatewayApiCode;
import com.cyksj.mapper.AccountMapper;
import com.cyksj.mapper.manage.sys.WorkOrderChatHistoryMapper;
import com.cyksj.mapper.manage.sys.WorkOrderMapper;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.WorkOrder;
import com.cyksj.model.entity.WorkOrderChatHistory;
import com.cyksj.model.request.WorkOrderReq;
import com.cyksj.model.views.CmsUserVO;
import com.cyksj.model.views.GroupRelationDetailView;
import com.cyksj.service.shop.YhShopFrontService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.service.user.UserService;
import com.cyksj.service.user.WorkOrderFrontService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/*
 *项目名: netflix
 *文件名: WorkOrderFrontServiceImpl
 *创建者: JavaZou
 *创建时间:2023/4/20 13:43
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WorkOrderFrontServiceImpl implements WorkOrderFrontService {
	private final WorkOrderMapper workOrderMapper;

	private final WorkOrderChatHistoryMapper historyMapper;

	private final BeanSearcher beanSearcher;

	private final UserService userService;

	private final AccountMapper accountMapper;

	private final UserBindRelationService userBindRelationService;

	private final YhShopFrontService yhShopFrontService;

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void submitWorkOrder(WorkOrderReq workOrderReq) {
		Long userId = workOrderReq.getUserId();
		Long relationId = workOrderReq.getRelationId();
		//是否已提交过该工单
		WorkOrder exists = workOrderMapper.selectOne(Wrappers.lambdaQuery(WorkOrder.class)
				.eq(WorkOrder::getRelationId, relationId)
				.eq(WorkOrder::getUserId, userId)
				.last("limit 1"));
		if (exists != null) {
			throw BusinessRuntimeException.getInstance("您已提交过该车票工单");
		}
		User user = userService.getById(userId);
		if (user == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
		String content = workOrderReq.getContent();
		String imgs = workOrderReq.getImgs();
		String topic = workOrderReq.getTopic();
		if (StrUtil.isNotBlank(topic) && topic.length() > 32) {
			throw BusinessRuntimeException.getInstance("标题最多输入30字数以内");
		}
		if (StrUtil.isNotBlank(content) && content.length() > 200) {
			throw BusinessRuntimeException.getInstance("问题描述最多输入200字数以内");
		}
		if (StrUtil.isNotBlank(imgs) && imgs.length() > 2000) {
			throw BusinessRuntimeException.getInstance("图片过多");
		}
		List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
		GroupRelationDetailView detailView = beanSearcher.searchFirst(GroupRelationDetailView.class, MapUtils.builder()
				.field(GroupRelationDetailView::getUserId, userIds).op(Operator.InList)
				.field(GroupRelationDetailView::getRelationId, relationId)
				.build());
		if (detailView == null) throw BusinessRuntimeException.getInstance("车票不存在");

		WorkOrder workOrder = new WorkOrder();
		BeanUtil.copyProperties(workOrderReq, workOrder);
		workOrder.setGoodsId(detailView.getGoodsId());
		workOrder.setSkuId(detailView.getSkuId());
		Optional.ofNullable(accountMapper.selectById(detailView.getAccountId()))
				.ifPresent(account -> {
					workOrder.setAccountId(detailView.getAccountId());
					workOrder.setAccount(account.getAccount());
				});
		//随机分配给客服
		List<CmsUserVO> customers = beanSearcher.searchAll(CmsUserVO.class, MapUtils.builder()
				.field(CmsUserVO::getRoleNames, "客服").op(Operator.Contain)
				.field(CmsUserVO::getStatus, true)
				.build());
		if (customers.size() > 0) {
			int randomIndex = RandomUtil.randomInt(customers.size());
			CmsUserVO customer = customers.get(randomIndex);
			workOrder.setAssignCustomerServiceId(customer.getId());
			workOrder.setCustomerServiceAuthId(customer.getAuthId());
		}
		if (workOrder.getType() == WorkOrder.Type.other) {
			workOrder.setContent(workOrder.getContent());
		}
		if (StrUtil.isNotBlank(workOrderReq.getCustomId())) {
			Long yhsId = yhShopFrontService.getYhsIdByCustomId(workOrderReq.getCustomId());
			workOrder.setYhsId(yhsId);
		}
		workOrderMapper.insert(workOrder);
	}

	@Override
	public void replyCustomer(WorkOrderChatHistory history) {
		Long userId = history.getUserId();
		User user = userService.getById(userId);
		if (user == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
		Long workOrderId = history.getWorkOrderId();
		WorkOrder workOrder = workOrderMapper.selectById(workOrderId);
		if (workOrder == null) throw BusinessRuntimeException.getInstance("该工单不存在");
		if (workOrder.getStatus() == WorkOrder.Status.close) throw BusinessRuntimeException.getInstance("本次对话已结束,如有问题请提交新的工单");
		List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
		if (!userIds.contains(workOrder.getUserId())) throw BusinessRuntimeException.getInstance("网络错误");
		String content = history.getContent();
		String imgs = history.getImgs();
		if (StrUtil.isEmpty(content) && StrUtil.isEmpty(imgs)) {
			throw BusinessRuntimeException.getInstance("请回复相关内容");
		}
		if (StrUtil.isNotBlank(content) && content.length() > 200)
			throw BusinessRuntimeException.getInstance("回复内容最多200字数以内");

		if (StrUtil.isNotBlank(imgs)) {
			if (!imgs.contains("[") && !imgs.contains("]")) {
				imgs = String.format("[\"%s\"]", imgs);
			}
			if (imgs.length() > 2000) throw BusinessRuntimeException.getInstance("选择图片过多");
		}
		history.setFromUser(WorkOrderChatHistory.Messenger.user);
		history.setToUser(WorkOrderChatHistory.Messenger.root);
		historyMapper.insert(history);
	}
}
