package com.slodon.b2b2c.controller.business.seller;

import com.slodon.b2b2c.business.pojo.Order;
import com.slodon.b2b2c.business.pojo.OrderAfterService;
import com.slodon.b2b2c.business.pojo.OrderExtend;
import com.slodon.b2b2c.core.constant.GoodsConst;
import com.slodon.b2b2c.core.constant.OrderConst;
import com.slodon.b2b2c.core.express.TracesResult;
import com.slodon.b2b2c.core.express.TrackUtil;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.model.business.OrderAfterServiceModel;
import com.slodon.b2b2c.model.business.OrderExtendModel;
import com.slodon.b2b2c.model.business.OrderModel;
import com.slodon.b2b2c.model.seller.StoreExpressSettingModel;
import com.slodon.b2b2c.seller.example.StoreExpressSettingExample;
import com.slodon.b2b2c.seller.pojo.StoreExpressSetting;
import com.slodon.b2b2c.seller.pojo.Vendor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author slodon
 */
@Api(tags = "seller-物流信息")
@RestController
@RequestMapping("v3/business/seller/logistics")
public class SellerLogisticsController {

    @Resource
    private OrderModel orderModel;
    @Resource
    private OrderExtendModel orderExtendModel;
    @Resource
    private OrderAfterServiceModel orderAfterServiceModel;
    @Resource
    private StoreExpressSettingModel storeExpressSettingModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("订单查看物流")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单号", required = true, paramType = "query")
    })
    @GetMapping("order/getTrace")
    public JsonResult<TracesResult> getOrderTrace(HttpServletRequest request, String orderSn) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //查询订单信息
        Order order = orderModel.getOrdersWithOpByOrderSn(orderSn);
        AssertUtil.notNull(order, "此订单物流信息为空");
        AssertUtil.isTrue(!vendor.getStoreId().equals(order.getStoreId()), "您无权查看此订单物流");
        AssertUtil.isTrue(order.getIsVirtualGoods() == GoodsConst.IS_VIRTUAL_GOODS_2, "该订单为虚拟商品订单，没有物流信息");

        if (order.getOrderState() > OrderConst.ORDER_STATE_20 && StringUtil.isEmpty(order.getExpressCode())) {
            OrderExtend orderExtend = orderExtendModel.getOrderExtendByOrderSn(orderSn);
            AssertUtil.notNull(orderExtend, "此订单扩展信息为空");
            TracesResult tracesResult = new TracesResult();
            tracesResult.setExpressName(orderExtend.getDeliverName());
            tracesResult.setExpressNumber(orderExtend.getDeliverMobile());
            tracesResult.setType("1");
            return SldResponse.success(tracesResult);
        } else {
            AssertUtil.isTrue(StringUtil.isEmpty(order.getExpressCode()), "快递公司编号信息为空");

            TracesResult tracesResult;
            String expressType = stringRedisTemplate.opsForValue().get("express_type");
            if ("1".equals(expressType)) {
                //快递鸟
                tracesResult = this.getExpressTrack1(order.getOrderSn(), order.getExpressCode(), order.getExpressName(),
                        order.getExpressNumber(), order.getStoreId(), order.getReceiverMobile().substring(7, 11));
            } else {
                //快递100
                tracesResult = this.getExpressTrack2(order.getReceiverMobile(), order.getExpressCode(), order.getExpressName(),
                        order.getExpressNumber());
            }
            return SldResponse.success(tracesResult);
        }
    }

    @ApiOperation("售后查看物流")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "afsSn", value = "退货单号", required = true, paramType = "query")
    })
    @GetMapping("afs/getTrace")
    public JsonResult<TracesResult> getTrace(HttpServletRequest request, String afsSn) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //查询售后服务信息
        OrderAfterService orderAfterService = orderAfterServiceModel.getAfterServiceByAfsSn(afsSn);
        AssertUtil.isTrue(StringUtil.isEmpty(orderAfterService.getBuyerExpressCode()), "物流公司快递代码为空，请重试");
        AssertUtil.isTrue(StringUtil.isEmpty(orderAfterService.getBuyerExpressNumber()), "物流单号为空，请重试");
        AssertUtil.isTrue(!vendor.getStoreId().equals(orderAfterService.getStoreId()), "无权限");

        TracesResult tracesResult;
        String expressType = stringRedisTemplate.opsForValue().get("express_type");
        if ("1".equals(expressType)) {
            //快递鸟
            tracesResult = this.getExpressTrack1(orderAfterService.getOrderSn(), orderAfterService.getBuyerExpressCode(),
                    orderAfterService.getBuyerExpressName(), orderAfterService.getBuyerExpressNumber(), orderAfterService.getStoreId(),
                    orderAfterService.getContactPhone().substring(7, 11));
        } else {
            //快递鸟100
            tracesResult = this.getExpressTrack2(orderAfterService.getContactPhone(), orderAfterService.getBuyerExpressCode(),
                    orderAfterService.getBuyerExpressName(), orderAfterService.getBuyerExpressNumber());
        }
        return SldResponse.success(tracesResult);
    }

    /**
     * 获取快递鸟物流轨迹
     *
     * @param orderSn        订单号
     * @param expressCode    快递编码
     * @param expressName    快递公司
     * @param expressNumber  快递单号
     * @param storeId        店铺id
     * @param receiverMobile 收货人手机号
     * @return 物流信息轨迹
     */
    public TracesResult getExpressTrack1(String orderSn, String expressCode, String expressName, String expressNumber, Long storeId, String receiverMobile) {
        //快递鸟电商ID
        String eBusinessId;
        //快递鸟电商加密私钥
        String appKey;
        String accountSetting = stringRedisTemplate.opsForValue().get("express_account_setting");
        if (StringUtil.isEmpty(accountSetting) || "1".equals(accountSetting)) {
            eBusinessId = stringRedisTemplate.opsForValue().get("express_ebusinessid");
            AssertUtil.notNull(eBusinessId, "请完善快递鸟配置信息：");
            appKey = stringRedisTemplate.opsForValue().get("express_apikey");
            AssertUtil.notNull(appKey, "请完善快递鸟配置信息：");
        } else {
            StoreExpressSettingExample example = new StoreExpressSettingExample();
            example.setStoreId(storeId);
            List<StoreExpressSetting> list = storeExpressSettingModel.getStoreExpressSettingList(example, null);
            AssertUtil.notEmpty(list, "请完善快递鸟配置信息：");

            eBusinessId = list.get(0).getBusinessId();
            AssertUtil.notNull(eBusinessId, "请完善快递鸟配置信息：");
            appKey = list.get(0).getAppKey();
            AssertUtil.notNull(appKey, "请完善快递鸟配置信息：");
        }
        return TrackUtil.getKdniaoTrack(orderSn, expressCode, expressName, expressNumber, eBusinessId, appKey, receiverMobile);
    }

    /**
     * 获取快递100物流轨迹
     *
     * @param phone         手机号
     * @param expressCode   快递编码
     * @param expressName   快递公司
     * @param expressNumber 快递单号
     * @return 物流信息轨迹
     */
    public TracesResult getExpressTrack2(String phone, String expressCode, String expressName, String expressNumber) {
        String key = stringRedisTemplate.opsForValue().get("express_100_key");
        AssertUtil.notNull(key, "请设置快递100 授权key");
        String customer = stringRedisTemplate.opsForValue().get("express_100_customer");
        AssertUtil.notNull(customer, "请设置快递100 授权码");
        return TrackUtil.getKd100Track(phone, expressCode, expressName, expressNumber, key, customer);
    }
}
