package com.sifang.modules.order.controller;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.JSONAppendUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.EmployeInformationDao;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.financialManagement.entity.CrmOrderSiteSettlement;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.service.FittingRefundService;
import com.sifang.modules.platform.service.RecevierAddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.service.OrderFeedbackService;
import com.sifang.modules.order.service.OrderService;
import com.sifang.modules.order.service.SiteSettlementRecordService;
import com.sifang.modules.order.utils.OrderUtils;
import com.sifang.modules.site.fittingManager.service.SiteFittingApplyService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.util.CrmSiteUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * 服务商工单控制层类
 * @author lzp
 * @version 2019-11-13
 */
@Controller
@RequestMapping(value="${adminPath}/service/order")
public class ServiceOrderController extends BaseController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderFeedbackService feedbackService;
    @Autowired
    private SiteFittingApplyService fittingApplyService;
    @Autowired
    SiteFittingApplyService siteFittingApplyService;
    @Autowired
    private FittingRefundService refundService;

    @Autowired
    SiteSettlementRecordService siteSettlementRecordService;

    @Autowired
    private RecevierAddressService recevierAddressService;

    @Autowired
    EmployeInformationDao employeInformationDao;

    @Autowired
    CrmSiteFittingApplyDao crmSiteFittingApplyDao;

    @Autowired
    AddressService addressService;
    /***
     * 服务商端全部工单
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="getFormOrder")
    public String getFormOrder(HttpServletRequest request, Model model){
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        List<Record> empList = employeInformationDao.getEmp(siteId);
        model.addAttribute("empList", empList);
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/allOrderList";
    }

    @ResponseBody
    @RequestMapping(value="getServiceFormList")
    public Object getServiceFormList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        LayuiPage page = new LayuiPage(request);
        Map<String, Object> sitemap = orderService.getSiteOrderList(map, siteId, page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>) sitemap.get("orderList"));
        return page.renderJson();
    }
    /***
     * 服务商端服务中工单
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="getServiceingOrder")
    public String getServiceingOrder(HttpServletRequest request, Model model){
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        List<Record> empList = employeInformationDao.getEmp(siteId);
        model.addAttribute("empList", empList);
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/serviceingOrder";
    }
    @ResponseBody
    @RequestMapping(value = "getServiceingOrderList")
    public Object getServiceingOrderList(HttpServletRequest request){
       Map<String,String> map=getParams(request);
       String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        LayuiPage page=new LayuiPage(request);
        Map<String,Object> sitemap=orderService.getInServiceOrderBySiteId(map,siteId,page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>)sitemap.get("orderList"));
        return page.renderJson();
    }

    /***
     * 服务商端待接收工单
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="waitReceive")
    public String getWaitReceive(HttpServletRequest request, Model model) {
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/waitReceive";
    }

    /**
     * 获取服务商待接单数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getWaitReceiveData")
    public Object getWaitReceiveData(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        LayuiPage page=new LayuiPage(request);
        Map<String,Object> sitemap=orderService.getWaitReceiveData(map,siteId,page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>)sitemap.get("orderList"));
        return page.renderJson();
    }

    /***
     * 服务商端待派工
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="waitWork")
    public String getWaitWork(HttpServletRequest request, Model model) {
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/waitWork";
    }

    /**
     * 获取服务商待派工
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getWaitWorkData")
    public Object getWaitWorkData(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        LayuiPage page=new LayuiPage(request);
        Map<String,Object> sitemap=orderService.getWaitWorkData(map,siteId,page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>)sitemap.get("orderList"));
        return page.renderJson();
    }

    /***
     * 服务商端已完工
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="workFinish")
    public String getWorkFinish(HttpServletRequest request, Model model) {
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        List<Record> empList = employeInformationDao.getEmp(siteId);
        model.addAttribute("empList", empList);
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/workFinish";
    }

    /**
     * 获取服务商已完工数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getWorkFinishData")
    public Object getWorkFinishData(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        LayuiPage page=new LayuiPage(request);
        Map<String,Object> sitemap=orderService.getWorkFinishData(map,siteId,page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>)sitemap.get("orderList"));
        return page.renderJson();
    }

    /**
     * 跳转服务商无效单列表
     * @return
     */
    @RequestMapping(value="workInvalid")
    public String workInvalid(HttpServletRequest request,Model model){
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        List<Record> empList = employeInformationDao.getEmp(siteId);
        model.addAttribute("empList", empList);
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/workInvalid";
    }

    /**
     * 获取无效单数据
     */
    @RequestMapping(value = "getWorkInvalidData")
    @ResponseBody
    public Object getWorkInvalidData(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        String status = request.getParameter("status");
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        orderService.getWorkInvalidData(page,map,status,siteId);
        return page.renderJson();
    }


    /***
     * 服务商端已完成
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="workSettlement")
    public String getWorkSettlement(HttpServletRequest request, Model model) {
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        List<Record> empList = employeInformationDao.getEmp(siteId);
        model.addAttribute("empList", empList);
        model.addAttribute("measures", PlantformUtils.getAllMeasutes());
        return "modules/order/service/workSettlement";
    }

    /**
     * 获取服务商已结算数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getWorkSettlementData")
    public Object getWorkSettlementData(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        LayuiPage page=new LayuiPage(request);
        Map<String,Object> sitemap=orderService.getWorkSettlementData(map,siteId,page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>)sitemap.get("orderList"));
        return page.renderJson();
    }

    /***
     * 服务商端查看配件单
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "getServiceFitting")
    public String getServiceFitting(HttpServletRequest request,Model model){
        return "modules/order/service/serviceFittingOrder";
    }
    @ResponseBody
    @RequestMapping(value = "getFittingOrderList")
    public Object getFittingOrderList(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        Map<String,Object> sitemap =orderService.getSitePartsOrderList(map,siteId,page);
        page.setCount((Long) sitemap.get("count"));
        page.setData((List<Record>)sitemap.get("orderList"));
        return page.renderJson();
    }

    /***
     * 服务商端 查看工单详情
     */
    @RequestMapping(value="serviceGetOrderDetail")
    public String toServiceGetOrderDetail(HttpServletRequest request,Model model) {
        String orderId = request.getParameter("orderId");
        CrmOrder order = orderService.getOrderById(orderId);
        model.addAttribute("order", order);
        String siteStatus = order.getSiteStatus();
        String status = order.getStatus();

        //地址信息
        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);
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();//
        model.addAttribute("promiseLimit",promiseLimit);
        //服务措施
        model.addAttribute("serviceMeasures",OrderUtils.getOrderServiceMeasures(order.getServiceType()));

        String siteId=order.getSiteId();
        //获取服务反馈信息
        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);

        //备件申请记录
        List<Record> list = orderService.getApply(orderId);
        model.addAttribute("list", list);
        //收款记录
        model.addAttribute("collectionVoucher" ,siteSettlementRecordService.getOrderCollection(orderId));

        //跟进记录信息
        String  detail = orderService.getOrderTrackDetail(orderId);
        if(StringUtil.isNotBlank(detail)){
            model.addAttribute("detail", JSONAppendUtils.getProcess(detail));
        }
        //已完成
        if (CrmOrder.FIVE.equals(status)&&CrmOrder.SEVEN.equals(siteStatus)) {
            CrmOrderSiteSettlement settle = orderService.getOrderSiteSettlementByOrderId(orderId);
            model.addAttribute("settle",settle);
            Record serrds = siteSettlementRecordService.getOrderSettle(orderId);
            model.addAttribute("serrds",serrds);

            return "modules/order/service/finishSettlementOrderForm";
        }
        //无效工单
        if("9".equals(siteStatus)){
            return "modules/order/service/invalidOrderForm";
        }
        //待接收
        if (CrmOrder.ORDERTYPE_ONE.equals(siteStatus)) {
            return "modules/order/service/waitReceiveOrderForm";
        }
        //待派工
        if(CrmOrder.ORDERTYPETHREE.equals(siteStatus)){
            return "modules/order/service/waiteDispatchOrderForm";
        }
        //服务中
        if(CrmOrder.FOUR.equals(siteStatus)||CrmOrder.FIVE.equals(siteStatus)||CrmOrder.SIX.equals(siteStatus)){
             return "modules/order/service/inServiceOrderForm";
        }
        //已完工
        if(CrmOrder.SEVEN.equals(siteStatus)){
            return "modules/order/service/finishServiceOrderForm";
        }

            return "modules/order/service/waitReceiveOrderForm";
        }

    /**
     * 查看工单过程信息
     */
    @RequestMapping(value = "getOrderProcessDetail")
    @ResponseBody
    public Object getOrderDetail(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        if(StringUtil.isBlank(orderId)){
            return null;
        }
        return orderService.getOrderDetail(orderId);
    }
    /***
     * 保存修改的工单
     */
    @ResponseBody
   @RequestMapping(value = "saveUpdate")
    public Object  saveUpdate(HttpServletRequest request,Model model){
        Map<String,String> map=getParams(request);
        String SiteName=orderService.getOrderById(request.getParameter("orderId")).getSiteName();
        map.put("feedback_name",SiteName);
        Result result=null;
    try{
      result=orderService.siteUpdateOrder(map);
    }catch (Exception e){
        e.printStackTrace();
        result.setCode("505");
    }
       return result;
    }

    /***
     * 派工弹框
     */
    @RequestMapping(value="dispatchOrderForm")
    public String toDispatchOrderForm(HttpServletRequest request,Model model){
        String orderId=request.getParameter("orderId");
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        List<Record> records=orderService.getEngineerList(siteId);
       model.addAttribute("records",records);
       model.addAttribute("orderId",orderId);
        return "modules/order/service/dispatchOrderForm";
    }
    /***
     * 服务商派工
     */
    @ResponseBody
    @RequestMapping(value = "dispatchForm")
    public Object toDispatchForm(HttpServletRequest request){
        Map<String,String> map=getParams(request);
      String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
          map.put("siteId",siteId);
         Result result=orderService.siteDispatchOrder(map);
          return result;
    }

    /***
     * 服务商转派弹框
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="turnDisOrderForm")
    public String toTurnDisOrderForm(HttpServletRequest request,Model model){
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        List<Record> records=orderService.getEngineerList(siteId);
        model.addAttribute("records",records);
        model.addAttribute("employeName", request.getParameter("employeName"));
        return "modules/order/service/turnDisOrderForm";
    }
    /***
     * 服务商转派
     */
    @ResponseBody
    @RequestMapping(value = "tunDispatchForm")
    public Object toTunDispatchForm(HttpServletRequest request){
        Map<String,String> map=getParams(request);
         String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        map.put("siteId",siteId);
        Result result=orderService.siteTransferOrder(map);
        return result;
    }
    /****
     * 服务商预约弹框
     */
    @RequestMapping(value = "appointment")
    public String toAppointment(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        CrmOrder order = orderService.getOrderById(orderId);
        List<String> promiseLimit = PlantformUtils.getPromiseLimit();//
        model.addAttribute("promiseLimit",promiseLimit);
        model.addAttribute("order",order);
        return "modules/order/service/appointmentTime";
    }


    /***
     * 保存服务商的预约时间
     */
    @ResponseBody
    @RequestMapping(value="saveAppointment")
    public Object toSaveAppointment(HttpServletRequest request){
        Map<String,Object> mapss = Maps.newHashMap();
        Map<String,String> map = getParams(request);
        try {
            orderService.sitePromiseTimeOrder(map.get("orderId"),map.get("promiseTime"),map.get("promiseLimit"));
            mapss.put("code","200");
        }catch (Exception e){
            e.printStackTrace();
            mapss.put("code","505");
        }
        return mapss;
    }
    /***
     * 服务商申请备件
     */
    @RequestMapping(value="serviceAddFitApplyPage")
    public String toServiceAddFitApplyPage(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        String selectAddress = request.getParameter("selectAddress");//选择的地址类型1.自定义地址 2.用户地址 3.网点地址
        CrmOrder order = orderService.getOrderById(orderId);
        Record orderRecord = CrmSiteUtils.getUserAddress(orderId);//获取用户地址信息
        Record autoRecord = CrmSiteUtils.getAutoInfo(orderId);//获取自定义地址信息
        model.addAttribute("order",order);
     //   model.addAttribute("siteRecord",siteRecord);
        model.addAttribute("autoRecord",autoRecord);
        //查出服务商自定义收货地址
        List<Record> list =recevierAddressService.getSiteRecevierAddress(order.getSiteId());
        if(selectAddress.equals("1")){//自定义信息
            model.addAttribute("contactsInfos", autoRecord.getStr("delivery_name"));//自定义--收货人
            model.addAttribute("mobileInfos", autoRecord.getStr("delivery_mobile"));//自定义--联系方式
            model.addAttribute("addressInfos", autoRecord.getStr("delivery_address"));//自定义--收货地址
        }else if(selectAddress.equals("2")){
            model.addAttribute("contactsInfos", orderRecord.getStr("customer_name"));//用户信息--收货人
            model.addAttribute("mobileInfos", orderRecord.getStr("customer_mobile"));//用户信息--联系方式
            model.addAttribute("addressInfos", orderRecord.getStr("province")+orderRecord.getStr("city")+orderRecord.getStr("area")+
                   orderRecord.getStr("customer_address"));//用户信息--收货地址
        }else{
            if(list.size()>0){
                Record siteRecord = list.get(0);
                model.addAttribute("contactsInfos", siteRecord.getStr("receiver"));//网点信息--收货人
                model.addAttribute("mobileInfos", siteRecord.getStr("mobile"));//网点信息--联系方式
                model.addAttribute("addressInfos", siteRecord.getStr("siteAddress"));//网点信息--收货地址
            }
        }
        model.addAttribute("sitelist",list);
        model.addAttribute("selectAddress",selectAddress);
        return "modules/order/service/serviceAddFitApplyPage";
    }
    /***
     * 保存服务商添加的备件
     */
    @ResponseBody
    @RequestMapping(value = "saveApplyFitting")
    public Object toSaveApplyFitting(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        map.put("applicantName", name);
        map.put("creator", name);
        map.put("applicantId", user.getId());
        map.put("applicant_type", "3");
        Result result = fittingApplyService.siteApplyFitting(map);
        return result;
    }

    /***
     * 服务商删除备件
     */
    @ResponseBody
    @RequestMapping(value="deleteFitting")
    public Object toDeleteFitting(HttpServletRequest request){
        Map<String,String> map = getParams(request);
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        map.put("creator", name);
        return  siteFittingApplyService.siteDeleteApplyFitting(map);
    }
/***
 * 服务商反馈封单弹框
 */
 @RequestMapping(value="feedbackFormPage")
public String toFeedbackFormPage(HttpServletRequest request,Model model){
     String orderId =request.getParameter("orderId");
     CrmOrder order = orderService.getOrderById(orderId);
     List<Record> list = OrderUtils.getOrderServiceMeasures(order.getServiceType());
     model.addAttribute("order",order);
     model.addAttribute("list",list);
     return "modules/order/service/feedbackFormPage";
 }

    /***
     * 将已完成工单返回服务中
     */
    @ResponseBody
    @RequestMapping(value="backService")
    public Object toBackService(HttpServletRequest request){
        Map<String,String> map =getParams(request);
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        Record site=CrmSiteUtils.getSiteById(map.get("siteId"));
        map.put("feedback_id", site.getStr("id"));
        map.put("feedback_name",name);
        map.put("user_type", user.getUserType());
        return orderService.updateOrderStatus(map);
    }
    /***
     * 服务商接单
     */
    @ResponseBody
    @RequestMapping(value="receiveOrder")
    public Object toReceiveOrder(HttpServletRequest request){
        String orderId =request.getParameter("orderId");
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        Result result=null;
        if(StringUtil.isBlank(orderId)){
           result.setCode("407");
            return result;
        }
        return  orderService.siteReceiveOrder(orderId,siteId);
    }
    /***
     * 服务商拒单
     */
    @ResponseBody
    @RequestMapping(value="refuseOrder")
    public Object toRefuseOrder(HttpServletRequest request){
        String orderId =request.getParameter("orderId");
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        Result result=null;
        try {
            result = orderService.siteRefuseOrder(orderId,siteId);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("505");
        }
        return result;
    }
}
