package com.xunhong.erp.turbo.admin.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.cola.dto.SingleResponse;
import com.xunhong.erp.turbo.api.biz.api.DealerServiceI;
import com.xunhong.erp.turbo.api.biz.dto.qry.DealerListQry;
import com.xunhong.erp.turbo.api.biz.dto.vo.DealerVO;
import com.xunhong.erp.turbo.api.facade.api.DeepSeekServiceI;
import com.xunhong.erp.turbo.api.facade.dto.cmd.VehicleExtractionCmd;
import com.xunhong.erp.turbo.api.facade.dto.vo.VehicleExtractionVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天
 */
@Slf4j
@Tag(name = "Extraction", description = "信息抽取")
@RestController("operationExtractionController")
@RequestMapping("/operation")
@RequiredArgsConstructor
public class ExtractionController {

	@DubboReference(version = "1.0.0")
	private final DeepSeekServiceI deepSeekService;

	@DubboReference(version = "1.0.0")
	private final DealerServiceI dealerService;

	@SaCheckLogin
	@PostMapping("/extraction/vehicle")
	@Operation(summary = "智能提取物流信息", method = "POST")
	public SingleResponse<VehicleExtractionVO> vehicleExtraction(@RequestBody @Validated VehicleExtractionCmd vehicleExtractionCmd) {
		DealerListQry dealerListQry = new DealerListQry();
		dealerListQry.setStatus(Boolean.TRUE);
		List<DealerVO> dealerVOList = dealerService.list(dealerListQry);
		String dealerNames = dealerVOList.stream().map(DealerVO::getShortName).collect(Collectors.joining(","));
		vehicleExtractionCmd.setDealerNames(dealerNames);

		VehicleExtractionVO vehicleExtractionVO = deepSeekService.vehicleExtraction(vehicleExtractionCmd);
		String dealerName = vehicleExtractionVO.getDealerName();
		if (dealerName != null) {
			dealerVOList.stream()
				.filter(dealerVO -> dealerVO.getShortName().equals(dealerName))
				.findFirst()
				.ifPresent(dealerVO -> {
					vehicleExtractionVO.setDealerId(dealerVO.getDealerId());
					vehicleExtractionVO.setDealerVO(dealerVO);
				});
		}
		return SingleResponse.of(vehicleExtractionVO);
	}
}
