package com.palmnest.webapp.controller.api;

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.OrgDto;
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.AppUserService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.redis.BaseRedisService;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping(value = "/api/repairService")
public class ApiRepairServiceController {

	@Autowired
	private BaseRedisService     baseRedisService;
	@Autowired
	private UserManager          userManager;
	@Autowired
	private AppUserService       appUserService;
	@Autowired
	private RepairServiceManager repairServiceManager;
	@Autowired
	private OrganizationManager  organizationManager;


	/**
	 * 报修记录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getList")
	@ResponseBody
	public AppResultDto getList(HttpServletRequest request) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User user   = userManager.getUserByUsername2(userName);
		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");
		String       orgStr = "";
		List<OrgDto> dtos   = appUserService.getUserOrgs(user.getId());
		if (dtos != null && dtos.size() > 0) {
			for (OrgDto org : dtos) {
				orgStr += "," + org.getId();
			}
			orgStr = orgStr.substring(1);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", status);
		String querys = request.getParameter("params");
		params.put("params", querys);
		if (!StringUtil.isNotEmpty(orgStr)) {
			return AppResultUtil.createErrorDto("400", "您没有项目权限！");
		}
		params.put("orgStr", orgStr);
		try {
			Page page = repairServiceManager.findPageBy(params, pageSize, pageNo);
			//WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			//dto.setCount(page.getTotalCount());
			return AppResultUtil.createSuccesDto(page);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto("400", "查询记录失败");
		}
	}

	/**
	 * 审核
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/approval")
	@ResponseBody
	public AppResultDto approval(HttpServletRequest request) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user = userManager.getUserByUsername2(userName);
		String id   = request.getParameter("id");
		if (!StringUtil.isNotEmpty(id)) {
			return AppResultUtil.createErrorDto("400", "ID为空");
		}
		RepairService repairService = repairServiceManager.get(Long.parseLong(id));
		if (repairService.getStatus() == 1) {
			return AppResultUtil.createErrorDto("400", "单据已审核");
		}
		repairService.setStatus((byte) 1);
		repairService.setStatus_date(new Date());
		repairService.setUpdated_at(new Date());
		repairService.setUpdated_by(user.getId());
		repairServiceManager.updateModel(repairService);
		repairServiceManager.pushWx(repairService);
		return AppResultUtil.createSuccesDto();

	}

	/**
	 * 详情
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDetail")
	@ResponseBody
	public AppResultDto getDetail(HttpServletRequest request) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String id = request.getParameter("id");
		if (StringUtils.isEmpty(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");
			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());
				}
			}
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto("400", "获取详情失败！");
		}

	}

}
