package com.bohuikeji.delivery.backstage.controller.api.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.controller.api.order.TorderCirceApi;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TOrderCircu;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.service.ITCourierService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.DataPage;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.service.ISysUserService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = {"管理端APP接口——订单相关"})
@RestController
@RequestMapping("/api/admin/order")
@Slf4j
public class AdminOrderApi {

    @Autowired
    ITOrderService orderService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ISysUserService userService;
    @Autowired
    ITFranchiseeInformationService franService;
    @Autowired
    ThirdUtils thirdUtils;
    @Autowired
    TorderCirceApi circeApi;

    /**
     *
     * @param page
     * @param status
     * @return
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态(待接单、进行中、已完成、全部订单)", dataType = "String", paramType = "query", example = "进行中", required = true),
            @ApiImplicitParam(name = "key", value = "搜索关键字[订单号]", dataType = "String", paramType = "query", example = "1724861")})
    public APIEntity list(@ApiIgnore @RequestAttribute("JwtAdminId") Integer adminId, DataPage page, String status,String key) {
        SysUser user=userService.getById(adminId);
        QueryWrapper<TOrder> queryWrapper;

        if(user.getFranId()==1){
            queryWrapper = new QueryWrapper<TOrder>().eq("order_batch_num", "0").orderByDesc("order_id");
        }
        else{
            queryWrapper = new QueryWrapper<TOrder>().eq("order_batch_num", "0")
                    .in("fran_id", franService.queryLow(user.getFranId())).orderByDesc("order_id");
        }
        queryWrapper.ne("is_test",1);
        if(StringUtils.isNotBlank(key)){
            switch (status) {
                case "待接单":
                    queryWrapper.eq("order_status", "待接单").like("order_num",key);
                    break;
                case "进行中":
                    queryWrapper.in("order_status", "待取件","待支付", "取件中", "待派送", "派送中").like("order_num",key);
                    break;
                case "已完成":
                    queryWrapper.in("order_status", "已完成", "待评价").like("order_num",key);
                    break;
                case "全部订单":
                    queryWrapper.like("order_num",key);
                    break;
                default:
                    return APIEntity.fail("参数错误，无法识别订单状态参数！");
            }
        }else {
            switch (status) {
                case "待接单":
                    queryWrapper.eq("order_status", "待接单");
                    break;
                case "进行中":
                    queryWrapper.in("order_status", "待取件","待支付", "取件中", "待派送", "派送中");
                    break;
                case "已完成":
                    queryWrapper.in("order_status", "已完成", "待评价");
                    break;
                case "全部订单":break;
                default:
                    return APIEntity.fail("参数错误，无法识别订单状态参数！");
            }
        }

        return APIEntity.success(orderService.page(page,queryWrapper));
    }


    @ApiOperation("查询订单详情")
    @GetMapping("/get")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id", dataType = "String", paramType = "query", example = "561", required = true)})
    public APIEntity get(Integer orderId) {
       TOrder order=orderService.getById(orderId);
       if(order==null){
           return APIEntity.fail("参数错误，未找到订单信息！");
       }
        return APIEntity.success(order);
    }

    @ApiOperation("搜索订单")
    @GetMapping("/search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "搜索关键字[订单号,寄件人姓名、寄件人手机号、收件人姓名、收件人手机号，付款单号]", dataType = "String", paramType = "query", example = "1724861", required = true)})
    public APIEntity searchCourice(String key){
        return APIEntity.success(orderService.list(new QueryWrapper<TOrder>()
                .like("order_num",key).or()
                .like("mailing_name",key).or()
                .like("mailing_phone",key).or()
                .like("receipt_name",key).or()
                .like("receipt_phone",key).or()
                .like("pay_num",key).orderByDesc("order_id").last(" limit 20")));
    }
    @ApiOperation("为订单指定/转派派送员")
    @GetMapping("/appoint")

    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id", dataType = "String", paramType = "query", example = "1", required = true),
            @ApiImplicitParam(name = "courierId", value = "派送员Id", dataType = "String", paramType = "query", example = "1", required = true)})
    public APIEntity setCourier(@ApiIgnore @RequestAttribute("JwtAdminId") Integer id,Integer orderId,Integer courierId){
        SysUser user=userService.getById(id);
        TOrder order=orderService.getById(orderId);
        TCourier courier=courierService.getById(courierId);
        if(order==null){
            return APIEntity.fail("未找到订单信息");
        }
        if(courier==null){
            return APIEntity.fail("没有该派送员信息！");
        }
        if("关闭".equals(courier.getAssignSwitch())){
            return APIEntity.fail("该派送员未开启接收指派功能！");
        }
        if("已完成".equals(order.getOrderStatus())){
            return APIEntity.fail("该订单已完成不可在指定/转派其他派送员");
        }
        return orderService.pointCourier(user,order,courier);
    }

    /**
     * 获取第三方订单推送结果
     * @param orderNum 订单号
     * @return
     */
    @ApiOperation("获取第三方订单推送结果")
    @GetMapping("/get/third/push/result")
    public APIEntity thirdResult(String orderNum){
        StringBuilder strBuilder=new StringBuilder();
        Map<String,APIEntity<OrderDetailDO>> results=new HashMap<>(4);
        results.put("闪送",thirdUtils.orderResult(orderNum,"SS"));
        results.put("UU跑腿",thirdUtils.orderResult(orderNum,"UU"));
        results.put("京东快递",thirdUtils.orderResult(orderNum,"JD"));
        results.put("货拉拉",thirdUtils.orderResult(orderNum,"HLL"));
        results.put("快递100",thirdUtils.orderResult(orderNum,"KD"));
        APIEntity sfRes=thirdUtils.orderResult(orderNum,"SF");
        if (sfRes==null||sfRes.getBody()==null){
            results.put("顺丰快递",APIEntity.fail("暂无推送信息"));
        }else {
            results.put("顺丰快递",thirdUtils.orderResult(orderNum,"SF"));
        }
        results.forEach((k,v)->{
            if (v==null){
                strBuilder.append("<span style='color: #DD524D;'>【").append(k).append("推送失败】</span>，无法找到推送记录，可能由于第三方系统延迟，请尝试等待1分钟再试！").append("<br>");return;
            }
            if (v.checkSuccess()){
                strBuilder.append("<span style='color: #00aa7f;'>【").append(k).append("推送成功】</span>，").append("第三方订单号：").append(v.myBody(OrderDetailDO.class).getThirdNum()).append("<br>");
            }else{
                strBuilder.append("<span style='color: #DD524D;'>【").append(k).append("推送失败】</span>，").append("第三方返回信息：").append(v.getMessage()).append("<br>");
            }
        });
        return APIEntity.success(strBuilder.toString());
    }

    /**
     * 获取第三方订单配送信息
     * @param orderId
     * @return
     */
    @ApiOperation("获取第三方订单配送信息")
    @GetMapping("/get/third/order/info")
    public APIEntity thirdInfo(Integer orderId){
        TOrder order=orderService.getById(orderId);
        if (order!=null){
            OrderDetailDO detail=thirdUtils.orderDetail(order);
            if (detail==null){
                return APIEntity.fail("暂无信息，该订单当前不是由第三方进行配送！");
            }
            return APIEntity.success(detail);
        }
        return APIEntity.fail("无法找到订单信息，请刷新页面重试！");
    }

    /**
     * 获取第三方订单信息
     * @param orderId
     * @return
     */
    @ApiOperation("获取第三方订单信息")
    @GetMapping("/get/third/order/record")
    public APIEntity<List<TOrderCircu>> thirdRecord(Integer orderId){
        return circeApi.getByOrder(orderId);
    }

   /* @ApiOperation("搜索订单")
    @GetMapping("/get/order/search/key")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "搜索关键字[第三方名称,订单状态、订单号、客户手机号]", dataType = "String", paramType = "query", example = "1724861"),
            @ApiImplicitParam(name = "status", value = "搜索关键字[第三方名称,订单状态、订单号、客户手机号]", dataType = "String", paramType = "query", example = "1724861")})
    public APIEntity getSearchByName(@ApiIgnore @RequestAttribute("JwtAdminId") Integer adminId, DataPage page, String status,String key){
        SysUser user=userService.getById(adminId);
        QueryWrapper<TOrder> queryWrapper;

        if(user.getFranId()==1){
            queryWrapper = new QueryWrapper<TOrder>().eq("order_batch_num", "0").orderByDesc("order_id");
        }
        else{
            queryWrapper = new QueryWrapper<TOrder>().eq("order_batch_num", "0")
                    .in("fran_id", franService.queryLow(user.getFranId())).orderByDesc("order_id");
        }
        queryWrapper.ne("is_test",1);
        if(StringUtils.isNotBlank(key)){
            switch (status) {
                case "待接单":
                    queryWrapper.eq("order_status", "待接单").like("order_num",key);
                    break;
                case "进行中":
                    queryWrapper.in("order_status", "待取件","待支付", "取件中", "待派送", "派送中").like("order_num",key);
                    break;
                case "已完成":
                    queryWrapper.in("order_status", "已完成", "待评价").like("order_num",key);
                    break;
                case "全部订单":
                    queryWrapper.like("order_num",key);
                    break;
                default:
                    return APIEntity.fail("参数错误，无法识别订单状态参数！");
            }
        }else {
            switch (status) {
                case "待接单":
                    queryWrapper.eq("order_status", "待接单");
                    break;
                case "进行中":
                    queryWrapper.in("order_status", "待取件","待支付", "取件中", "待派送", "派送中");
                    break;
                case "已完成":
                    queryWrapper.in("order_status", "已完成", "待评价");
                    break;
                case "全部订单":break;
                default:
                    return APIEntity.fail("参数错误，无法识别订单状态参数！");
            }
        }
        return APIEntity.success(orderService.page(page,queryWrapper));
    }*/

}
