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

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.sys.WorkOrderChatHistoryMapper;
import com.cyksj.mapper.manage.sys.WorkOrderMapper;
import com.cyksj.model.entity.WorkOrder;
import com.cyksj.model.entity.WorkOrderChatHistory;
import com.cyksj.model.excel.ExcelWorkOrderData;
import com.cyksj.model.views.CmsUserVO;
import com.cyksj.model.views.WorkOrderChatHistoryView;
import com.cyksj.model.views.WorkOrderView;
import com.cyksj.web.util.EasyExcelUtils;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/*
 *项目名: netflix
 *文件名: r
 *创建者: JavaZou
 *创建时间:2023/4/19 15:08
 */
@RestController
@RequestMapping("/manage/work/order")
@RequiredArgsConstructor
public class WorkOrderController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final GoodsDonMapper goodsDonMapper;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	private final WorkOrderMapper workOrderMapper;

	private final WorkOrderChatHistoryMapper historyMapper;

	private final UserMapper userMapper;

	@GetMapping("/get")
	@SaCheckPermission("workOrder:view")
	public Result<SearchResult<WorkOrderView>> getWorkOrderList(String nickname, Integer feedbackNum, Long customerServiceId) {
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (feedbackNum != null) {
			builder.put("feedback", String.format("wo.account in (select account from work_order group by account having count(*) >= %s)", feedbackNum));
			builder.orderBy(WorkOrder::getAccount).asc();
		}
		if (customerServiceId != null) {
			builder.field(WorkOrderView::getAssignCustomerServiceId, customerServiceId);
		}
		if (StrUtil.isNotBlank(nickname)) {
			List<Long> userIds = userMapper.selectListByNickname(nickname);
			builder.field(WorkOrderView::getUserId, userIds).op(Operator.InList);
		}
		SearchResult<WorkOrderView> search = beanSearcher.search(WorkOrderView.class, builder.build());
		search.getDataList().forEach(data -> {
			Optional.ofNullable(goodsDonMapper.selectById(data.getGoodsId()))
					.ifPresent(goodsDon -> data.setTitle(goodsDon.getTitle()));

			Optional.ofNullable(goodsDonSkuMapper.selectById(data.getSkuId()))
					.ifPresent(sku -> data.setSpecVal(sku.getSpecVal()));

			Optional.ofNullable(historyMapper.selectOne(Wrappers.lambdaQuery(WorkOrderChatHistory.class)
					.eq(WorkOrderChatHistory::getWorkOrderId, data.getId()).orderByDesc(WorkOrderChatHistory::getId)
					.last("limit 1")
					.select(WorkOrderChatHistory::getCreatedTime)))
					.ifPresent(last -> data.setFinalReplyTime(last.getCreatedTime()));
		});

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

	/**
	 * 修改工单状态
	 */
	@PutMapping("/put")
	public Result<String> putWorkOrderStatus(@RequestBody WorkOrder dto) {
		long adminId = StpUtil.getLoginIdAsLong();
		Long id = dto.getId();
		WorkOrder.Status status = dto.getStatus();
		String remark = dto.getRemark();
		WorkOrder workOrder = workOrderMapper.selectById(id);

		if (workOrder == null) {
			throw BusinessRuntimeException.getInstance("该工单不存在");
		}
		if (workOrder.getStatus() != WorkOrder.Status.waiting) {
			throw BusinessRuntimeException.getInstance("该工单已处理");
		}
		if (workOrder.getCloseCustomerServiceId() == 0) {
			workOrder.setCloseCustomerServiceId(adminId);
		}
		workOrder.setStatus(status);
		workOrder.setRemark(remark);
		workOrderMapper.updateById(workOrder);
		return GatewayResponse.SUCCESS.newBuilder().toResult("处理成功");
	}

	/**
	 * 查看聊天
	 */
	@GetMapping("/get/chat/history")
	@SaCheckPermission("workOrder:detail")
	public Result<SearchResult<WorkOrderChatHistoryView>> getChatHistoryById() {
		SearchResult<WorkOrderChatHistoryView> search = beanSearcher.search(WorkOrderChatHistoryView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		search.getDataList().forEach(data->{
			Optional.ofNullable(userMapper.selectById(data.getUserId()))
					.ifPresent(user -> data.setNickname(user.getNickname()));
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 客服回复用户工单
	 */
	@PostMapping("/customer/reply")
	@SaCheckPermission("workOrder:reply")
	@Transactional(rollbackFor = Throwable.class)
	public Result<String> customerReplyWorkOrder(@RequestBody @Validated WorkOrderChatHistory history) {
		long adminId = StpUtil.getLoginIdAsLong();
		//回复内容字数
		Long workOrderId = history.getWorkOrderId();
		WorkOrder workOrder = workOrderMapper.selectById(workOrderId);
		Assert.notNull(workOrder, "该工单不存在");
		if (workOrder.getStatus() == WorkOrder.Status.close) {
			throw BusinessRuntimeException.getInstance("该工单已被关闭");
		}
		history.setFromUser(WorkOrderChatHistory.Messenger.root);
		history.setToUser(WorkOrderChatHistory.Messenger.user);
		history.setReplyCustomerServiceId(adminId);
		history.setUserId(workOrder.getUserId());
		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.setImgs(imgs);
		}
		historyMapper.insert(history);
		if (workOrder.getCloseCustomerServiceId() == 0) {
			//记录首次回复聊天的客服
			workOrder.setReplyCustomerServiceId(adminId);
			workOrderMapper.updateById(workOrder);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 导出工单
	 */
	@GetMapping("/export")
	public void export(String nickname, String ids, HttpServletResponse response) {
		long adminId = StpUtil.getLoginIdAsLong();
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		//是不是客服
		CmsUserVO isCustomer = beanSearcher.searchFirst(CmsUserVO.class, MapUtils.builder()
				.field(CmsUserVO::getRoleNames, "客服").op(Operator.Contain)
				.field(CmsUserVO::getId, adminId)
				.build());
		if (StrUtil.isNotBlank(ids)) {
			String[] idAr = ids.split(",");
			builder.field(ExcelWorkOrderData::getId, idAr).op(Operator.InList);
		}
		if (isCustomer != null) {
			builder.field(ExcelWorkOrderData::getAssignCustomerServiceId, isCustomer.getId());
		}
		if (StrUtil.isNotBlank(nickname)) {
			List<Long> userIds = userMapper.selectListByNickname(nickname);
			builder.field(WorkOrderView::getUserId, userIds).op(Operator.InList);
		}
		List<ExcelWorkOrderData> list = beanSearcher.searchAll(ExcelWorkOrderData.class, builder.build());
		EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelWorkOrderData.class, list, "用户工单", "用户工单", ExcelTypeEnum.XLSX, null);
	}
}
