package com.iamberry.rent.handlers.admin;

import bsh.StringUtil;
import com.iamberry.rent.face.machine.MachineService;
import com.iamberry.wechat.core.entity.RentFilterUtil;
import com.iamberry.wechat.core.entity.order.MessageDto;
import com.iamberry.wechat.core.entity.order.OrderActionDto;
import com.iamberry.wechat.core.entity.rent.MachineShare;
import com.iamberry.wechat.core.entity.rent.RentChangeLogs;
import org.apache.commons.lang.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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/admin_machine")
public class AdminMachineHandler {
    
    @Autowired
    private MachineService machineService;
    @Autowired
    private RentFilterUtil rentFilterUtil;
    
    /**
     * 机器分享记录后台
     * 2017年3月20日
     * @author muzx
     * @param pageSize
     * @param pageNO
     * @param request
     * @return
     */
    @RequestMapping("/share_list")
    public ModelAndView listMachineShare(
            @RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
            @RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO,
            HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/admin/reserve/machine/list");
        MachineShare share = new MachineShare();
        share.getPage().setPageSize(pageSize);
        share.getPage().setPageNumber(pageNO);
        List<MachineShare> shareList = machineService.listMachineShareAdmin(share);
        int count = machineService.countMachineShare(share);
        int pageCount =  count % share.getPage().getPageSize() == 0 ? count/share.getPage().getPageSize():(count/share.getPage().getPageSize()) + 1;
        mv.addObject("shareList", shareList);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", pageCount);
        mv.addObject("url", "/admin/admin_machine/share_list?pageSize=" + pageSize + "&pageNO=");
        return mv;
    }

    /**
     * 分页查询更换滤芯记录
     * @param request
     * @param pageSize
     * @param pageNO
     * @return
     * @throws Exception
     */
    @RequestMapping("/list_change_filter")
    public ModelAndView listChangeFilter(HttpServletRequest request,
    		@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
            @RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) throws Exception {
        ModelAndView mv = new ModelAndView("/admin/reserve/machine/filterList");
    	StringBuilder url = new StringBuilder("/admin/admin_machine/list_change_filter?pageSize=" + pageSize);

        RentChangeLogs logs = new RentChangeLogs();
        String filterStatus = request.getParameter("filterStatus");
        if (filterStatus == null || "".equals(filterStatus)) {
            filterStatus = "inFilter";
        }
        String logsOrderId = request.getParameter("logsOrderId");
        if (StringUtils.isNotEmpty(logsOrderId)) {
            logs.setLogsOrderId(logsOrderId);
            mv.addObject("logsOrderId",logsOrderId);
            url.append("&logsOrderId=" + logsOrderId);
        }
        String logsAddressName = request.getParameter("logsAddressName");
        if (StringUtils.isNotEmpty(logsAddressName)) {
            logs.setLogsAddressName(logsAddressName);
            mv.addObject("logsAddressName",logsAddressName);
            url.append("&logsAddressName=" + logsAddressName);
        }
        String logsAddressTel = request.getParameter("logsAddressTel");
        if (StringUtils.isNotEmpty(logsAddressTel)) {
            logs.setLogsAddressTel(logsAddressTel);
            mv.addObject("logsAddressTel",logsAddressTel);
            url.append("&logsAddressTel=" + logsAddressTel);
        }
        String logsAddressInfo = request.getParameter("logsAddressInfo");
        if (StringUtils.isNotEmpty(logsAddressInfo)) {
            logs.setLogsAddressInfo(logsAddressInfo);
            mv.addObject("logsAddressInfo",logsAddressInfo);
            url.append("&logsAddressInfo=" + logsAddressInfo);
        }
        // 订单状态，数字标识
        int status = -1;
        if (!filterStatus.equals("allFilter")) {
            status = rentFilterUtil.getFilterStatusByStr(filterStatus);
        }
        logs.setLogsStatus(status);
    	 logs.getPage().setPageNumber(pageNO);
    	 logs.getPage().setPageSize(pageSize);
    	 logs.getPage().initRecordBegin();
    	 //根据条件查询更换滤芯集合
    	 List<RentChangeLogs> changeList = machineService.listChangeFilterLogs(logs);
         if (changeList != null && changeList.size() > 0) {
             for (RentChangeLogs filter : changeList) {
                 filter.setRentUserNickName(URLDecoder.decode(filter.getRentUserNickName(),"UTF-8"));
                 if (status == -1) {
                     mv.addObject("orderListIsStatus", false);
                     // 获取用户的操作权限
                     filter.setOperations(rentFilterUtil.filterStatusToOperation(filter.getLogsStatus(), filter.getLogsId()));
                     filter.setOrderLinkStatus(rentFilterUtil.filterStatusToString(filter.getLogsStatus())); // 滤芯状态描述，中文
                 } else {
                     mv.addObject("orderListIsStatus", true);
                     // 获取用户的操作权限
                     filter.setOperations(rentFilterUtil.filterStatusToOperation(filter.getLogsStatus(), filter.getLogsId()));
                 }
             }
         }
         url.append("&pageNO=");
        mv.addObject("changeList", changeList);
        mv.addObject("filterStatus",status);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", machineService.getChangeFilterCount(logs));
        mv.addObject("statusUrl", "/admin/admin_machine/list_change_filter?bid=&sid=");
        mv.addObject("url", url.toString());
        mv.addObject("orderStatusStr", rentFilterUtil.filterStatusIntToOrderStatusString(status));// 订单状态描述（用于选中订单头）
        mv.addObject("orderLinkStatus", rentFilterUtil.filterStatusToString(status));// 订单状态描述，中文（显示给用户看）
        return mv;
    }

    /**
     * 操作订单
     * @return
     * @throws Exception
     */
    @RequestMapping("/{action}/{orderId}")
    public synchronized ModelAndView actionOrder(
            @PathVariable("action") String action,
            @PathVariable("orderId") Integer filterId,
            OrderActionDto actionDto
    ) throws Exception {
        ModelAndView mv = new ModelAndView("admin/msg/msg");
        RentChangeLogs logs = new RentChangeLogs();
        logs.setLogsId(filterId);
        // 订单状态，数字标识
        logs.setLogsPostFirm(actionDto.getPostFirm());
        logs.setLogsPostNum(actionDto.getPostNum());
        // 判断当前的订单，是否支持希望进行的操作
        List<RentChangeLogs> filterList = machineService.listSelectChangeLogs(logs);
        if (filterList == null || filterList.size() <= 0) {
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            return mv;
        }
        RentChangeLogs filter = filterList.get(0);
        Integer filterStatus = filter.getLogsStatus();
        logs.setLogsOldStatus(filterStatus);
        if (!rentFilterUtil.filterStatusIntToOrderStatusString(filterStatus).equals(actionDto.getOrderStatus())) {
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            return mv;
        }
        switch (filterStatus) {
            case 0: // 取消的订单，不支持任何修改订单状态的操作

                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，取消的订单不能操作!"));
                return mv;
            case 1: // 更换申请中（管理员存在操作权限：同意申请）

                // 只有两种操作 : 取消、同意
                if (rentFilterUtil.getFilterActin()[0].equals(action)) {
                    // 取消更换记录
                    if (!rentFilterUtil.filterStatusIntToOrderStatusString(0).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
                        mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                        return mv;
                    }
                    logs.setLogsStatus(0);
                    if (machineService.updateChangeLogsById(logs)) {// 驳回退款
                        mv.addObject("msgObj", new MessageDto(true, "取消订单成功!", "订单取消成功，订单即将封存!"));
                        return mv;
                    } else {
                        mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，对不起，取消订单失败，请稍后重试！"));
                        return mv;
                    }
                } else if (rentFilterUtil.getFilterActin()[4].equals(action)) {
                    // 同意换货

                    if (!rentFilterUtil.filterStatusIntToOrderStatusString(2).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
                        mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                        return mv;
                    }
                    logs.setLogsStatus(2);
                    if (machineService.updateChangeLogsById(logs)) {
                        //根据orderId查询订单所有信息
                        mv.addObject("msgObj", new MessageDto(true, "滤芯换货成功", "恭喜您!滤芯换货成功，即将为您发货!"));
                        return mv;
                    } else {
                        mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                        return mv;
                    }
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                    return mv;
                }
            case 2: // 更换中（管理员的操作为：确认发货）

                if (!rentFilterUtil.getFilterActin()[2].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
                    mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                    return mv;
                }
                if (!rentFilterUtil.filterStatusIntToOrderStatusString(4).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
                    mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
                    return mv;
                }
                // 执行修改操作
                logs.setLogsStatus(rentFilterUtil.getFilterStatusByStr(actionDto.getToOrderStatus()));
                logs.setLogsSendTime(new Date());
                if (machineService.updateChangeLogsById(logs)) {
                    mv.addObject("msgObj", new MessageDto(true, "操作成功", "订单发货成功!"));
                    return mv;
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，订单发货失败", "对不起，取消订单失败，请稍后重试！"));
                    return mv;
                }
            case 3: // 驳回

                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，已发货的订单不能操作!"));
                return mv;
            case 4: // 已发货

                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，已退款的订单不能操作!"));
                return mv;
            case 5: // 已完成

                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，已发货的订单不能操作!"));
                return mv;
            default: // 报错

                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误!"));
                return mv;
        }
    }

    /**
     *获取订单详情
     * @param request
     * @param filterId
     * @return
     */
    @ResponseBody
    @RequestMapping("/getFilterById/{orderId}")
    public ModelAndView getFilterById(HttpServletRequest request,
           @PathVariable("orderId") Integer filterId) throws Exception {
        ModelAndView mv = new ModelAndView("/admin/reserve/machine/filterInfo");
        RentChangeLogs logs = new RentChangeLogs();
        logs.setLogsId(filterId);
        //根据id查询滤芯更换记录
        List<RentChangeLogs> filterList = machineService.listChangeFilterLogs(logs);
        if (filterList == null) {
            mv.setViewName("admin/msg/msg");
            mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
            return mv;
        }
        logs = filterList.get(0);
        logs.setRentUserNickName(URLDecoder.decode(logs.getRentUserNickName(),"UTF-8"));
        mv.addObject("logs",logs);
        return mv;
    }
}
