package com.kmall.api.api;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kmall.api.annotation.IgnoreAuth;
import com.kmall.api.annotation.LoginUser;
import com.kmall.api.contants.Dict;
import com.kmall.api.dao.ApiOrderRefundMapper;
import com.kmall.api.entity.*;
import com.kmall.api.service.*;
import com.kmall.api.service.express.kdn.ApiKdniaoService;
import com.kmall.api.util.ApiBaseAction;
import com.kmall.api.util.ApiPageUtils;
import com.kmall.common.utils.Constant;
import com.kmall.common.utils.Query;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.WechatUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 作者: @author Scott <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseAction {
    @Autowired
    private ApiOrderService orderService;
    @Autowired
    private ApiOrderGoodsService orderGoodsService;
    @Autowired
    private ApiKD100Service apiKD100Service;
    @Autowired
    private ApiKdniaoService apiKdniaoService;
    @Autowired
    private ApiAddressService apiAddressService;
    @Autowired
    private ApiCommentService apiCommentService;
    @Autowired
    private ApiOrderProcessRecordService orderProcessRecordService;
    @Autowired
    private ApiOrderRefundService apiOrderRefundService;

    /**
     */
    @IgnoreAuth
    @GetMapping("index")
    public Object index(@LoginUser UserVo loginUser) {
        //
        return toResponsSuccess("");
    }

    /**
     * 获取订单列表
     */
    @GetMapping("list")
    public Object list(@LoginUser UserVo loginUser,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size,
                       Integer evaluate_status, Integer order_status) {
        //
        Map params = new HashMap();
        params.put("user_id", loginUser.getId());
        params.put("page", page);
        params.put("order_status", order_status);
        params.put("evaluate_status", evaluate_status);
        params.put("limit", size);
        params.put("sidx", "add_time");
        params.put("order", "desc");
        params.put("size", "desc");

        //查询列表数据
        Query query = new Query(params);
        List<OrderVo> orderEntityList = orderService.queryList(query);
        int total = orderService.queryTotal(query);
        //
        for (OrderVo item : orderEntityList) {
            Map orderGoodsParam = new HashMap();
            orderGoodsParam.put("order_id", item.getId());
            if(item.getRefundStatus() !=null){
                if(item.getRefundStatus().equalsIgnoreCase(Dict.RefundStatus.item_1.getItem()) ||
                        item.getRefundStatus().equalsIgnoreCase(Dict.RefundStatus.item_2.getItem())){
                    item.setIsRefundStatus(true);
                }else{
                    item.setIsRefundStatus(false);
                }
            }else{
                item.setIsRefundStatus(false);
            }

            //订单的商品
            List<OrderGoodsVo> goodsList = orderGoodsService.queryList(orderGoodsParam);
            Integer goodsCount = 0;
            for (OrderGoodsVo orderGoodsEntity : goodsList) {
                goodsCount += orderGoodsEntity.getNumber();
                item.setGoodsCount(goodsCount);
            }
            item.setGoodsList(goodsList);
        }
        ApiPageUtils pageUtil = new ApiPageUtils(orderEntityList, total, query.getLimit(), query.getPage());
        return toResponsSuccess(pageUtil);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("detail")
    public Object detail(@LoginUser UserVo loginUser, Long 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);
        //订单的商品
        List<OrderGoodsVo> orderGoods = orderGoodsService.queryList(orderGoodsParam);

        //订单可操作的选择,删除，支付，收货，评论，退换货
        Map handleOption = orderInfo.getHandleOption();
        resultObj.put("orderInfo", orderInfo);
        resultObj.put("orderGoods", orderGoods);
        resultObj.put("handleOption", handleOption);

        //查询物流轨迹
        List<Map> mapList = new ArrayList<>();

        if(orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())
                && orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_301.getItem())){
            Map map = new HashMap();
            map.put("AcceptStation", "交易完成，用户已提走");
            mapList.add(map);
        }
        OrderProcessRecordEntity entity = orderProcessRecordService.queryObjectByOrderSn(orderInfo.getOrder_sn());
        if (entity != null) {
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(entity.getIsCustomsSend())) {
                Map map = new HashMap();
                map.put("AcceptTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getCustomsSuccTime()));
                map.put("AcceptStation", "订单清关完成，等待仓库发货");
                mapList.add(map);
            }
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(entity.getIsPaymentSend())) {
                Map map = new HashMap();
                map.put("AcceptTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getPaySuccTime()));
                map.put("AcceptStation", "订单支付成功，等待海关清关");
                mapList.add(map);
            }
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(entity.getIsAddOrderSend())) {
                Map map = new HashMap();
                map.put("AcceptTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getAddOrderSuccTime()));
                map.put("AcceptStation", "订单提交成功");
                mapList.add(map);
            }
        }
        if(!orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
            if (!StringUtils.isEmpty(orderInfo.getShipping_code()) && !StringUtils.isEmpty(orderInfo.getShipping_no())) {
                JSONObject Traces = apiKdniaoService.getOrderTracesByJson(orderInfo.getShipping_code(), orderInfo.getShipping_no());
                if (Traces != null) {
                    mapList = (List<Map>) Traces.get("Traces");
                    String State = (String) Traces.get("State"); //物流状态：2-在途中,3-签收,4-问题件
                    if (Dict.logisticsStatus.item_0.getItem().equalsIgnoreCase(State)) {
                        Map noDataMap = new HashMap();
                        noDataMap.put("AcceptTime", "");
                        noDataMap.put("AcceptStation", Traces.get("Reason"));
                        mapList.add(noDataMap);
                    }
                }
            }
        }
        resultObj.put("wuliu", mapList != null && mapList.size() > 0 ? mapList.get(0) : null);

        if(orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_401.getItem()) || orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_402.getItem()) ) {
            MallOrderRefund refundInfo = apiOrderRefundService.queryObjectByOrderId(String.valueOf(orderInfo.getId()));
            resultObj.put("refundInfo", refundInfo);
        }

        return toResponsSuccess(resultObj);
    }

    @GetMapping("detailList")
    public Object detailList(@LoginUser UserVo loginUser, Long[] orderIds) {
        List<Long> orderIdList=new ArrayList<>();
        for(int i=0;i<orderIds.length;i++){
            orderIdList.add(orderIds[i]);
        }
        Map resultObj = new HashMap();

        List<OrderVo> orderVoList = orderService.queryObjectByIdList(orderIdList);
        BigDecimal actualPrice = Constant.ZERO;

        for (OrderVo orderInfo:orderVoList) {
            if (null == orderInfo) {
                return toResponsObject(400, "订单号为"+orderInfo.getOrder_sn()+"的订单不存在", "");
            }
            actualPrice = actualPrice.add(orderInfo.getActual_price());
        }
        //订单的商品
        List<OrderGoodsVo> orderGoods = orderGoodsService.queryListByIds(orderIdList);

        resultObj.put("actualPrice", actualPrice);
        resultObj.put("orderGoods", orderGoods);
        return toResponsSuccess(resultObj);
    }

    /**
     * 获取订单列表
     */
    @PostMapping("submit")
    public Object submit(@LoginUser UserVo loginUser) {
        Map resultObj = null;
        try {
            resultObj = orderService.submit(getJsonRequest(), loginUser, getStoreId());
            if (null != resultObj) {
                return toResponsObject(MapUtils.getInteger(resultObj, "errno"), MapUtils.getString(resultObj, "errmsg"), resultObj.get("data"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 取消订单
     */
    @GetMapping("cancelOrder")
    public Object cancelOrder(@LoginUser UserVo loginUser, Long orderId) {
        try {
            OrderVo orderVo = orderService.queryObject(orderId);
            if (orderVo.getOrder_status() == 300) {
                return toResponsFail("已发货，不能取消");
            } else if (orderVo.getOrder_status() == 301) {
                return toResponsFail("已收货，不能取消");
            } else if (orderVo.getOrder_status() == 101 || orderVo.getOrder_status() == 401 || orderVo.getOrder_status() == 402) {
                return toResponsFail("当前订单不能取消");
            }
            // 需要退款
            if (orderVo.getPay_status() == 2) {
                WechatRefundApiResult result = WechatUtil.wxRefund(orderVo.getMerchOrderSn().toString(),
                        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.cancelOrder(orderVo);
                    return toResponsMsgSuccess("取消成功");
                } else {
                    return toResponsFail("取消失败");
                }
            } else {
                orderVo.setOrder_status(101);
                orderService.cancelOrder(orderVo);
                return toResponsSuccess("取消成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 确认收货
     */
    @GetMapping("confirmOrder")
    public Object confirmOrder(@LoginUser UserVo loginUser, Long orderId) {
        try {
            if (null == orderId) {
                JSONObject params = getJsonRequest();
                orderId = params.getLong("orderId");
            }
            orderService.confirmOrder(orderId);
            return toResponsSuccess("取消成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 跟踪快递轨迹
     */
    @GetMapping("getLogistics")
    public Object getLogistics(Long orderId) {
        Map resultObj = new HashMap();
        Map map = new HashMap();
        OrderVo orderInfo = orderService.queryObject(orderId);
        if (null == orderInfo) {
            return toResponsObject(400, "订单不存在", "");
        }
        List<WuliuVo> wuliuList = new ArrayList<WuliuVo>();

        if((orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())
                || orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem()))
                && orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_301.getItem())){
            WuliuVo vo = new WuliuVo();
            vo.setAcceptStation("交易完成，用户已提走");
            wuliuList.add(vo);
        }
        if(!orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())) {
            if (!StringUtils.isEmpty(orderInfo.getShipping_code()) && !StringUtils.isEmpty(orderInfo.getShipping_no())) {
                // 快递
                JSONObject Traces = apiKdniaoService.getOrderTracesByJson(orderInfo.getShipping_code(), orderInfo.getShipping_no());
                List<Map> mapList = (List<Map>) Traces.get("Traces");
                for (int i = 0; i < mapList.size(); i++) {
                    WuliuVo vo = new WuliuVo();
                    vo.setAcceptTime((String) mapList.get(i).get("AcceptTime"));
                    vo.setAcceptStation((String) mapList.get(i).get("AcceptStation"));
                    wuliuList.add(vo);
                }

                String State = (String) Traces.get("State"); //物流状态：2-在途中,3-签收,4-问题件
                String Reason = (String) Traces.get("Reason");
                if (Dict.logisticsStatus.item_0.getItem().equalsIgnoreCase(State)) {
                    WuliuVo wuliuVo = new WuliuVo();
                    wuliuVo.setAcceptStation(Reason);
                    wuliuList.add(wuliuVo);
                }
                map.put("State", Traces.get("State")); //物流状态：2-在途中,3-签收,4-问题件
                map.put("Reason", Traces.get("Reason"));
            }
        }
        OrderProcessRecordEntity entity = orderProcessRecordService.queryObjectByOrderSn(orderInfo.getOrder_sn());
        if(entity !=null){
            if(Dict.isSend.item_1.getItem().equalsIgnoreCase(entity.getIsCustomsSend())){
                WuliuVo wuliuVo = new WuliuVo();
                wuliuVo.setAcceptStation("订单清关完成，等待仓库发货");
                wuliuVo.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getCustomsSuccTime()));
                wuliuList.add(wuliuVo);
            }
            if(Dict.isSend.item_1.getItem().equalsIgnoreCase(entity.getIsPaymentSend())){
                WuliuVo wuliuVo = new WuliuVo();
                wuliuVo.setAcceptStation("订单支付成功，等待海关清关");
                wuliuVo.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getPaySuccTime()));
                wuliuList.add(wuliuVo);
            }
            if(Dict.isSend.item_1.getItem().equalsIgnoreCase(entity.getIsAddOrderSend())){
                WuliuVo wuliuVo = new WuliuVo();
                wuliuVo.setAcceptStation("订单提交成功");
                wuliuVo.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getAddOrderSuccTime()));
                wuliuList.add(wuliuVo);
            }
        }
        map.put("TracesList",wuliuList);
        map.put("LogisticCode", orderInfo.getShipping_no());
        map.put("ShipperCode",  orderInfo.getShipping_code());
        resultObj.put("wuliu", map);
        return toResponsSuccess(resultObj);
    }

    /**
     * 申请退款
     * @param loginUser
     * @return
     */
    @PostMapping("saveApplyRefund")
    public Object saveApplyRefund(@LoginUser UserVo loginUser) {
        try {
            JSONObject json = getJsonRequest();
            String orderId = json.getString("orderId");
            String merchOrderSn = json.getString("merchOrderSn");
            String refundReason = json.getString("refundReason");
            List<OrderVo> list = orderService.queryObjectByMerchOrderSn(merchOrderSn);
            OrderVo orderInfo = null;
            if(list!=null && list.size()>0){
                for (OrderVo vo: list) {
                    if(Long.valueOf(orderId).equals(vo.getId())){
                        orderInfo = vo;
                    }
                }
            }
            if (null == orderInfo) {
                return toResponsObject(400, "订单不存在", "");
            }
//            OrderVo orderVo = new OrderVo();
//            orderVo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_400.getItem()));
//            orderVo.setId(orderInfo.getId());
//            orderService.update(orderVo);//修改状态为维权申请中
            MallOrderRefund mallOrderRefund = apiOrderRefundService.queryObjectByOrderId(orderInfo.getId()+"");
            MallOrderRefund orderRefund = new MallOrderRefund();
            orderRefund.setOrderId(Integer.parseInt(orderId));
            orderRefund.setUserId(Integer.parseInt(orderInfo.getUser_id()+""));
            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_1.getItem()));
            orderRefund.setRefundReason(refundReason);
            orderRefund.setModTime(new Date());
            if(list.size()>1){//多条订单
                orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
            }
            orderRefund.setRefundMoney(orderInfo.getActual_price());

            if(mallOrderRefund !=null){
                orderRefund.setId(mallOrderRefund.getId());
                apiOrderRefundService.update(orderRefund);
            }else{
                orderRefund.setCreateTime(new Date());
                apiOrderRefundService.save(orderRefund);
            }
            return toResponsMsgSuccess("退款申请成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }
}