package com.palmnest.webapp.controller.wechat;

import cn.superdesk.libs.common.json.JsonUtils;

import cn.superdesk.libs.common.util.BeanUtils;
import com.palmnest.application.AppConstants;
import com.palmnest.application.Constants;
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.LogExceptionStackUtil;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.RepairBillInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.RepairParamDto;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.repair.*;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.repair.*;
import com.palmnest.webapp.controller.backstage.ServiceTypeInfoController;

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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping(value = "/wechat/repairBill")
public class WxRepairBillController {

	@Autowired
	private ElementGroupManager      elementGroupManager;
	@Autowired
	private RepairBillService        repairBillService;
	@Autowired
	private UserRepairTypeManager    userRepairTypeManager;
	@Autowired
	private RepairBillManager        repairBillManager;
	@Autowired
	private ScWxuserManager          scWxuserManager;
	@Autowired
	private RepairBillCommentManager repairBillCommentManager;
	@Autowired
	private RepairConfigManager repairConfigManager;
	@Autowired
	private RepairMaterialManager repairMaterialManager;
	@Autowired
	private RepairAddressManager repairAddressManager;
	@Autowired
	private RepairBillMaterialManager repairBillMaterialManager;
	/**
	 * 发起维修首页
	 *
	 * @return
	 */
	@RequestMapping(value = "/index")
	@ResponseBody
	public AppResultDto index(HttpServletRequest request) {
		RepairParamDto dto = new RepairParamDto();
		String orgId = request.getParameter("orgId");

		if (StringUtil.isNotEmpty(orgId)) {
//			//大类
//			List<ElementDto> elementDtos = elementGroupManager.getOrgElementGroupInfoV2(orgId, Constants.REPAIR_TYPE_CODE);
//			dto.setRepairTypeGroup(elementDtos);
//
//			if (null != elementDtos && elementDtos.size() > 0) {
//				//小类
//				List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(elementDtos.get(0).getItemcode());
//				dto.setRepairTypeaDetailGroup(elementGroupManager.convert(repairTypeaDetailGroup));
//			}

			List<Element> repairTypeGroup = new ArrayList<>();
			//大类
			List<ElementDto> elementDtos = elementGroupManager.getOrgElementGroupInfoV2(orgId, Constants.REPAIR_TYPE_CODE);
			if (null != elementDtos && elementDtos.size() > 0) {
				List<Element> repairTypeGroups = BeanUtils.copy(elementDtos, Element.class);
				repairTypeGroup.addAll(repairTypeGroups);
			}
			dto.setRepairTypeGroup(elementDtos);
			if (repairTypeGroup.size() > 0) {
				List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(elementDtos.get(0).getItemcode());
				dto.setRepairTypeaDetailGroup(elementGroupManager.convert(repairTypeaDetailGroup));
			}


			//设置默认配置
			RepairConfig repairConfig = repairConfigManager.getByOrgId(Integer.parseInt(orgId));
			if (null != repairConfig) {
				dto.setCheckFloor(repairConfig.getCheckFloor());
			}

		} else {
			List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName(Constants.REPAIR_TYPE_CODE);
			if (null != repairTypeGroup && 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);
	}


	/**
	 * @param request
	 * @return 根据维修类型查找维修类型详情
	 */
	@RequestMapping(value = "/getRepairTypeaDetail")
	@ResponseBody
	public AppResultDto getRepairTypeaDetail(@RequestParam("repairTypeId") Long repairTypeId) {
		List<Element> repairTypeaDetailGroup = new ArrayList<Element>();
		if(null ==repairTypeId){
			return AppResultUtil.createSuccesDto(repairTypeaDetailGroup);
		}
		Element       element                = elementGroupManager.getElementId(repairTypeId);
		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 {
			log.info("WxRepairBillController-repair:{}",JsonUtils.toJson(dto));
			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 = "/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);
			if (null != wxUser) {
				params.put("bill_user_id", wxUser.getId());
				if(null != wxUser.getUserId()){
					params.put("user_id", wxUser.getUserId());
					params.put("bill_from", 2);
					params.put("bill_user_id", "");
				}
			}
			params.put("orgIds", request.getParameter("orgId"));
			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);
		}
	}

	@RequestMapping(value = "/cancelOrder")
	@ResponseBody
	public WebPageResultDto cancelOrder(HttpServletRequest request) {
		try {
			String                 id    = request.getParameter("id");
			String              openId   = request.getParameter("openId");
			WxUser              wxUser   = scWxuserManager.getScWxuserByOpenId(openId);

			repairBillService.cancelOrder(id,wxUser);
			return new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功",null);
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "取消失败", null);
		}
	}

	/**
	 * @param request
	 * @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, "添加评论失败");
		}
	}


	/**
	 * 获取耗材列表
	 *
	 * @param orgId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getMaterialList")
	@ResponseBody
	public AppResultDto getMaterialList(
			@RequestParam(value = "orgId") Integer orgId, HttpServletRequest request) {
		try {
			List<Map<String, Object>> reuslt = new ArrayList<>();
//            User user = (User) request.getSession().getAttribute("UserCache");
			List<RepairMaterial> repairMaterialList = repairMaterialManager.getMaterialListByOrgId(orgId);

			if (null != repairMaterialList && repairMaterialList.size() > 0) {
				for (RepairMaterial repairMaterial :
						repairMaterialList) {
					Map<String, Object> map = new HashMap<>();
					map.put("id", repairMaterial.getId());
					map.put("materialName", repairMaterial.getMaterialName());
					reuslt.add(map);
				}
			}

			return AppResultUtil.createSuccesDto(reuslt);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.GET_MATERIAL_ERROR, "查询耗材失败");
		}
	}


	/**
	 * 新增耗材
	 *
	 * @param id
	 * @param materialName
	 * @param amount
	 * @return
	 */
	@RequestMapping(value = "/addMaterial")
	@ResponseBody
	public AppResultDto addMaterial(@RequestParam("id") Long id, @RequestParam(value = "materialsId", required = false) Long materialsId, String materialName, Integer amount) {
		try {

			RepairMaterial repairMaterial = repairMaterialManager.get(materialsId);

			if (null != repairMaterial) {
				materialName = repairMaterial.getMaterialName();
			}

			RepairBillMaterial material = new RepairBillMaterial(id, materialsId, materialName, amount);
			repairBillMaterialManager.saveModel(material);
			List<RepairBillMaterial> list = repairBillMaterialManager.findBy(id);

			return AppResultUtil.createSuccesDto(list);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.ADD_MATERIAL_ERROR, "添加耗材失败");
		}
	}

	/**
	 * 获取耗材列表
	 *
	 * @param orgId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getAddressList")
	@ResponseBody
	public WebPageResultDto getAddressList(
			@RequestParam(value = "orgId") Integer orgId, HttpServletRequest request) {
		try {
//            User user = (User) request.getSession().getAttribute("UserCache");
			List<RepairAddress> repairAddresses = repairAddressManager.getListByOrgId(orgId);

			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", repairAddresses);
			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询列表失败", LogExceptionStackUtil.LogExceptionStack(e));
		}
	}
	
	 /**
     * @param request
     * @return 查找维修单对应维修类型下的人员
     */
    @RequestMapping(value = "/getconfigbyorg")
    @ResponseBody
    public AppResultDto getconfigbyorg(@RequestParam("org_id") Integer org_id, HttpServletRequest request) {
        RepairConfig s_con = repairConfigManager.getByOrgId(org_id);
        return AppResultUtil.createSuccesDto(s_con);
    }


}
