package com.sifang.modules.order.controller;

        import com.alibaba.fastjson.JSONObject;
        import com.google.common.collect.Lists;
        import com.google.common.collect.Maps;
        import com.jfinal.plugin.activerecord.Db;
        import com.jfinal.plugin.activerecord.Record;
        import com.sifang.modules.order.dao.OrdeCallbackDao;
        import com.sifang.modules.order.dao.OrderCollectionsDao;
        import com.sifang.modules.order.dao.OrderDao;
        import com.sifang.modules.platform.service.AddressService;
        import com.sifang.modules.sunshine.SystemSetting.service.OrderMarkSettingService;
        import com.sifang.modules.sunshine.SystemSetting.utils.CustomException;
        import com.sifang.modules.sunshine.SystemSetting.utils.Result;
        import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
        import com.sifang.modules.sunshine.fittingManager.service.FittingApplyService;
        import com.sifang.modules.platform.controller.form.ComplaintReply;
        import com.sifang.modules.platform.utils.AddressUtils;
        import com.sifang.modules.platform.utils.PlantformUtils;
        import com.sifang.modules.platform.utils.JSONAppendUtils;
        import com.sifang.modules.order.entity.CrmOrder;
        import com.sifang.modules.order.entity.OrderCallback;
        import com.sifang.modules.order.service.*;
        import com.sifang.modules.order.utils.OrderUtils;
        import com.sifang.modules.order.utils.Target;
        import com.sifang.modules.sys.common.UserUtils;
        import com.sifang.modules.sys.common.entity.User;
        import com.sifang.modules.sys.common.utils.DateUtils;
        import com.sifang.modules.sys.util.CrmUtils;
        import com.sifang.modules.sys.util.LayuiPage;
        import com.sifang.modules.sys.web.BaseController;
        import org.apache.commons.lang3.StringUtils;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Controller;
        import org.springframework.ui.Model;
        import org.springframework.web.bind.annotation.RequestBody;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.ResponseBody;
        import org.springframework.web.multipart.MultipartFile;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;
        import java.util.List;
        import java.util.Map;


/**
 *工单信息控制类
 * @author lzp
 * @version 2019-11-13
 */
@Controller
@RequestMapping(value = "${adminPath}/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderFeedbackService feedbackService;

    @Autowired
    private OrderMarkSettingService markSettingService;

    @Autowired
    SiteSettlementRecordService siteSettlementRecordService;

    @Autowired
    CrmOrderDispatchService orderDispatchService;

    @Autowired
    private OrderCollectionsDao orderCollectionsDao;
    @Autowired
    private OrdeCallbackService callService;

    @Autowired
    private OrdeCallbackDao ordeCallbackDao;
    @Autowired
    private FittingApplyService fittingApplyService;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    AddressService addressService;


    /**
     * 跳转发布工单页面
     * type 根据不同的类型到不同的页面
     */
    @RequestMapping(value = "orderForm")
    public String orderForm(HttpServletRequest request){
        return "modules/order/issueOrder";
    }



    /**
     * 保存工单信息
     * 平台端有使用
     */
    @ResponseBody
    @RequestMapping(value = "saveOrder")
    public Object saveOrder(@RequestBody String str,HttpServletRequest request, HttpServletResponse response){
        System.out.println("保存数据!");
        User user = UserUtils.getUser();
        Result result = new Result();
        JSONObject object= JSONObject.parseObject(str);
        CrmOrder order=JSONObject.toJavaObject(object,CrmOrder.class);
        Map<String,String> map = getParams(request);
        Boolean flag=orderService.checkBlack(order);
        if(!flag){
            result.setCode("202");
            return  result;
        }
        try{
            return orderService.SaveOrder(order,user);
        } catch (CustomException m) {
            m.printStackTrace();
            result.setCode(m.getCode());
            result.setMsg(m.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("505");
            throw e;
        }
        return result;
    }


    /**
     * 平台端保存修改的工单信息
     */
    @ResponseBody
    @RequestMapping(value = "saveUpdate")
    public Object saveUpdate(@RequestBody String str,HttpServletRequest request){
        System.out.println("保存数据!");
        Result onjicr = new Result();
        try {
            JSONObject object= JSONObject.parseObject(str);
            CrmOrder order=JSONObject.toJavaObject(object,CrmOrder.class);
            return orderService.updateOrder(order,UserUtils.getUser());
        } catch (CustomException m) {
            m.printStackTrace();
            onjicr.setCode(m.getCode());
        }catch (Exception e){
            e.printStackTrace();
            onjicr.setCode("505");
            throw e;
        }
        return  onjicr;
    }







    /**工单详情
     */
    @RequestMapping(value = "getOrderForm")
    public String getOrderForm(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        String type = request.getParameter("type");
        CrmOrder order = orderService.getOrderById(orderId);
        model.addAttribute("order",order);
        model.addAttribute("type",type);
        //获取新建、旧件返厂信息
        //  User user = UserUtils.getUser();

        /*    //获取备件申请信息
            List<Record> applyInfo = orderService.getOrderFittingByorderId(orderId,"");
            if(applyInfo.size()>0){
                model.addAttribute("applyInfo",applyInfo);
            }*/
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
           /* //购买渠道
            List<Record> mall = OrderUtils.getOrderMall();
            model.addAttribute("mall",mall);*/
        String province = order.getProvince();
        String city = order.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys",citys);
        model.addAttribute("areas",areas);
        String status = order.getStatus();
        // 反馈信息
        Map<String, Object> feedbackInfo = feedbackService.getOrderFeedbackRecords(orderId);
        model.addAttribute("feedbackInfo", feedbackInfo);
        if(CrmOrder.ORDERTYPETWO.equals(status)){
            //服务中
            return "modules/order/factory/orderForm";
        }else if(CrmOrder.FOUR.equals(status) || CrmOrder.FIVE.equals(status)){
            //回访信息
            OrderCallback call = callService.getOrderCallbackByOrderId(orderId);

            model.addAttribute("call",call);

            return "modules/order/factory/historyOrderForm";
        }
        //默认
        return "modules/order/orderForm";
    }

    /**
     * 修改工单
     * 只有status为1的时候才可以修改
     */
    @RequestMapping(value = "getUpdateOrderForm")
    public String getUpdateOrderForm(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");

        CrmOrder order = orderService.getOrderById(orderId);
        model.addAttribute("order",order);
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
        String province = order.getProvince();
        String city = order.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys",citys);
        model.addAttribute("areas",areas);
        return "modules/order/updateOrderForm";
    }


    /**
     * 修改工单保存
     * 只有品牌上修改保存
     */
    @ResponseBody
    @RequestMapping(value = "updateOrder")
    public Object updateOrder(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        Result result = new Result();
        try {
            CrmOrder order = new CrmOrder();
            order.setId(map.get("id"));

            order.setCustomerName(map.get("customerName"));
            order.setCustomerMobile(map.get("customerMobile"));
            order.setCustomerTelephone(map.get("customerTelephone"));
            order.setProvince(map.get("province"));
            order.setCity(map.get("city"));
            order.setArea(map.get("area"));
            order.setApplianceModel(map.get("applianceModel"));
            order.setApplianceBarcode(map.get("applianceBarcode"));
            order.setApplianceBuyTime(StringUtil.isNotBlank(map.get("applianceBuyTime"))? DateUtils.parseDate(map.get("applianceBuyTime")) : null);
            order.setRemarks(map.get("remarks"));
            order.setCustomerAddress(map.get("customerAddress"));
            return orderService.updateOrder(order,UserUtils.getUser());
        }  catch (CustomException m) {
            m.printStackTrace();
            result.setCode(m.getCode());
            result.setMsg(m.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("505");
            throw e;
        }
        return result;
    }


    /**
     * 根据手机号查询历史工单数量
     */
    @ResponseBody
    @RequestMapping(value = "getOrderCountByMobile")
    public Object getOrderCountByMobile(HttpServletRequest request){
        String mobile = request.getParameter("mobile");
        if(StringUtils.isBlank(mobile)){
            return "205";
        }
        return OrderUtils.getOrderCountByMobile(mobile);
    }


    /**
     * 根据手机号查询历史工单
     */
    @ResponseBody
    @RequestMapping(value = "getOrderByMobile")
    public Object getOrderByMobile(HttpServletRequest request){
        String mobile = request.getParameter("mobile");
        if(StringUtils.isBlank(mobile)){
            return "205";
        }
        return OrderUtils.getOrderByMobile(mobile);
    }

    /**
     * 查看工单过程信息
     */
    @RequestMapping(value = "getOrderDetail")
    @ResponseBody
    public Object getOrderDetail(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        if(StringUtil.isBlank(orderId)){
            return null;
        }
        User user = UserUtils.getUser();
        List<Target> list = orderService.getOrderDetail(orderId);
        List<Target> rds = Lists.newArrayList();
        if("2".equals(user.getUserType())){
            for(Target ta :list){
                String com = ta.getC();
                if(com.indexOf("服务商工单") != -1){
                    //包含，过滤
                }else{
                    rds.add(ta);
                }
            }
        }else{
            return list;
        }

        return rds;
    }


    /**
     *置为无效工单
     * status : 6
     */
    @ResponseBody
    @RequestMapping(value = "invalidOrder")
    public Object invalidOrder(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String description = request.getParameter("description");
        User user  = UserUtils.getUser();
        return orderService.invalidOrder(orderId,user,description);
    }

    /**
     *平台置为无效工单
     * status : 6
     * 只要没完工都可以操作无效
     * status < 3
     */
    @ResponseBody
    @RequestMapping(value = "platformInvalidOrder")
    public Object platformInvalidOrder(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String description = request.getParameter("description");
        User user  = UserUtils.getUser();
        return orderService.platformInvalidOrder(orderId,user,description);
    }

    /**
     * 服务商设置为无效工单
     * site_status : 9
     *
     * status =1 3 4 5 6
     */
    @ResponseBody
    @RequestMapping(value = "siteInvalidOrder")
    public Object siteInvalidOrder(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        String description = request.getParameter("description");
        User user = UserUtils.getUser();
        return orderService.siteInvalidOrder(orderId, user, description);
    }



    /**
     * 平台端查看全部工单信息
     */
    @RequestMapping(value = "getPlatformOrder")
    public String getPlatformOrder(HttpServletRequest request,Model model){
        String psname = request.getParameter("name");
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        model.addAttribute("psname",psname);
        return "modules/order/platform/platformOrderList";
    }

    /**
     * 平台直接封单弹窗 -- 只针对于咨询工单
     * @return
     */
    @RequestMapping("consultOrder")
    public String consultOrder(HttpServletRequest request,Model model){
        String orderId= request.getParameter("orderId");
        model.addAttribute("orderId",orderId);
        return "modules/order/platform/consultOrder";
    }

    /**
     * 平台直接封单保存
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "consultOrderSave")
    public Object consultOrderSave(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String consultOrder = request.getParameter("consultOrder");
        User user  = UserUtils.getUser();
        return orderService.consultOrderSave(orderId,user,consultOrder);
    }

    /**
     * 平台无效工单弹窗
     * @return
     */
    @RequestMapping("lookNOUse")
    public String goToNoUsePop(HttpServletRequest request,Model model){
        String orderId= request.getParameter("orderId");
        String wheremark= request.getParameter("where");
        model.addAttribute("orderId",orderId);
        model.addAttribute("wheremark",wheremark);
        return "modules/order/platform/noUsePop";
    }

    /**
     * 服务商无效工单弹窗
     * @return
     */
    @RequestMapping("siteInvalid")
    public String goTositeInvalid(HttpServletRequest request,Model model){
        String orderId= request.getParameter("orderId");
        String where= request.getParameter("where");
        model.addAttribute("orderId",orderId);
        model.addAttribute("where",where);
        return "modules/order/service/siteInvalid";
    }

    /**
     * 平台端获取全部工单信息
     */
    @ResponseBody
    @RequestMapping(value = "platform/getPlatformOrderPage")
    public Object getPlatformOrderPage(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        orderService.getPlatformOrderPage(page,map);
        return page.renderJson();
    }

    /**
     * 平台查看待派单
     * Tobesent
     */
    @RequestMapping(value = "tobesentOrderList")
    public String tobesentOrder(HttpServletRequest request,Model model){
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/tobesentOrderList";
    }

    /**
     * 待接单
     * WaitingforOrders
     */
    @RequestMapping(value = "getWaitingforOrders")
    public String getWaitingforOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        System.out.println("待接单");
        return "modules/order/platform/waitingforOrders";
    }

    @ResponseBody
    @RequestMapping(value = "platform/waitingforOrders")
    public Object waitingforOrdersPage(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责得省
            Record rd = CrmUtils.getByUserId(user);
            String provices = rd.getStr("provices");
            String is_many = rd.getStr("is_many");
            String city = rd.getStr("city");
            map.put("is_many",is_many);
            map.put("city",city);
            map.put("provices",provices);
        }
        LayuiPage page = new LayuiPage(request);
        orderService.getWaitingforOrdersPage(page,map);
        return page.renderJson();
    }


    @ResponseBody
    @RequestMapping(value = "platform/getPlatformOrderStatus")
    public Object getPlatformOrderStatus(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        String status = request.getParameter("status");
        if(StringUtil.isBlank(status)){
            status ="1";
        }
        orderService.getPlatformOrderStatus(page,map,status);
        return page.renderJson();
    }

    /**
     * 多次回访列表
     */
    @ResponseBody
    @RequestMapping(value = "platform/getManyTimesPlatformOrder")
    public Object getManyTimesPlatformOrder(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        orderService.getManyTimesPlatformOrder(page,map);
        return page.renderJson();
    }

    /**
     * 平台查看服务中工单
     *InService
     */
    @RequestMapping(value = "getInServiceOrders")
    public String getInServiceOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/InServiceOrders";
    }

    /**
     * 平台查看待回访
     *callback
     */
    @RequestMapping(value = "getCallbackOrders")
    public String getCallbackOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/CallbackOrders";
    }

    /**
     * 平台查看多次回访
     *callback
     */
    @RequestMapping(value = "getmanyimesCallbackOrders")
    public String getmanyimesCallbackOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/manyTimesCallbackOrders";
    }

    /**
     * 平台查看待结算
     *callback
     */
    @RequestMapping(value = "getSettlementOrders")
    public String getSettlementOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/SettlementOrders";
    }

    /**
     * 平台查看已完成
     *Completed
     */
    @RequestMapping(value = "getCompletedOrders")
    public String getCompletedOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/CompletedOrders";
    }

    /**
     * 平台查看无效单
     *invalid
     */
    @RequestMapping(value = "getInvalidOrders")
    public String getInvalidOrders(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/InvalidOrdersList";
    }

    /**
     * 平台查看渠道商安装单
     */
    @RequestMapping(value="getChannelBusinessOrders")
    public String getChannelBusinessOrders(HttpServletRequest request,Model model){
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        model.addAttribute("measures",PlantformUtils.getAllMeasutes());
        return "modules/order/platform/channelBusinessOrderList";
    }

    // 平台查看渠道商工单
    @ResponseBody
    @RequestMapping(value = "platform/getChannelBusinessList")
    public Object getChannelBusinessList(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        orderService.getChannelBusinessOrdersPage(page,map);
        return page.renderJson();
    }


    //平台新建渠道商工单页面
    @RequestMapping(value="platform/newChannelBusinessOrderForm")
    public String newChannelBusinessOrderForm(HttpServletRequest request,Model model){
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();
        model.addAttribute("promiseLimit",promiseLimit);
        //服务措施
        model.addAttribute("serviceMeasures",OrderUtils.getOrderServiceMeasures("安装"));
        return "modules/order/platform/addChannelBusinessOrderForm";
    }
    /***
     * 平台保存新建的渠道商工单
     */
    @ResponseBody
    @RequestMapping(value="platform/saveChannelBusinessOrder")
    public Object saveChannelBusinessOrder(@RequestBody String str,HttpServletRequest request, HttpServletResponse response){
        System.out.println("保存数据!");
        User user = UserUtils.getUser();
        Result result = new Result();
        JSONObject object= JSONObject.parseObject(str);
        CrmOrder order=JSONObject.toJavaObject(object,CrmOrder.class);
        Boolean flag=orderService.checkFlag(order);
        if(!flag){
            result.setCode("202");
            return  result;
        }
        try{
            return orderService.saveChannelBusinessOrder(order,user);
        } catch (CustomException m) {
            m.printStackTrace();
            result.setCode(m.getCode());
            result.setMsg(m.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("505");
            throw e;
        }
        return result;
    }

    //平台下查看渠道商工单详情
    @RequestMapping(value="getChannelBusinessOrderDetail")
    public String getChannelBusinessOrderDetail(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        CrmOrder order = orderService.getOrderById(orderId);
        model.addAttribute("order",order);
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();
        model.addAttribute("promiseLimit",promiseLimit);
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
        //服务措施
        model.addAttribute("serviceMeasures",OrderUtils.getOrderServiceMeasures(order.getServiceType()));
        String province = order.getProvince();
        String city = order.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys",citys);
        model.addAttribute("areas",areas);
        String[] arrImages= StringUtil.isBlank(order.getBdImgs())?  null:order.getBdImgs().split(",");
        model.addAttribute("images",arrImages);
        model.addAttribute("imgNumber", StringUtil.isBlank(order.getBdImgs())? "0":arrImages.length);
        return "modules/order/platform/channelBusinessOrderDetailForm";
    }

    //平台保存修改的渠道商工单信息
    @ResponseBody
    @RequestMapping(value="saveUpdateChannelBusinessOrder")
    public Object saveUpdateChannelBusinessOrder(@RequestBody String str,HttpServletRequest request){
        System.out.println("保存数据!");
        Result result = new Result();
        try {
            JSONObject object= JSONObject.parseObject(str);
            CrmOrder order=JSONObject.toJavaObject(object,CrmOrder.class);
            Boolean flag=orderService.checkFlag(order);
            if(!flag){
                result.setCode("202");
                return  result;
            }
            return orderService.UpdateChannelBusinessOrder(order,UserUtils.getUser());
        } catch (CustomException m) {
            m.printStackTrace();
            result.setCode(m.getCode());
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("505");
            throw e;
        }
        return  result;
    }




    /**
     * 备件单
     * getPlatformFittingOrderPage
     */
    @RequestMapping(value = "getFittingOrder")
    public String getFittingOrder(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        return "modules/order/platform/fittingOrderList";
    }

    @ResponseBody
    @RequestMapping(value = "platform/platformFittingOrderPage")
    public Object platformFittingOrderPage(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责得省
            Record rd = CrmUtils.getByUserId(user);
            String is_many = rd.getStr("is_many");
            String city = rd.getStr("city");
            String provices = rd.getStr("provices");
            map.put("provices",provices);
            map.put("city",city);
            map.put("is_many",is_many);
        }
        orderService.getPlatformFittingOrderPage(page,map);
        return page.renderJson();
    }

    /**
     * 投诉单
     * Complaint
     */
    @RequestMapping(value = "getComplaintOrder")
    public String getComplaintOrder(HttpServletRequest request,Model model){
        model.addAttribute("siteList", PlantformUtils.getAllSiteList());
   /*     model.addAttribute("brandList", PlantformUtils.getCrmBrand());
        model.addAttribute("cateList", PlantformUtils.getCrmCategory());*/
        return "modules/order/platform/complaintOrderList";
    }

    @ResponseBody
    @RequestMapping(value = "platform/platformComplaintOrderPage")
    public Object platformComplaintOrderPage(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责得省
            Record rd = CrmUtils.getByUserId(user);
            String is_many = rd.getStr("is_many");
            String city = rd.getStr("city");
            String provices = rd.getStr("provices");
            map.put("provices",provices);
            map.put("is_many",is_many);
            map.put("city",city);
        }
        orderService.getComplaintOrderPage(page,map);
        return page.renderJson();
    }

    @RequestMapping(value = "getFlagOrder")
    public String getFlagOrder(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        model.addAttribute("orderId",orderId);
        model.addAttribute("typeList", markSettingService.getAllMarkType("1"));
        return "modules/order/platform/flagOrder";
    }


    /**
     * 标记工单
     */
    @ResponseBody
    @RequestMapping(value = "flagOrder")
    public Object flagOrder(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String flag = request.getParameter("flag");
        if(StringUtil.isBlank(orderId)){
            return Result.fail("505","工单ID为空");
        }
        return orderService.flagOrder(orderId,flag);
    }

    @RequestMapping(value = "platFormFeedback")
    public String platFormFeedback(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        if(StringUtil.isNotBlank(orderId)){
            CrmOrder or= orderService.getOrderById(orderId);
            //获取服务措施
            List<Record> list = OrderUtils.getOrderServiceMeasures(or.getServiceType());
            model.addAttribute("order",or);
            model.addAttribute("rds",list);

        }
        return "modules/order/platform/feedbackOrder";
    }

    /**
     * 平台端和厂家端--已完成工单进行反馈
     * @param request
     * @return
     */
    @RequestMapping(value = "feedbackOrderYwc")
    public String FeedbackOrderYwc(HttpServletRequest request){
        return "modules/order/platform/feedbackOrderYwc";
    }

    /**
     * 平台下查看工单详情
     */
    @RequestMapping(value = "getplatformOrderForm")
    public String getplatformOrderForm(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        CrmOrder order = orderService.getOrderById(orderId);
        model.addAttribute("order",order);
        //获取新建、旧件返厂信息
        User user = UserUtils.getUser();
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();
        model.addAttribute("promiseLimit",promiseLimit);
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
        //服务措施
        model.addAttribute("serviceMeasures",OrderUtils.getOrderServiceMeasures(order.getServiceType()));

        String province = order.getProvince();
        String city = order.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys",citys);
        model.addAttribute("areas",areas);
        String status = order.getStatus();
        // 反馈信息
        Map<String, Object> feedbackInfo = feedbackService.getOrderFeedbackRecords(orderId);
        model.addAttribute("feedbackInfo", feedbackInfo);
        String[] arrImages= StringUtil.isBlank(order.getBdImgs())?  null:order.getBdImgs().split(",");
        model.addAttribute("images",arrImages);
        model.addAttribute("imgNumber", StringUtil.isBlank(order.getBdImgs())? "0":arrImages.length);
        if(CrmOrder.ORDERTYPE_ONE.equals(status)){
            //待指派工单
            return "modules/order/platform/waitDisOrderForm";
        }
        //跟进记录信息
        String  detail = orderService.getOrderTrackDetail(orderId);
        if(StringUtil.isNotBlank(detail)){
            model.addAttribute("detail", JSONAppendUtils.getProcess(detail));
        }
        //工单的收款凭证
        model.addAttribute("collectionVoucher" ,siteSettlementRecordService.getOrderCollection(orderId));
        if(CrmOrder.ORDERTYPETWO.equals(status)){
            //服务中
            return "modules/order/platform/InServiceOrderForm";
        }
        Record record = Db.findFirst("select * from crm_customer_comment where order_id = ?  limit 1" , orderId);
        model.addAttribute("comment", record);
        if(CrmOrder.ORDERTYPETHREE.equals(status)){
            //待回访
            return "modules/order/platform/callbackOrderForm";
        }
        //回访信息
        model.addAttribute("call", ordeCallbackDao.getOrderCallback(orderId));
        //回访信息模块里面的收款总额
        model.addAttribute("payment",orderCollectionsDao.getOrderPayment(orderId));
        if(CrmOrder.FOUR.equals(status)){
            //待结算
            return "modules/order/platform/callbackOrderForm";
        }
        //服务商结算信息
        Record serrds = siteSettlementRecordService.getOrderSettle(orderId);
        model.addAttribute("serrds",serrds);
        //无效工单
        if(CrmOrder.SIX.equals(order.getStatus())){
            return "modules/order/platform/callbackOrderForm";
        }
        //默认已完成
        return "modules/order/platform/callbackOrderForm";
    }

    /**
     * 平台跟进记录
     */
    @ResponseBody
    @RequestMapping(value = "FollowUp")
    public Object FollowUp(HttpServletRequest request){
        String follow = request.getParameter("follow");
        String orderId = request.getParameter("orderId");
        if(StringUtil.isBlank(orderId)){
            return "201";
        }else if(StringUtil.isBlank(follow)){
            return "202";
        }
        orderService.followUpInformation(orderId,follow);
        return "200";
    }

    /**
     * 获取工单跟进记录信息
     */
    @ResponseBody
    @RequestMapping(value = "getTrackDetail")
    public List<ComplaintReply> getTrackDetail(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        if(StringUtil.isBlank(orderId)){
            return null;
        }
        return orderService.getTrackDetail(orderId);
    }

    @RequestMapping(value = "getFittingUse")
    public String getFittingUse(HttpServletRequest request,Model model){

        return "modules/yangguang/fittingManager/addfittingApply";
    }

    @ResponseBody
    @RequestMapping(value = "getOrderCount")
    public Object getOrderCount(HttpServletRequest request){
        String factor = request.getParameter("factor");
        Map<String ,Object> map = Maps.newHashMap();
        map.put("order",orderService.getPageOrderCount(factor,"",""));
        return map;
    }

    /**
     * 平台端首页统计
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSysOrderCount")
    public Object getSysOrderCount(HttpServletRequest request){
        String factor = request.getParameter("factortNew");
        Map<String ,Object> map = Maps.newHashMap();
        map.put("order",orderService.getPageOrderCount(factor,"",""));
        map.put("fitting",fittingApplyService.getpaltformFittingApplyCount());
        return map;
    }

    /**
     * 服务商平台首页统计
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSiteOrderCount")
    public Object getSiteOrderCount(HttpServletRequest request){
        String factor = request.getParameter("factor");
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        Map<String ,Object> map = Maps.newHashMap();
        map.put("order",orderService.getPageOrderCount(factor,siteId,""));
        map.put("fitting",fittingApplyService.getSiteFittingApplyCount(siteId));
        return map;
    }



    @RequestMapping(value = "checkHistoryCustomerExcel")
    @ResponseBody
    public Object checkHistoryCustomerExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = Maps.newHashMap();
        Map<String, Object> retMap = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        try {
            retMap = orderService.checkFactoryOrder(params, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return retMap;
    }


    @RequestMapping(value = "importHistoryCustomerExcel")
    @ResponseBody
    public Object importHistoryCustomerExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = Maps.newHashMap();
        Map<String, Object> retMap = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        //   params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        try {
            retMap = orderService.importFactoryOrder(params, file.getInputStream(),request);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return retMap;
    }


    /**
     * 平台下跳转新建工单
     */
    @RequestMapping(value="platform/addNewOrder")
    public String toAddOrderForm(HttpServletRequest request,Model model){
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();
        model.addAttribute("promiseLimit",promiseLimit);
        model.addAttribute("data",DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        return "modules/order/platform/addOrderForm";
    }

    /**
     * 平台下跳转新建工单
     */
    @RequestMapping(value="platform/addRepairOrder")
    public String addRepairOrder(HttpServletRequest request,Model model){
        String id = request.getParameter("orderId");
        if (StringUtil.isNotBlank(id)) {
            CrmOrder order = orderDao.get(id);
            if (order!=null) {
                List<Record> citys = AddressUtils.getCityByProName(order.getProvince());
                List<Record> areas = AddressUtils.getAreaByCityName(order.getCity());
                model.addAttribute("faccitys",citys);
                model.addAttribute("areas",areas);
                model.addAttribute("order",order);
            }
        }
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros",pros);
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();
        model.addAttribute("promiseLimit",promiseLimit);
        model.addAttribute("data",DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        return "modules/order/platform/addOrderForm";
    }

    @Autowired
    CrmOrderDispatchService crmOrderDispatchService;
    @ResponseBody
    @RequestMapping(value="getSiteByAdress")
    public List<Record> getSiteByAdress(HttpServletRequest request){
        String customerAdress=request.getParameter("customerAdress");
        String province=request.getParameter("province");
        String city=request.getParameter("city");
        String siteName = request.getParameter("siteName");
        return crmOrderDispatchService.getSiteByAdress(customerAdress,province,city,siteName);
    }

    /**
     * 删除无效工单
    */
    @ResponseBody
    @RequestMapping(value="deleteOrder")
    public Result deleteOrder(HttpServletRequest request){
        String orderId=request.getParameter("orderId");
        return orderService.deleteOrder(orderId);
    }


}
