package com.platform.api;

import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.enums.OrderStatusEnum;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.util.wechat.WechatRefundApiResult;
import com.platform.util.wechat.WechatUtil;
import com.platform.utils.CommonDataUtils;
import com.platform.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * 描述: ApiIndexController <br>
 */
@Api(tags = "订单相关")
@RestController
@RequestMapping("/api/order")
@Slf4j
public class ApiOrderController extends ApiBaseAction {
    @Autowired
    private ApiOrderService orderService;
    @Autowired
    private ApiOrderGoodsService orderGoodsService;
    @Autowired
    private ApiKdniaoService apiKdniaoService;
    @Autowired
    private ApiOrderShippingService apiOrderShippingService;
    @Autowired
    private ApiGoodsService apiGoodsService;

    @Autowired
    private ApiBrandService apiBrandService;

    @Autowired
    private ApiUserCouponService apiUserCouponService;

    /**
     */
    @ApiOperation(value = "个人订单所有状态信息（主要是数量）")
    @PostMapping("index")
    public Object index() {
        long userId = getUserId();
        List<Map<String ,Object>> resultList = new ArrayList<>();
        //代付款
        long waitForPay = orderService.countOrderInfo(userId , OrderStatusEnum.WAIT_FOR_PAY.getCode());
        Map<String , Object> waitForPayMp = new HashMap<>();
        waitForPayMp.put("code" , OrderStatusEnum.WAIT_FOR_PAY.getCode());
        waitForPayMp.put("desc" , OrderStatusEnum.WAIT_FOR_PAY.getDesc());
        waitForPayMp.put("num" , waitForPay);
        resultList.add(waitForPayMp);

        //待发货
        long waitForDeliver = orderService.countOrderInfo(userId , OrderStatusEnum.WAIT_FOR_DELIVER.getCode());
        Map<String , Object> waitForDeliverMp = new HashMap<>();
        waitForDeliverMp.put("code" , OrderStatusEnum.WAIT_FOR_DELIVER.getCode());
        waitForDeliverMp.put("desc" , OrderStatusEnum.WAIT_FOR_DELIVER.getDesc());
        waitForDeliverMp.put("num" , waitForDeliver);
        resultList.add(waitForDeliverMp);

        //待收货
        long waitForReceive = orderService.countOrderInfo(userId , OrderStatusEnum.HAS_DELIVERED.getCode());
        Map<String , Object> waitForReceiveMp = new HashMap<>();
        waitForReceiveMp.put("code" , OrderStatusEnum.HAS_DELIVERED.getCode());
        waitForReceiveMp.put("desc" , OrderStatusEnum.HAS_DELIVERED.getDesc());
        waitForReceiveMp.put("num" , waitForReceive);
        resultList.add(waitForReceiveMp);

        //
        long finished = orderService.countOrderInfo(userId , OrderStatusEnum.FINISH.getCode());
        Map<String , Object> finishedMp = new HashMap<>();
        finishedMp.put("code" , OrderStatusEnum.FINISH.getCode());
        finishedMp.put("desc" , OrderStatusEnum.FINISH.getDesc());
        finishedMp.put("num" , finished);
        resultList.add(finishedMp);

        return toResponsSuccess(resultList);
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "获取订单列表")
    @PostMapping("list")
    public Object list(@LoginUser UserVo loginUser,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer size,
                       @RequestParam(value = "orderStatus", defaultValue = "-1") Integer orderStatus) {
        //
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "desc");
        if(orderStatus >= 0){
            if(orderStatus == 300){
                params.put("shipping_status", 1);
                params.put("order_status", orderStatus);
            }else if(orderStatus == 301) {
                params.put("order_done", 501);
            } else{
                params.put("order_status", orderStatus);
            }
        }
        //查询列表数据
        Query query = new Query(params);
        List<OrderVo> orderEntityList = orderService.queryList(query);
        int total = orderService.queryList(params).size();
        ApiPageUtils pageUtil = new ApiPageUtils(orderEntityList, total, query.getLimit(), query.getPage());
        //
        for (OrderVo item : orderEntityList) {
            Map orderGoodsParam = new HashMap();
            orderGoodsParam.put("order_id", item.getId());
            //订单的商品
            List<OrderGoodsVo> goodsList = orderGoodsService.queryList(orderGoodsParam);
            item.setGoodsList(goodsList);

            Integer goodsCount = 0;
            for (OrderGoodsVo orderGoodsEntity : goodsList) {
                goodsCount += orderGoodsEntity.getNumber();
                item.setGoodsCount(goodsCount);
            }
            //TODO:这里不做事务管控，能更新到就更新，不能就留着，后续这里需要挪到定时任务做，减轻查询接口的压力
            if(item.getOrder_status() == 0){
               if(null != item.getAdd_time()){
                   Duration duration = Duration.between(item.getAdd_time() , LocalDateTime.now());
                   long hours = duration.toHours();
                   log.info("订单[{}]创建时间距离现在过了:{}小时" ,item.getOrder_sn() , hours);
                   if(hours > 1){
                       //订单下单超过1个小时未支付，自动取消订单
                       item.setOrder_status(101);
                       int update =  orderService.update(item);
                       if(update != 1){
                           log.info("取消订单失败{}" , item.getOrder_sn());
                       }
                   }
               }
            }
        }
        return toResponsSuccess(pageUtil);
    }

    /**
     * 获取订单详情
     */
    @ApiOperation(value = "获取订单详情")
    @PostMapping("detail")
    public Object detail(Integer orderId) {
        Map resultObj = new HashMap();
        //
        OrderVo orderInfo = orderService.queryObject(orderId);
        if (null == orderInfo) {
            return toResponsObject(400, "订单不存在", "");
        }
        Map orderGoodsParam = new HashMap();
        orderGoodsParam.put("order_id", orderId);
        //订单的品牌种类
        orderGoodsParam.put("orderId", orderId);
        List<OrderShippingVo> shippingVoList = apiOrderShippingService.queryList(orderGoodsParam);
        //订单的商品
        List<OrderGoodsVo> orderGoods = orderGoodsService.queryList(orderGoodsParam);
        GoodsVo goodsVo = null;
        int is_on_sale = 1;
        for(OrderGoodsVo orderGoodsVo : orderGoods){
            goodsVo = apiGoodsService.queryObject(orderGoodsVo.getGoods_id());
            if(null == goodsVo){
                continue;
            }
            if(null != goodsVo.getIs_on_sale() && goodsVo.getIs_on_sale().compareTo(0) == 0){
                //订单中，只要有一个商品下架了，需要将整个订单置为下架
                is_on_sale = 0;
            }
            logger.info("goodsVo:" + goodsVo.getBrand_id());
            for(OrderShippingVo orderShippingVo : shippingVoList){
                logger.info("orderShippingVo:" + orderShippingVo.getBrandId());
                List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
                if(goodsVo.getBrand_id().intValue() == orderShippingVo.getBrandId().intValue()){
                    if(orderShippingVo.getOrderGoodsVoList() == null){
                        orderGoodsVoList.add(orderGoodsVo);
                        orderShippingVo.setOrderGoodsVoList(orderGoodsVoList);
                    }else {
                        orderGoodsVoList = orderShippingVo.getOrderGoodsVoList();
                        orderGoodsVoList.add(orderGoodsVo);
                        orderShippingVo.setOrderGoodsVoList(orderGoodsVoList);
                    }
                }
            }
        }
        //订单最后支付时间
        if (orderInfo.getOrder_status() == 0) {
            // if (moment().subtract(60, 'minutes') < moment(orderInfo.add_time)) {
//            orderInfo.final_pay_time = moment("001234", "Hmmss").format("mm:ss")
            // } else {
            //     //超过时间不支付，更新订单状态为取消
            // }
        }

        for(OrderShippingVo orderShippingVo : shippingVoList){
            BrandVo brandVo = apiBrandService.queryObject(orderShippingVo.getBrandId());
            orderShippingVo.setBrandName(orderShippingVo.getBrandName());
            if(!ObjectUtils.isEmpty(brandVo)){
                orderShippingVo.setBrandName(brandVo.getName());
            }
        }

        //订单可操作的选择,删除，支付，收货，评论，退换货
        Map handleOption = orderInfo.getHandleOption();
        //
        resultObj.put("orderInfo", orderInfo);
        resultObj.put("orderGoods", shippingVoList);
//        resultObj.put("orderGoods", orderGoods);
        resultObj.put("handleOption", handleOption);
        resultObj.put("handleOption", handleOption);
        resultObj.put("is_on_sale", is_on_sale);
//        if (!StringUtils.isEmpty(orderInfo.getShipping_code()) && !StringUtils.isEmpty(orderInfo.getShipping_no())) {
//            // 快递
//            List Traces = apiKdniaoService.getOrderTracesByJson(orderInfo.getShipping_code(), orderInfo.getShipping_no());
//            resultObj.put("shippingList", Traces);
//        }
        return toResponsSuccess(resultObj);
    }

    @ApiOperation(value = "修改订单")
    @PostMapping("updateSuccess")
    public Object updateSuccess(Integer orderId) {
        OrderVo orderInfo = orderService.queryObject(orderId);
        if (orderInfo == null) {
            return toResponsFail("订单不存在");
        } else if (orderInfo.getOrder_status() != 0) {
            return toResponsFail("订单状态不正确orderStatus" + orderInfo.getOrder_status() + "payStatus" + orderInfo.getPay_status());
        }

        orderInfo.setId(orderId);
        orderInfo.setPay_status(2);
        orderInfo.setOrder_status(201);
        orderInfo.setShipping_status(0);
        orderInfo.setPay_time(new Date());
        int num = orderService.update(orderInfo);
        if (num > 0) {
            return toResponsMsgSuccess("修改订单成功");
        } else {
            return toResponsFail("修改订单失败");
        }
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "订单提交")
    @PostMapping("submit")
    @Transactional(rollbackFor = Exception.class)
    public Object submit(@LoginUser UserVo loginUser) {
        Map resultObj = null;
        try {
            resultObj = orderService.submit(getJsonRequest(), loginUser);
            if (null != resultObj) {
                return toResponsObject(MapUtils.getInteger(resultObj, "errno"), MapUtils.getString(resultObj, "errmsg"), resultObj.get("data"));
            }
        } catch (Exception e) {
           log.error("订单提交失败，出现异常:{}" , e);
           throw new CommonBaseException(ResultCodeEnum.D100 , "订单提交失败");
        }
        return toResponsFail("提交失败");
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "取消订单")
    @PostMapping("cancelOrder")
    public Object cancelOrder(Integer orderId) {
        try {
            OrderVo orderVo = orderService.queryObject(orderId);
            if (orderVo.getOrder_status() == 300) {
                return toResponsFail("已发货，不能取消");
            } else if (orderVo.getOrder_status() == 301) {
                return toResponsFail("已收货，不能取消");
            }
            // 需要退款
            if (orderVo.getPay_status() == 2) {
                WechatRefundApiResult result = WechatUtil.wxRefund(orderVo.getOrder_sn(),
                        orderVo.getActual_price().doubleValue(), orderVo.getActual_price().doubleValue());
                if (result.getResult_code().equals("SUCCESS")) {
                    if (orderVo.getOrder_status() == 201) {
                        orderVo.setOrder_status(401);
                    } else if (orderVo.getOrder_status() == 300) {
                        orderVo.setOrder_status(402);
                    }
                    orderVo.setPay_status(4);
                    orderService.update(orderVo);
                    //取消已经使用的优惠券
                    cancelOrderCoupon(orderVo.getCoupon_id() , orderVo.getUser_id() , orderVo.getOrder_sn());
                    return toResponsMsgSuccess("取消成功");
                } else {
                    return toResponsObject(400, "取消成失败", "");
                }
            } else {
                orderVo.setOrder_status(102);
                orderService.update(orderVo);
                //取消已经使用的优惠券
                cancelOrderCoupon(orderVo.getCoupon_id() , orderVo.getUser_id() , orderVo.getOrder_sn());
                return toResponsMsgSuccess("取消成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    public void  cancelOrderCoupon(String couponIdListStr , long userId , String orderSn){
        if(StringUtils.isBlank(couponIdListStr)){
            return;
        }
        List<String> idStrList = Arrays.asList(couponIdListStr.split(","));
        if(CollectionUtils.isNotEmpty(idStrList)){
            for(String idStr : idStrList){
                int couponId = CommonDataUtils.getInteger(idStr);
                UserCouponVo userCouponVo = apiUserCouponService.getByUserIdAndCouponIdForUpdate(userId , couponId);
                if(userCouponVo != null){
                    //状态 1. 可用 2. 已用 3. 过期
                    if(null != userCouponVo.getCouponStatus() && userCouponVo.getCouponStatus().compareTo(2) == 0){
                        userCouponVo.setCouponStatus(1);
                        apiUserCouponService.update(userCouponVo);
                        log.info("取消订单:{}的优惠券:{}成功" , orderSn ,couponId);
                    }
                }
            }

        }
    }

    /**
     * 确认收货
     */
    @ApiOperation(value = "确认收货")
    @PostMapping("confirmOrder")
    public Object confirmOrder(Integer orderId) {
        try {
            OrderVo orderVo = orderService.queryObject(orderId);
            orderVo.setOrder_status(301);
            orderVo.setShipping_status(2);
            orderVo.setConfirm_time(new Date());
            orderService.update(orderVo);
            return toResponsSuccess("确认收货成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }
}
