package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.BeanUtils;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.output.RepairServiceDto;
import com.palmnest.model.User;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.repair.RepairService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.repair.RepairServiceManager;
import com.palmnest.webapp.controller.BaseFormController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * PC端报修
 */
@Controller
@RequestMapping(value = "/repairService")
public class RepairServiceController extends BaseFormController {


	@Autowired
	private RepairServiceManager repairServiceManager;
	@Autowired
	private UserManager          userManager;
	@Autowired
	private OrganizationManager  organizationManager;

	/**
	 * 报修订单详情页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/repairDetail")
	public ModelAndView repairDetail() {
		//报修方式 区域 类型 小类型
		Model model = new ExtendedModelMap();
//		List<Element> repairWayGroup = elementGroupManager.getElementsByGroupName("repairWayGroup");
//		List<Element> repairAreaGroup = elementGroupManager.getElementsByGroupName("repairAreaGroup");
//		List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName("repairTypeGroup");
//		model.addAttribute("repairWayGroup", elementGroupManager.convert(repairWayGroup));
//		model.addAttribute("repairAreaGroup", elementGroupManager.convert(repairAreaGroup));
//		model.addAttribute("repairTypeGroup", elementGroupManager.convert(repairTypeGroup));

//		if(repairTypeGroup.size()>0) {
//			List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(repairTypeGroup.get(0).getItemcode());
//			model.addAttribute("repairTypeaDetailGroup", elementGroupManager.convert(repairTypeaDetailGroup));
//		}
		return new ModelAndView("/admin/repairService/serviceOrderDetail", model.asMap());
	}

	@RequestMapping(value = "/repairList")
	@ResponseBody
	public WebPageResultDto repairList(HttpServletRequest request) {
		int pageNo = 1;
		if (StringUtils.isNotBlank(request.getParameter("page"))) {
			pageNo = Integer.parseInt(request.getParameter("page"));
		}
		int pageSize = 10;
		if (StringUtils.isNotBlank(request.getParameter("limit"))) {
			pageSize = Integer.parseInt(request.getParameter("limit"));
		}
		String              status    = request.getParameter("status");
		String              startTime = request.getParameter("startTime");
		String              endTime   = request.getParameter("endTime");
		String              phone     = request.getParameter("phone");
		String              username  = request.getParameter("username");
		String              code      = request.getParameter("code");
		Map<String, Object> params    = new HashMap<String, Object>();
		params.put("status", status);
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		params.put("repair_phone", phone);
		params.put("repair_username", username);
		params.put("s_no", code);

		User   user  = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
		String orgId = request.getParameter("orgId");
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		params.put("orgStr", orgId);
		try {
			Page             page = repairServiceManager.findPageBy(params, pageSize, pageNo);
			WebPageResultDto dto  = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			dto.setCount(page.getTotalCount());
			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "获取列表失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 详情
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/repairInfo")
	@ResponseBody
	public WebPageResultDto repairInfo(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (!StringUtil.isNotEmpty(id)) {
			return new WebPageResultDto("400", "ID为空！", "");
		}
		try {
			RepairService    repairService = repairServiceManager.get(Long.parseLong(id));
			RepairServiceDto dto           = new RepairServiceDto();
			BeanUtils.copyProperties(dto, repairService);
			SimpleDateFormat sdf   = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Long             orgId = repairService.getOrg_id();
			TbOrganization   org   = organizationManager.getOrganizationById(Integer.parseInt(orgId.toString()));
			if (org != null) {
				dto.setOrgTel(org.getTelephone());
			}
			if(null != dto.getCreated_at()){
				dto.setCreated_at_str(sdf.format(dto.getCreated_at()));
			}
			if(null != dto.getStatus_date()){
				dto.setStatus_at_str(sdf.format(dto.getStatus_date()));
			}
			if(null != dto.getUpdated_at()){
				dto.setUpdated_at_str(sdf.format(dto.getUpdated_at()));
			}
			if (dto.getUpdated_by() != null && dto.getUpdated_by() != 0) {
				User user = userManager.get(repairService.getUpdated_by());
				if (user != null) {
					dto.setUpdated_by_name(user.getFullName());
				}
			}
			WebPageResultDto webPageResultDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", dto);
			return webPageResultDto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "获取详情失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 审核
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/repairApproval")
	@ResponseBody
	public WebPageResultDto repairApproval(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (!StringUtil.isNotEmpty(id)) {
			return new WebPageResultDto("400", "ID为空！", "");
		}
		try {
			 User user = (User) request.getSession().getAttribute("UserCache");
			RepairService repairService = repairServiceManager.get(Long.parseLong(id));
			if (repairService.getStatus() == 1) {
				return new WebPageResultDto("400", "单据已审核！", "");
			}
			repairService.setStatus((byte) 1);
			repairService.setStatus_date(new Date());
			repairService.setUpdated_at(new Date());
			if(null != user){
				repairService.setUpdated_by(user.getId());
			}
			repairServiceManager.updateModel(repairService);
			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", repairService);
			repairServiceManager.pushWx(repairService);
			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "审核失败！" + e.getMessage(), "");
		}
	}
//	/**
//	 * 
//	 * @param request
//	 * @return
//	 * 根据维修类型查找维修类型详情
//	 */
//	@RequestMapping(value="/getRepairTypeaDetail")
//	@ResponseBody
//	public AppResultDto getRepairTypeaDetail(@RequestParam("repairTypeId") Long repairTypeId) {
//		Element element = elementGroupManager.getElementId(repairTypeId);
//		List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(element.getItemcode());
//		return AppResultUtil.createSuccesDto(repairTypeaDetailGroup);
//	}
//	
//	/**
//	 * 发起维修
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value="/repair")
//	@ResponseBody
//	public AppResultDto repair(@ModelAttribute("repairBillInputDto") RepairBillInputDto dto,MultipartHttpServletRequest request) {
//		try {
//			RepairBill bill = repairBillService.repair(dto, request);
//			repairBillService.push(bill);
//			return AppResultUtil.createSuccesDto(repairBillService.convert(bill));
//		} catch (Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "保存维修单失败");
//		}
//	}
//	
//	/**
//	 * 
//	 * @param request
//	 * @return
//	 * 查找维修单详情
//	 */
//	@RequestMapping(value="/getDetail")
//	@ResponseBody
//	public AppResultDto getDetail(@RequestParam("id") Long id) {
//		return AppResultUtil.createSuccesDto(repairBillService.findById(id));
//	}
//	/**
//	 * 
//	 * @param request
//	 * @return
//	 * 查找对应维修类型下的人员
//	 */
//	@RequestMapping(value="/getRepairTypeUser")
//	@ResponseBody
//	public AppResultDto getRepairTypeUser(@RequestParam("repairTypeId") Long repairTypeId) {
//		return AppResultUtil.createSuccesDto(repairBillService.findByTypeId(repairTypeId));
//	}
//	
//	/**
//	 * 
//	 * @param request
//	 * @return
//	 * 查找所有维修类型
//	 */
//	@RequestMapping(value="/getRepairType")
//	@ResponseBody
//	public AppResultDto getRepairType() {
//		List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName("repairTypeGroup");
//		return AppResultUtil.createSuccesDto(elementGroupManager.convert(repairTypeGroup));
//	}
//	
//	/**
//	 * 
//	 * @param request
//	 * @return
//	 * 查找维修单列表
//	 */
//	@RequestMapping(value="/list")
//	@ResponseBody
//	public WebPageResultDto list(HttpServletRequest request) {
//		try {
//			int pageSize=Integer.parseInt(request.getParameter("limit"));
//			int pageNo=Integer.parseInt(request.getParameter("page"));
//			Map<String, Object> params = new HashMap<String, Object>();
//			params.put("startTime", request.getParameter("startTime"));
//			params.put("endTime", request.getParameter("endTime"));
//			params.put("repairWay", request.getParameter("repairWay"));
//			params.put("repairArea", request.getParameter("repairArea"));
//			params.put("repairType", request.getParameter("repairType"));
//			params.put("status", request.getParameter("status"));
//			params.put("code", request.getParameter("code"));
//			params.put("star", request.getParameter("star"));
//			params.put("hasComment", request.getParameter("hasComment"));//1,2
//			params.put("hasReturnVisit", request.getParameter("hasReturnVisit"));//1,2
//			params.put("serviceUsers", request.getParameter("serviceUsers"));//工程人员
//			
//			String repairTypeIds = "";
//			User user = (User) request.getSession().getAttribute("UserCache");
//			List<Element> types = userRepairTypeManager.findByUser(user.getId());
//			for(Element e : types) {
//				repairTypeIds+=","+e.getId();
//			}
//			if(repairTypeIds.length()>1) {
//				repairTypeIds = repairTypeIds.substring(1);
//			}
//			params.put("repairTypeIds", repairTypeIds);
//			Page page = repairBillService.findPageBy(params, pageSize, pageNo);
//			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//			dto.setCount(page.getTotalCount());
//			return dto;
//		}catch(Exception e ) {
//			e.printStackTrace();
//			return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询列表失败",null);
//		}
//	}
//	
//	/**
//	 * 
//	 * @param request
//	 * @return
//	 * 查找维修单对应维修类型下的人员
//	 */
//	@RequestMapping(value="/getRepairUser")
//	@ResponseBody
//	public AppResultDto getRepairUser(@RequestParam("id") Long id) {
//		RepairBill bill = repairBillManager.get(id);
//		return AppResultUtil.createSuccesDto(repairBillService.findByTypeId(bill.getRepairType()));
//	}
//	
//	/**
//	 * 审核
//	 */
//	@RequestMapping(value="/auditBill")
//	@ResponseBody
//	public AppResultDto auditBill(@RequestParam("id") Long id,Integer operateType,HttpServletRequest request) {
//		try {
//			RepairBill bill = repairBillManager.get(id);
//			//状态 TODO
//			if(!bill.getStatus().equals(CodeConstants.TO_AUDIT)) {
//				return AppResultUtil.createErrorDto(AppConstants.AUDIT_BILL_ERROR, "审核失败，该单不是可审核状态");
//			}
//			User user = (User) request.getSession().getAttribute("UserCache");
//			repairBillService.audit(id, operateType, user);
//			repairBillService.auditPush(operateType, bill);
//			return AppResultUtil.createSuccesDto();
//		}catch(Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.AUDIT_BILL_ERROR, "审核失败");
//		}
//	}
//
//	
//	/**
//	 * 派单
//	 */
//	@RequestMapping(value="/sendBill")
//	@ResponseBody
//	public AppResultDto sendBill(@RequestParam("id") Long id,@RequestParam("receiverId") Long receiverId,HttpServletRequest request) {
//		try {
//			RepairBill bill = repairBillManager.get(id);
//			//状态 TODO
//			if(!bill.getStatus().equals(CodeConstants.IN_PROGRESS) && !bill.getStatus().equals(CodeConstants.IS_SINGLE)
//					&& !bill.getStatus().equals(CodeConstants.IN)) {
//				return AppResultUtil.createErrorDto(AppConstants.SEND_BILL_ERROR, "派单失败，该单不是可派单状态");
//			}
//			User user1 = (User) request.getSession().getAttribute("UserCache");
//			User user = userManager.get(receiverId);
//			bill.setStatus(CodeConstants.IN_PROGRESS);//派单成功设置状态为进行中
//			bill.setServiceUser(user.getId());
//			repairBillManager.updateModel(bill);
//			RepairOperateRecord operateRecord = new RepairOperateRecord(id, user1.getId(), user1.getFullName(), new Date());
//			operateRecord.setOperateType(CodeConstants.TRANSFER);
//			operateRecord.setDetail(user1.getFullName()+"派单给"+user.getFullName());
//			repairOperateRecordManager.saveModel(operateRecord);
//			
//			return AppResultUtil.createSuccesDto();
//		}catch(Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.SEND_ERROR, "派单失败");
//		}
//	}
//	
//	@RequestMapping(value="/addOrUpdateVisit")
//	@ResponseBody
//	public AppResultDto addOrUpdateVisit(@RequestParam("billId") Long billId,@RequestParam(required = false) Long id,Integer star,String description ) {
//		try {
//			RepairReturnVisit visit = null;
//			if(id == null) {
//				visit = new RepairReturnVisit(billId, star, description);
//				repairReturnVisitManager.saveModel(visit);
//			}else {
//				visit = repairReturnVisitManager.get(id);
//				if(visit != null) {
//					visit.setDescription(description);
//					visit.setStar(star);
//					repairReturnVisitManager.updateModel(visit);
//				}
//			}
//			RepairBill bill = repairBillManager.get(billId);
//			bill.setHasReturnVisit(Integer.parseInt("2"));
//			repairBillManager.updateModel(bill);
//			return AppResultUtil.createSuccesDto();
//		}catch(Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.ADD_RETURN_VISIT_ERROR, "添加回访记录失败");
//		}
//	}
}
