package com.qs.mp.web.controller.common;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.AutoNum;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.api.QueryTrackMap;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.AutoNumReq;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.utils.SignUtils;
import com.qs.mp.admin.domain.param.LogisticsQueryParam;
import com.qs.mp.admin.domain.vo.LogisticsQueryVO;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.domain.DeliveryCompany;
import com.qs.mp.common.service.IDeliveryCompanyService;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.common.utils.MD5Util;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Cup
 * @date 2022/4/20
 */
@RequestMapping("/api/v1/mp/logistics")
@RestController
@Api(tags = "物流相关接口")
public class LogisticsController extends BaseApiController {


    @Value("${kuaidi100.key}")
    public String key;

    @Value("${kuaidi100.customer}")
    private String customer;

    @Value("${kuaidi100.secret}")
    private String secret;

    @Value("${kuaidi100.userid}")
    private String userid;

    @Autowired
    private IDeliveryCompanyService deliveryCompanyService;


    @PostMapping("/query")
    @ApiOperation("物流查询")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = LogisticsQueryVO.class)
    )
    public AjaxResult query(@Validated @RequestBody LogisticsQueryParam logisticsQueryParam) {
        // 查询物流公司信息
        DeliveryCompany deliveryCompany = deliveryCompanyService.getOne(new LambdaQueryWrapper<DeliveryCompany>()
                .select(DeliveryCompany::getCode)
                .eq(DeliveryCompany::getDeliveryId, logisticsQueryParam.getDeliveryId()));

        if (Objects.isNull(deliveryCompany)) {
            return error("物流公司不存在");
        }
        if (StringUtils.isBlank(deliveryCompany.getCode())) {
            return error("物流公司编码不存在");
        }

        // 封装物流请求参数
        QueryTrackParam queryTrackParam = new QueryTrackParam();
        // 快递公司编码
        queryTrackParam.setCom(deliveryCompany.getCode());
        // 物流单号
        queryTrackParam.setNum(logisticsQueryParam.getDeliveryFlowId());
        //1：开通行政区域解析功能以及物流轨迹增加物流状态名称
        queryTrackParam.setResultv2("1");

        // 查询地图轨迹必填,暂时写死
        queryTrackParam.setTo("浙江省杭州市西湖区");
        queryTrackParam.setFrom("浙江省嘉兴市南湖区");

        String param = new Gson().toJson(queryTrackParam);

        QueryTrackReq queryTrackReq = new QueryTrackReq();
        queryTrackReq.setCustomer(customer);
        queryTrackReq.setParam(param);
        String sign = SignUtils.querySign(param ,key,customer);
        queryTrackReq.setSign(sign);

        IBaseClient baseClient = new QueryTrackMap();
        try {
            HttpResult execute = baseClient.execute(queryTrackReq);
            String body = execute.getBody();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String flag = jsonObject.getStr("result");
            if (StringUtils.equals(flag, "false")) {
                return AjaxResult.error(jsonObject.getStr("message"));
            }
            List<LogisticsQueryVO> data = JSONUtil.toList(jsonObject.getStr("data"), LogisticsQueryVO.class);
            if (CollectionUtils.isNotEmpty(data) && data.size() > 1) {
                for (int i = data.size() - 1; i > 0; i--) {
                    if (data.get(i).getStatus().equals(data.get(i-1).getStatus())) {
                        data.get(i).setStatus("");
                    }
                }
            }
            return AjaxResult.success(data);

        } catch (Exception e) {
            LogUtil.error(logger, e, "物流查询异常");
            return AjaxResult.error(e.getMessage());
        }
    }




    @PostMapping("/autonumber/auto/{number}")
    @ApiOperation("自动单号识别接口")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "number", value = "快递单号", required = true, dataType = "String", paramType = "path")
    )
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = DeliveryCompany.class)
    )
    public AjaxResult autonumber(@PathVariable("number") String number) {
        if (StringUtils.isBlank(number)) {
            return error("快递单号不能为空");
        }
        AutoNumReq autoNumReq = new AutoNumReq();
        autoNumReq.setKey(key);
        autoNumReq.setNum(number);
        IBaseClient baseClient = new AutoNum();
        try {
            HttpResult execute = baseClient.execute(autoNumReq);
            if (Objects.isNull(execute)) {
                return error("自动单号识别失败");
            }
            String body = execute.getBody();
            if (StringUtils.isBlank(body)) {
                return error("自动单号识别失败");
            }

            JSONArray jsonArray = JSONUtil.parseArray(body);
            if (jsonArray.size() != 1) {
                return AjaxResult.success();
            }
            String name = jsonArray.getJSONObject(0).getStr("name");

            DeliveryCompany deliveryCompany = deliveryCompanyService.getOne(new LambdaQueryWrapper<DeliveryCompany>().eq(DeliveryCompany::getCompanyName, name));
            return AjaxResult.success(deliveryCompany);

        } catch (Exception e) {
            LogUtil.error(logger, e, "自动单号识别异常");
            return error(e.getMessage());
        }
    }




}
