package com.iamberry.rent.handlers.admin;

import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.CashLog;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.reback.RebackInfo;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.rent.face.order.RentOrderService;
import com.iamberry.wechat.core.entity.OrderUtil;
import com.iamberry.wechat.core.entity.order.MessageDto;
import com.iamberry.wechat.core.entity.order.OrderActionDto;
import com.iamberry.wechat.core.entity.rent.RentOrder;
import com.iamberry.wechat.core.entity.rent.RentOrderDTO;

@Controller
@RequestMapping("admin/rent_order")
public class AdminRentOrderHandler {
    @Autowired
    RentOrderService rentOrderService;
    @Autowired
    private OrderUtil orderUtil;
    /**
     * 订单列表页    后台
     * 2017年3月16日
     * @author muzx
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/list")
    public ModelAndView listRentOrder( 
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO,
            OrderActionDto actionDto,
            HttpServletRequest request) throws Exception{
        ModelAndView mv = new ModelAndView("admin/reserve/order/list");
        String rentStatus = request.getParameter("orderStatus");
       
        //url需要进行拼接，拼接的内容是页面上的时间条件
        StringBuilder url = new StringBuilder("/admin/rent_order/list?orderStatus=" + actionDto.getOrderStatus());
        //分页并带条件查询接收参数
        RentOrderDTO rentOrderDTO = new RentOrderDTO();        
        if (StringUtils.isNotEmpty(actionDto.getText())) {
            mv.addObject("text", actionDto.getText());
            url.append("&text=" + actionDto.getText());
            rentOrderDTO.setRentOrderId(actionDto.getText());
        }
        if (StringUtils.isNotEmpty(actionDto.getProbationSendName())) {
            rentOrderDTO.setRentAddressName(actionDto.getProbationSendName());
            mv.addObject("probationSendName", actionDto.getProbationSendName());
            url.append("&probationSendName=" + actionDto.getProbationSendName());
        }
        if (StringUtils.isNotEmpty(actionDto.getProbationSendTel())) {
            rentOrderDTO.setRentAddressTel(actionDto.getProbationSendTel());
            mv.addObject("probationSendTel", actionDto.getProbationSendTel());
            url.append("&probationSendTel=" + actionDto.getProbationSendTel());
        }
        if (StringUtils.isNotEmpty(actionDto.getSendAddress())) {
            rentOrderDTO.setRentAddressInfo(actionDto.getSendAddress());
            mv.addObject("sendAddress", actionDto.getSendAddress());
            url.append("&sendAddress=" + actionDto.getSendAddress());
        }
        url.append("&pageSize=" + pageSize + "&pageNO=");
        
        if (rentStatus == null || "".equals(rentStatus)) {
            rentStatus = "paySuccess";
        }
        // 订单状态，数字标识
        int status = -1;
        if (!rentStatus.equals("allOrder")) {
            status = orderUtil.getOrderStatusByStr(rentStatus);
        }
        rentOrderDTO.setRentStatus(status);
        rentOrderDTO.getPage().setPageSize(pageSize);
        rentOrderDTO.getPage().setPageNumber(pageNO);
        Map<String, Object> map = rentOrderService.listRentOrder(rentOrderDTO);
        List<RentOrderDTO> dtoList = (List<RentOrderDTO>) map.get("list");
       
        // 订单是否按照状态查询的, 用于页面
        for (RentOrderDTO orders : dtoList) {
            // 获取用户的操作权限
            orders.setOperations(orderUtil.rentOrderStatusToOperation(orders.getRentStatus(), orders.getRentOrderId()));
            if (status == -1) {
                mv.addObject("orderListIsStatus", false);
                orders.setOrderLinkStatus(orderUtil.orderStatusToString(orders.getRentStatus())); // 订单状态描述，中文
            }else{
                mv.addObject("orderListIsStatus", true);
            }
        }

        int count = (int) map.get("countOrder");
        int pageCount =  count % rentOrderDTO.getPage().getPageSize() == 0 ? count/rentOrderDTO.getPage().getPageSize():(count/rentOrderDTO.getPage().getPageSize()) + 1;
        //分页用
        mv.addObject("orderList", dtoList);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", pageCount);
        mv.addObject("rentStatus", status);// 订单状态
        mv.addObject("url", url);
        mv.addObject("orderStatusStr", orderUtil.orderStatusIntToOrderStatusString(status));// 订单状态描述（用于选中订单头）
        mv.addObject("orderLinkStatus", orderUtil.orderStatusToString(status));// 订单状态描述，中文（显示给用户看）
        mv.addObject("statusUrl", "/admin/rent_order/list?bid=&sid=");
        return mv;
    }
    
    /**
     * 操作订单
     * @return
     * @throws Exception 
     */
    @RequestMapping("/{action}/{orderId}")
    public synchronized ModelAndView actionOrder(
            @PathVariable("action") String action,
            @PathVariable("orderId") String orderId,
            OrderActionDto actionDto
            ) throws Exception {
        ModelAndView mv = new ModelAndView("admin/msg/msg");
        RentOrder rentOrder = new RentOrder();
        rentOrder.setRentOrderId(orderId);
        rentOrder.setRentPostFirm(actionDto.getPostFirm());
        rentOrder.setRentPostNum(actionDto.getPostNum());
        
        // 判断当前的订单，是否支持希望进行的操作
        RentOrder order = rentOrderService.getRentOrderByOrderId(rentOrder);
        order.setRentPostFirm(actionDto.getPostFirm());
        order.setRentPostNum(actionDto.getPostNum());
        rentOrder.setRentOldStatus(order.getRentStatus());
        if (!orderUtil.orderStatusIntToOrderStatusString(order.getRentStatus()).equals(actionDto.getOrderStatus())) {
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，当前订单状态不支持此操作!请确定后重试!"));
            return mv;
        }
        switch (order.getRentStatus()) {
            case 0: // 取消的订单，不支持任何修改订单状态的操作
                return mv;
            case 1: // 待支付（管理员存在操作权限：取消订单，如果取消订单，订单状态修改为0）
                return mv;
            case 2: // 已支付、待发货（管理员的操作为：确认发货）
                mv = checkOrderOperation1(action, actionDto, 2, 5);
                if (!(boolean)mv.getModel().get("status"))  return mv;
                // 执行修改操作
                rentOrder.setRentStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                rentOrder.setRentSendDate(new Date());
                if(rentOrderService.deliverOrderByOrderId(rentOrder)){
                    mv.addObject("msgObj", new MessageDto(true, "操作成功", "发货成功!"));
                }else{
                    mv.addObject("msgObj", new MessageDto(false, "对不起，订单发货失败", "对不起，订单发货失败，请稍后重试！"));
                }
                return mv;
            case 3: // 退款申请中（管理员可以操作：确认退款、驳回退款）
                mv = checkOrderOperation2(action, actionDto, 4, 5, 2, 4);
                if (!(boolean)mv.getModel().get("status"))  return mv;
                order.setRentStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                order.getList().get(0).setItemStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                try {
                    boolean flag = rentOrderService.rentReturnMoneyRentOrder(order);
                    if(flag){
                        if(orderUtil.orderStatusIntToOrderStatusString(4).equals(actionDto.getToOrderStatus())){
                            mv.addObject("msgObj", new MessageDto(true, "订单申请退款成功", "同意订单：" + orderId + "退款!"));
                        }else{
                            mv.addObject("msgObj", new MessageDto(true, "驳回退款成功!", "订单：" + orderId + "退款被驳回,状态返回已支付、待发货!"));
                        }
                    }else {
                        mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                    }
                } catch (IllegalArgumentException e){
                    mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "微信企业转账失败,请确认余额是否充足！"));
                }finally {
                    return mv;
                }
            case 4: // 已退款（管理员通过申请退款，此时订单任何人不能操作）
                return mv;
            case 5: // 已发货（管理员不具有权限）
                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，已发货的订单不能操作!"));
                return mv;
            case 6: // 申请退货中（只有管理员能操作 : 确认退货）
                mv = checkOrderOperation2(action, actionDto, 6, 10, 5, 7);
                if (!(boolean)mv.getModel().get("status"))  return mv;
                // 执行修改操作
                order.setRentStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                order.getList().get(0).setItemStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                if (rentOrderService.updateOrderStatusAndItemStatus(order)) {
                    if(orderUtil.orderStatusIntToOrderStatusString(7).equals(actionDto.getToOrderStatus())){
                        mv.addObject("msgObj", new MessageDto(true, "订单申请退货成功", "恭喜您！同意订单：" + orderId + "退货，等待收到货物后确认退货!"));
                    }else{
                        mv.addObject("msgObj", new MessageDto(true, "成功驳回订单退货", "订单：" + orderId + "退货被驳回,状态返回已发货!"));
                    }
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，处理订单退货失败", "对不起，处理订单退货失败，请稍后重试！"));
                }
                return mv;
            case 7: // 退货中（管理员具有操作能力:确认退货）
                mv = checkOrderOperation1(action, actionDto, 7, 8 );
                if (!(boolean)mv.getModel().get("status"))  return mv;
                // 执行修改操作
                order.setRentStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                order.getList().get(0).setItemStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                if (rentOrderService.updateReturnRentOrder(order)) {
                    mv.addObject("msgObj", new MessageDto(true, "确认订单退货成功", "恭喜您！同意订单：" + orderId + "退货，订单关闭!"));
                    return mv;
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，订单退货失败", "对不起，订单退货失败，请稍后重试！"));
                    return mv;
                }
            case 8: // 订单退货，订单关闭（管理员收到货后，确认退货，订单状态修改为此，订单不对外提供操作能力）
                return mv;
            case 9: // 换货中（管理员对申请换货的订单，确认换货时，订单状态为此，此时只有管理员具有操作权限，只能确认换货，录入物流信息）
                mv = checkOrderOperation1(action, actionDto,9, 5);
                if (!(boolean)mv.getModel().get("status"))  return mv;

                order.setRentStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                if (rentOrderService.deliverOrderByOrderId(order)) {
                    mv.addObject("msgObj", new MessageDto(true, "订单发货成功", "恭喜您！订单：" + orderId + "订单发货成功!"));
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，订单发货失败", "对不起，订单发货失败，请稍后重试！"));
                }
                return mv;
            case 10: // 换货完成，当用户对换货中的订单，点击确认换货时，并录入物流信息，此订单进入已发货状态
                
                break;
            case 11: // 在订单为已发货时，用户具有的权限，用户申请换货
                mv = checkOrderOperation2(action, actionDto, 8, 11,9, 5);
                if (!(boolean)mv.getModel().get("status"))  return mv;

                // 执行修改操作
                order.setRentStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                order.getList().get(0).setItemStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
                order.setRentPostFirm(actionDto.getPostFirm());
                order.setRentPostNum(actionDto.getPostNum());
                if (rentOrderService.opertionRentExchangeOrder(order)) {
                    if(orderUtil.orderStatusIntToOrderStatusString(9).equals(actionDto.getToOrderStatus())){
                        mv.addObject("msgObj", new MessageDto(true, "同意换货成功", "恭喜您！同意订单：" + orderId + "换货，请收货后录入物流信息并同意换货!"));
                    }else{
                        mv.addObject("msgObj", new MessageDto(true, "驳回换货成功", "您已驳回订单：" + orderId + "换货，订单状态改为已发货!"));
                    }
                    return mv;
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，订单换货失败", "对不起，订单换货失败，请稍后重试！"));
                    return mv;
                }
            default: // 报错
                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误!"));
        }
        return mv;
    }

    /**
     * 订单操作校验
     * @param action
     * @param actionDto
     * @param actionId
     * @param toOrderStatus
     * @return
     */
    private ModelAndView checkOrderOperation1(String action, OrderActionDto actionDto, int actionId, int toOrderStatus){
        ModelAndView mv = new ModelAndView("admin/msg/msg");
        // 判断当前请求操作是否相符, 否则提示不成功
        if (!orderUtil.getOrderActin()[actionId].equals(action)) {
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            mv.addObject("status", false);
            return mv;
        }

        // 判断请求修改的订单状态是否相符，否则提示不成功
        if (!orderUtil.orderStatusIntToOrderStatusString(toOrderStatus).equals(actionDto.getToOrderStatus())) {
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            mv.addObject("status", false);
            return mv;
        }
        mv.addObject("status", true);
        return mv;
    }

    private ModelAndView checkOrderOperation2(String action, OrderActionDto actionDto,
             int action1, int action2, int toOrderStatus1, int toOrderStatus2){
        ModelAndView mv = new ModelAndView("admin/msg/msg");
        if ((!orderUtil.getOrderActin()[action1].equals(action))
                && (!orderUtil.getOrderActin()[action2].equals(action))) {// 判断当前请求操作是否相符, 否则提示不成功
            mv.addObject("status", false);
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            return mv;
        }

        if ((!orderUtil.orderStatusIntToOrderStatusString(toOrderStatus1).equals(actionDto.getToOrderStatus())) &&
                (!orderUtil.orderStatusIntToOrderStatusString(toOrderStatus2).equals(actionDto.getToOrderStatus()))){
            mv.addObject("status", false);
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            return mv;
        }
        mv.addObject("status", true);
        return mv;
    }
}
