package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
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.input.RepairServiceInputDto;
import com.palmnest.application.dto.output.RepairServiceDto;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.WxUser;
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.estateserve.ScWxuserManager;
import com.palmnest.service.repair.RepairServiceManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping(value = "/wechat/repairService")
public class WxRepairServiceController {

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

	/**
	 * 申请报修
	 *
	 * @param dto
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addRepair")
	@ResponseBody
	public AppResultDto addRepair(@ModelAttribute("repairServiceInputDto") RepairServiceInputDto dto, HttpServletRequest request) {
		try {
			String        openId = request.getParameter("openId");
			WxUser        wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			RepairService model  = new RepairService();
			model.setStatus((byte) 0);
			model.setBuild_floor(dto.getBuild_floor());
			model.setBuild_id(dto.getBuild_id());
			model.setBuild_name(dto.getBuild_name());
			model.setBuild_room(dto.getBuild_room());
			model.setCompany_name(dto.getCompany_name());
			model.setCreated_at(new Date());
			model.setRepair_amount(new BigDecimal(0));
			model.setRepair_phone(dto.getRepair_phone());
			model.setRepair_user_id((long) wxUser.getId());
			model.setRepair_username(dto.getRepair_username());
			model.setSource_type(dto.getSource_type());
			model.setS_no(repairServiceManager.getNo());
			model.setRemarks(dto.getRemarks());
			model.setUpdated_at(new Date());
			model.setStatus_date(new Date());
			model.setCreated_by((long) wxUser.getId());
//			model.setUpdated_by((long)wxUser.getId());
			model.setOrg_id(dto.getOrg_id());
			model.setRoom_id(dto.getRoom_id());
			model.setFloor_id(dto.getFloor_id());
			Object returnRS = repairServiceManager.saveModel(model);
			if (returnRS != null) {
				repairServiceManager.push(Long.parseLong(returnRS.toString()));
			}
			return AppResultUtil.createSuccesDto(returnRS);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "申请报修失败");
		}
	}

	/**
	 * 报修记录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getList")
	@ResponseBody
	public AppResultDto getList(HttpServletRequest request) {
		String openId = request.getParameter("openId");
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (wxUser == null || wxUser.getId() == null) {
			return new AppResultDto("400", "用户不存在！");
		}
		int pageNo = 1;
		if (StringUtils.isNotBlank(request.getParameter("pageNo"))) {
			pageNo = Integer.parseInt(request.getParameter("pageNo"));
		}
		int pageSize = 10;
		if (StringUtils.isNotBlank(request.getParameter("pageSize"))) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		String status = request.getParameter("status");

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", status);
		params.put("repair_user_id", wxUser.getId());
		try {
			Page             page = repairServiceManager.findPageBy(params, pageSize, pageNo);
			WebPageResultDto dto  = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			dto.setCount(page.getTotalCount());
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createSuccesDto("400", "查询记录失败");
		}
	}

	/**
	 * 报修详情
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDetail")
	@ResponseBody
	public AppResultDto getDetail(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (!StringUtil.isNotEmpty(id)) {
			return AppResultUtil.createErrorDto("400", "ID为空！");
		}
		try {
			RepairService    repairService = repairServiceManager.get(Long.parseLong(id));
			RepairServiceDto dto           = new RepairServiceDto();
			BeanUtils.copyProperties(dto, repairService);
			Long           orgId = repairService.getOrg_id();
			TbOrganization org   = organizationManager.getOrganizationById(Integer.parseInt(orgId.toString()));
			if (org != null) {
				dto.setOrgTel(org.getTelephone());
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			dto.setCreated_at_str(sdf.format(dto.getCreated_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 AppResultUtil.createSuccesDto(webPageResultDto);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto("400", "获取详情失败！");
		}

	}

	/**
	 *发起维修首页
	 * @return
	 */
//	@RequestMapping(value="/index")
//	@ResponseBody
//	public AppResultDto index(HttpServletRequest request) {
//		RepairParamDto dto = new RepairParamDto();
//		List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName("repairTypeGroup");
//		if(repairTypeGroup.size()>0) {
//			List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(repairTypeGroup.get(0).getItemcode());
//			dto.setRepairTypeaDetailGroup(elementGroupManager.convert(repairTypeaDetailGroup));
//		}
//		dto.setRepairTypeGroup(elementGroupManager.convert(repairTypeGroup));
//		return AppResultUtil.createSuccesDto(dto);
//	}


	/**
	 *
	 * @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, "保存维修单失败");
//		}
//	}

	/**
	 *
	 * @return
	 * 查找维修单详情
	 */
//	@RequestMapping(value="/getDetail")
//	@ResponseBody
//	public AppResultDto getDetail(@RequestParam("id") Long id) {
//		return AppResultUtil.createSuccesDto(repairBillService.findById(id));
//	}

	/**
	 *
	 * @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>();
//		String openId = request.getParameter("openId");
//    	WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
//    	params.put("bill_user_id", wxUser.getId());
//		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);
//	}
//	}

	/**
	 *
	 * @return
	 * 获取员工印象
	 */
//	@RequestMapping(value="/getServiceImpression")
//	@ResponseBody
//	public AppResultDto getServiceImpression() {
//		List<Element> repairPendReasonGroup = elementGroupManager.getElementsByGroupName("serviceImpressionGroup");
//		return AppResultUtil.createSuccesDto(elementGroupManager.convert(repairPendReasonGroup));
//	}

	/**
	 * 评价
	 * @param id
	 * @param star
	 * @param serviceImpression
	 * @param description
	 * @return
	 */
//	@RequestMapping(value="/comment")
//	@ResponseBody
//	public AppResultDto comment(@RequestParam("id") Long id,@RequestParam(required = false)String openId,Integer star,String serviceImpression,String description ) {
//		try {
//			RepairBillComment comment = new RepairBillComment(id, star, openId, description, serviceImpression);
//			comment.setCreateTime(new Date());
//			repairBillCommentManager.saveModel(comment);
//			RepairBill bill = repairBillManager.get(id);
//			bill.setHasComment(Integer.parseInt("2"));
//			repairBillManager.updateModel(bill);
//			return AppResultUtil.createSuccesDto(comment);
//		}catch(Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto(AppConstants.ADD_COMMENT_ERROR, "添加评论失败");
//		}
//	}
}
