package com.gxwebsoft.shop.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.google.gson.JsonObject;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.param.GoodsStockInMerchantParam;
import com.gxwebsoft.shop.service.*;
import com.gxwebsoft.shop.param.OrderDeliveryParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.BOrderReq;
import com.kuaidi100.sdk.response.BOrderResp;
import com.kuaidi100.sdk.response.SubscribeResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 发货单控制器
 *
 * @author 科技小王子
 * @since 2024-09-24 01:39:23
 */
@Api(tags = "发货单管理")
@RestController
@RequestMapping("/api/shop/order-delivery")
public class OrderDeliveryController extends BaseController {
    @Resource
    private OrderDeliveryService orderDeliveryService;
    @Resource
    private OrderService orderService;
    @Resource
    private KuaiDi100 kuaiDi100;
    @Resource
    private ExpressService expressService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private GoodsStockInMerchantService goodsStockInMerchantService;
    @Resource
    private MerchantService merchantService;

    @ApiOperation("分页查询发货单")
    @GetMapping("/page")
    public ApiResult<PageResult<OrderDelivery>> page(OrderDeliveryParam param) {
        // 使用关联查询
        return success(orderDeliveryService.pageRel(param));
    }

    @ApiOperation("发货回调")
    @PostMapping("/notify")
    @GetMapping("/notify")
    public SubscribeResp notify(@RequestBody Map<String, Object> data) {
        System.out.println("快递100回调:" + data);
        SubscribeResp subscribeResp = new SubscribeResp();
        subscribeResp.setResult(Boolean.TRUE);
        subscribeResp.setReturnCode("200");
        subscribeResp.setMessage("成功");
        return subscribeResp;
    }

    @ApiOperation("查询全部发货单")
    @GetMapping()
    public ApiResult<List<OrderDelivery>> list(OrderDeliveryParam param) {
        // 使用关联查询
        return success(orderDeliveryService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("根据id查询发货单")
    @GetMapping("/{id}")
    public ApiResult<OrderDelivery> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(orderDeliveryService.getByIdRel(id));
    }

    @Transactional(rollbackFor = {Exception.class})
    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("添加发货单")
    @PostMapping()
    public ApiResult<?> save(@RequestBody OrderDelivery orderDelivery, HttpServletRequest request) throws Exception {
        String access_token = JwtUtil.getAccessToken(request);
        String tenantId = getTenantId().toString();
        Order order = orderService.getById(orderDelivery.getOrderId());
        Merchant merchant = null;
        // 根据最近的库存分配发货
        List<OrderGoods> orderGoodsList = orderGoodsService.listByOrderId(orderDelivery.getOrderId());
        List<GoodsStockInMerchant> goodsStockInMerchantList =
                goodsStockInMerchantService.canExpressList(orderGoodsList.get(0).getGoodsId(), orderGoodsList.get(0).getTotalNum(), order.getAddressLat(), order.getAddressLng());
        if (goodsStockInMerchantList.isEmpty()) return fail("暂无可发货店铺");
        for (OrderGoods orderGoods : orderGoodsList) {
            if (!goodsStockInMerchantList.isEmpty()) {
                GoodsStockInMerchant usable = goodsStockInMerchantList.get(0);
                GoodsStockInMerchant goodsStockInMerchant = goodsStockInMerchantService.check(usable.getMerchantId(), orderGoods.getGoodsId(), orderGoods.getSkuId());
                if (goodsStockInMerchant == null || goodsStockInMerchant.getStock() < orderGoods.getTotalNum())
                    return fail("库存不足");
            }
        }
        merchant = merchantService.getById(goodsStockInMerchantList.get(0).getMerchantId());
        if (merchant != null) {
            // 商家发货
            Express express = expressService.getByIdRel(orderDelivery.getExpressId());
            BOrderReq bOrderReq = new BOrderReq();
            bOrderReq.setKuaidicom(express.getKuaidi100Code());
            bOrderReq.setSendManName(merchant.getMerchantName());
            bOrderReq.setSendManMobile(merchant.getPhone());
            bOrderReq.setSendManPrintAddr(merchant.getProvince() + merchant.getCity() + merchant.getRegion() + merchant.getAddress());
            bOrderReq.setRecManName(order.getRealName());
            bOrderReq.setRecManMobile(order.getPhone());
            bOrderReq.setRecManPrintAddr(order.getAddress());
            bOrderReq.setCallBackUrl("https://modules.gxwebsoft.com/api/shop/order-delivery/notify");
            HttpResult res = kuaiDi100.border(bOrderReq);
//        System.out.println("res.getBody():" + res.getBody());
            if (res.getStatus() != 200) return fail("快递100接口异常");
            KuaiDi100Resp kuaiDi100Resp = JSONUtil.parseObject(res.getBody(), KuaiDi100Resp.class);
            if (kuaiDi100Resp == null) return fail("快递100接口异常");
            if (!kuaiDi100Resp.getResult()) return fail(kuaiDi100Resp.getMessage());
            Map<String, Object> bOrderData = (Map<String, Object>) kuaiDi100Resp.getData();
//        System.out.println("kuaidinum:" + bOrderData.get("kuaidinum"));
            orderDelivery.setExpressNo((String) bOrderData.get("kuaidinum"));
            if (orderDeliveryService.save(orderDelivery)) {
                order.setExpressMerchantId(merchant.getMerchantId());
                order.setExpressMerchantName(merchant.getMerchantName());
                order.setDeliveryStatus(20);
                order.setDeliveryTime(DateUtil.date());
                orderService.updateById(order);
                // 结算
                orderService.settle(access_token, tenantId, order);
                return success("操作成功");
            }
        }
        return fail("操作失败");
    }

    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("修改发货单")
    @PutMapping()
    public ApiResult<?> update(@RequestBody OrderDelivery orderDelivery) {
        if (orderDeliveryService.updateById(orderDelivery)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("删除发货单")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (orderDeliveryService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("批量添加发货单")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<OrderDelivery> list) {
        if (orderDeliveryService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("批量修改发货单")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<OrderDelivery> batchParam) {
        if (batchParam.update(orderDeliveryService, "delivery_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:orderDelivery:list')")
    @ApiOperation("批量删除发货单")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (orderDeliveryService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
