package com.fzm.mall.server.admin.distribution.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.config.Redis;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.distribution.mapper.ExpressMapper;
import com.fzm.mall.server.admin.distribution.model.Express;
import com.fzm.mall.server.admin.distribution.service.IExpressService;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.order.mapper.DeliveryMapper;
import com.fzm.mall.server.admin.order.model.Delivery;
import com.fzm.mall.server.admin.util.HttpUtil;
import com.fzm.mall.server.admin.util.MD5Util;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 物流中心-物流公司 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-04-15
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ExpressServiceImpl extends ServiceImpl<ExpressMapper, Express> implements IExpressService {

    @Value("${express.showapi-url}")
    private String baseUrl;

    @Value("${express.appid}")
    private String appid;

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

    @Value("${express.activeTime}")
    private Long activeTime;

    private final ExpressMapper expressMapper;
    private final Redis redis;
    private final DeliveryMapper deliveryMapper;

    @Override
    public List<Express> listAll(String expName) {
        return expressMapper.listAll(expName);
    }

    /**
     * 查询订单的详细物流信息
     *
     * @param expressName 物流公司简称
     * @param expressNo   物流单号
     * @return
     */
    @Override
    public String readExpressDetail(Delivery delivery, String expressName, String expressNo, String phone) {
        String value = redis.getKey(Express.EDILVERY_ORDER_EXPRESS_DETAIL_KEY + expressNo);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        String expressDetail = geExpressDetail(expressName, expressNo, phone);
        if (StringUtils.isNotBlank(expressDetail)) {

            delivery.setExpressDetail(expressDetail);
            int update = deliveryMapper.update(delivery, new UpdateWrapper<Delivery>().eq("order_delivery_id", delivery.getOrderDeliveryId())
                    .eq("update_time", delivery.getUpdateTime()));

            if (update == 0) {
                throw new MyException(MallResponseError.UPDATE_FAIL);
            }
            redis.setKey(Express.EDILVERY_ORDER_EXPRESS_DETAIL_KEY + expressNo, expressDetail, activeTime);
        }
        return expressDetail;
    }

    private String geExpressDetail(String expressName, String expressNo, String phone) {
        //com(快递公司简称),nu(订单号)
        String str = new StringBuilder().append("com").append(expressName)
                .append("nu").append(expressNo)
                .append("phone").append(phone)
                .append("showapi_appid").append(appid).append(secret).toString();
        String showapiSign = MD5Util.getMD5String(str);
        String url = new StringBuilder(baseUrl).append("com=").append(expressName)
                .append("&").append("nu=").append(expressNo)
                .append("&").append("phone=").append(phone)
                .append("&").append("showapi_appid=").append(appid)
                .append("&").append("showapi_sign=").append(showapiSign).toString();
        String response = HttpUtil.httpGet(url);
        JSONObject responseObj = JSON.parseObject(response);
        if (!responseObj.get("showapi_res_code").equals(Express.SECCESS_CODE)) {
            throw new MyException((String) responseObj.get("showapi_res_error"));
        }
        JSONObject bodyObj = (JSONObject) responseObj.get("showapi_res_body");

        return JSON.toJSONString(bodyObj.get("data"));
    }

}
