package com.yueqian.xingyun.comp.controller.components;

import cn.hutool.crypto.SecureUtil;
import com.lframework.starter.common.constants.StringPool;
import com.lframework.starter.common.exceptions.ClientException;
import com.lframework.starter.common.exceptions.impl.DefaultClientException;
import com.lframework.starter.common.utils.CollectionUtil;
import com.lframework.starter.common.utils.FileUtil;
import com.lframework.starter.web.core.bo.ExcelImportBo;
import com.lframework.starter.web.core.controller.DefaultBaseController;
import com.lframework.starter.web.core.components.resp.InvokeResult;
import com.lframework.starter.web.core.components.resp.InvokeResultBuilder;
import com.lframework.starter.web.inner.service.SysConfService;
import com.lframework.starter.web.core.utils.ExcelImportUtil;
import com.lframework.starter.web.core.utils.HttpUtil;
import com.lframework.starter.web.core.utils.JsonUtil;
import com.lframework.starter.web.core.utils.UploadUtil;
import com.yueqian.xingyun.comp.bo.components.MapLocationBo;
import com.yueqian.xingyun.comp.bo.components.OrderTimeLineBo;
import com.lframework.starter.web.inner.entity.OrderTimeLine;
import com.lframework.starter.web.inner.service.GenerateCodeService;
import com.lframework.starter.web.inner.service.OrderTimeLineService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.Operation;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 公共组件 Controller
 */
@Slf4j
@Tag(name = "公共组件")
@Validated
@RestController
@RequestMapping("/component")
public class ComponentController extends DefaultBaseController {

  @Autowired
  private SysConfService sysConfService;

  @Autowired
  private OrderTimeLineService orderTimeLineService;

  @Autowired
  private GenerateCodeService generateCodeService;

  @Operation(summary = "查询导入Excel任务")
  @GetMapping("/import/task")
  public InvokeResult<ExcelImportBo> getExcelImportTask(
      @NotBlank(message = "ID不能为空！") String id) {

    return InvokeResultBuilder.success(ExcelImportUtil.getTask(id));
  }

  @Operation(summary = "获取地图Key")
  @GetMapping("/map/key")
  public InvokeResult<String> getMapKey() {
    String key = sysConfService.findRequiredByKey("tx-map.key");

    return InvokeResultBuilder.success(key);
  }

  @Operation(summary = "根据地址查询经纬度")
  @GetMapping("/map/location")
  public InvokeResult<MapLocationBo> getMapLocation(
      @NotEmpty(message = "地址不能为空！") String address) {

    String key = sysConfService.findRequiredByKey("tx-map.key");
    String secret = sysConfService.findRequiredByKey("tx-map.secret");

    // 请求腾讯地图WebService Api
    // Api文档地址：https://lbs.qq.com/service/webService/webServiceGuide/webServiceGeocoder
    String baseUrl = "https://apis.map.qq.com/";
    String uri = "/ws/geocoder/v1/";
    String reqParams = "?address=" + address + "&key=" + key;

    // Api使用签名方式
    // 签名文档：https://lbs.qq.com/faq/serverFaq/webServiceKey
    String sign = SecureUtil.md5(uri + reqParams + secret);
    Map<String, Object> reqMap = new HashMap<>();
    reqMap.put("address", address);
    reqMap.put("key", key);
    reqMap.put("sig", sign);

    try {
      String resp = HttpUtil.doGet(baseUrl + uri, reqMap);
      Map<String, Object> respMap = JsonUtil.parseObject(resp, Map.class);
      if (!"0".equals(String.valueOf(respMap.get("status")))) {
        throw new DefaultClientException(String.valueOf(respMap.get("message")));
      }

      Map<String, Object> result = (Map<String, Object>) respMap.get("result");
      Map<String, Object> location = (Map<String, Object>) result.get("location");
      MapLocationBo bo = new MapLocationBo();
      bo.setLng(new BigDecimal(String.valueOf(location.get("lng"))));
      bo.setLat(new BigDecimal(String.valueOf(location.get("lat"))));

      return InvokeResultBuilder.success(bo);
    } catch (ClientException e) {
      throw e;
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new DefaultClientException("解析地址失败，请稍后再试！");
    }
  }

  @Operation(summary = "单据时间轴")
  @Parameter(name = "orderId", description = "单据ID", in = ParameterIn.QUERY, required = true)
  @GetMapping("/timeline/order")
  public InvokeResult<List<OrderTimeLineBo>> getOrderTimeLine(
      @NotBlank(message = "单据ID不能为空！") String orderId) {

    List<OrderTimeLine> datas = orderTimeLineService.getByOrder(orderId);
    List<OrderTimeLineBo> results = datas.stream().map(OrderTimeLineBo::new)
        .collect(Collectors.toList());

    return InvokeResultBuilder.success(results);
  }

  @Operation(summary = "通用上传图片")
  @PostMapping("/upload/image")
  public InvokeResult<String> uploadImage(MultipartFile file) {
    if (!FileUtil.IMG_SUFFIX.contains(
        FileUtil.getSuffix(file.getOriginalFilename()).toLowerCase())) {
      throw new DefaultClientException(
          "上传图片仅支持【" + CollectionUtil.join(FileUtil.IMG_SUFFIX, StringPool.STR_SPLIT_CN)
              + "】格式！");
    }

    String url = UploadUtil.upload(file).getUrl();

    return InvokeResultBuilder.success(url);
  }

  @Operation(summary = "通用上传视频")
  @PostMapping("/upload/video")
  public InvokeResult<String> uploadVideo(MultipartFile file) {
    if (!FileUtil.VIDEO_SUFFIX.contains(
        FileUtil.getSuffix(file.getOriginalFilename()).toLowerCase())) {
      throw new DefaultClientException(
          "上传视频仅支持【" + CollectionUtil.join(FileUtil.VIDEO_SUFFIX, StringPool.STR_SPLIT_CN)
              + "】格式！");
    }

    String url = UploadUtil.upload(file).getUrl();

    return InvokeResultBuilder.success(url);
  }

  @Operation(summary = "获取编号")
  @Parameter(name = "type", description = "编号类型", in = ParameterIn.QUERY, required = true)
  @GetMapping("/generate/code")
  public InvokeResult<String> generateCode(@NotNull(message = "编号类型不能为空！") Integer type) {
    return InvokeResultBuilder.success(generateCodeService.generate(type));
  }
}
