package com.palmnest.service.washcar.service.impl;

import cn.jiguang.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.CodeGenerateUtils;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.dto.input.ExtraServiceInputDto;
import com.palmnest.application.dto.input.SlipInputDto;
import com.palmnest.application.dto.input.WashCarOrderDto;
import com.palmnest.application.dto.input.WashOrderInputDto;
import com.palmnest.application.dto.output.BillOperationDto;
import com.palmnest.application.dto.output.WashCarServiceDto;
import com.palmnest.application.dto.output.WashOrderOutputDto;
import com.palmnest.model.Element;
import com.palmnest.model.User;
import com.palmnest.model.washcar.Customer;
import com.palmnest.model.washcar.ProjectSet;
import com.palmnest.model.washcar.UserEvaluate;
import com.palmnest.model.washcar.WashCarOrder;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.BillOperationRecodesManager;
import com.palmnest.service.washcar.manager.CustomerManager;
import com.palmnest.service.washcar.manager.ProjectSetManager;
import com.palmnest.service.washcar.manager.UserEvaluateManager;
import com.palmnest.service.washcar.manager.WashCarOrderManager;
import com.palmnest.service.washcar.service.OrderExtraServiceService;
import com.palmnest.service.washcar.service.WashCarOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service("washCarOrderService")
public class WashCarOrderServiceImpl implements WashCarOrderService {


	@Autowired
	private WashCarOrderManager         washCarOrderManager;
	@Autowired
	private CustomerManager             customerManager;
	@Autowired
	private UserManager                 userManager;
	@Autowired
	private UserEvaluateManager         userEvaluateManager;
	@Autowired
	private BillOperationRecodesManager billOperationRecodesManager;
	@Autowired
	private OrderExtraServiceService    orderExtraServiceService;
	@Autowired
	private ElementGroupManager         elementGroupManager;
	@Autowired
	private ProjectSetManager           projectSetManager;

	private static final String XCFW = "xcfw";

	@Override
	public Page findSearch(WashCarOrderDto dto, int pageNo, int pageSize)
			throws Exception {
		return washCarOrderManager.findSearch(dto, pageNo, pageSize);
	}

	@Override
	public WashOrderOutputDto getOrderInfo(Long id) throws Exception {
		WashOrderOutputDto dto = new WashOrderOutputDto();
		if (id != null && id != 0) {
			if (washCarOrderManager.exists(id)) {
				WashCarOrder washOrder = washCarOrderManager.get(id);
				if (washOrder != null) {
					Map<String, Object> map    = washCarOrderManager.getExtAmount(id);//根据订单查出对应的金额以及服务内容
					BigDecimal          amount = new BigDecimal("0");
					if (map.get("amount") != null && StringUtils.isNotEmpty(map.get("amount").toString())) {
						amount = new BigDecimal(map.get("amount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP);
						;
					}
					dto.setKeySpace(washOrder.getKeySpace());
					dto.setParkSpace(washOrder.getParkSpace());
					dto.setAmount(amount);
					dto.setCarNumber(washOrder.getCarNumber());
					dto.setId(washOrder.getId());
					if (washOrder.getIsGetKey() == null || washOrder.getIsGetKey() == 0) {
						dto.setIsgetKey(1);//没有取钥匙
					} else {
						dto.setIsgetKey(2);//取钥匙了
					}
					if (washOrder.getCreateTime() != null) {
						dto.setCreateTime(DateHelper.formatDate(washOrder.getCreateTime(), DateHelper.DATE_STRING));
					}
//					User user=userManager.get(id);
					if (StringUtils.isNotEmpty(washOrder.getCarWasherId())) {
						if (userManager.exists(Long.parseLong(washOrder.getCarWasherId()))) {
							dto.setHandleMenId(washOrder.getCarWasherId());
							User user1 = userManager.get(Long.parseLong(washOrder.getCarWasherId()));
							dto.setHandleMen(user1.getFullName() == null ? user1.getUsername() : user1.getFullName());//处理人
							dto.setHandleMobile(user1.getTelephone());
						}
					}
					UserEvaluate ue = userEvaluateManager.findByOrderId(id, "1");//根据订单找评论
					if (ue == null) {//未评论
						dto.setIsEvaluate(1);
					} else {
						dto.setIsEvaluate(2);//已评论
						dto.setStar(ue.getStar() == null ? 0 : ue.getStar());
						dto.setComment(ue.getComment() == null ? "" : ue.getComment());
						String imps     = ue.getService_impression();
						String impsName = "";
						if (StringUtils.isNotEmpty(imps)) {
							String[] str = imps.split(";");
							if (str != null && str.length > 0) {
								for (int i = 0; i < str.length; i++) {
									Element el = elementGroupManager.getElementId(Long.parseLong(str[i]));
									if (el != null) {
										impsName = impsName + el.getItemname() + ";";
									}
								}
							}
						}
						dto.setImpressionsName(impsName);
					}
					List<BillOperationDto> list = billOperationRecodesManager.getRecodeBySourId(id, 3);//3代表洗车项目
					dto.setList(list);
					dto.setOrderContent(map.get("orderContent").toString());
					dto.setOrderNo(washOrder.getOrderNo());
					dto.setStatus(washOrder.getStatus());
					dto.setUserId(washOrder.getCustId());
					if (washOrder.getCustId() != null) {
						if (customerManager.exists(washOrder.getCustId())) {
							Customer cust = customerManager.get(washOrder.getCustId());
							dto.setUserName(cust.getUserName());
							dto.setMobile(cust.getMobile());
						}
					}
				}
			}
		}
		return dto;
	}

	@Override
	public Integer deleteOrder(Long id) throws Exception {
		if (washCarOrderManager.exists(id)) {
			WashCarOrder order = washCarOrderManager.get(id);
			if ("1".equals(order.getStatus()) || "6".equals(order.getStatus())) {//待接单或者已取消的单据可以删除
				return washCarOrderManager.deleteOrder(id);
			}
		}
		return 0;
	}

	@Transactional
	public Map<String, Object> saveWashCarOrder(WashOrderInputDto washOrderInputDto,
												String userId, Integer type) throws Exception {
		Map<String, Object> map       = new HashMap<String, Object>();
		WashCarOrder        washOrder = new WashCarOrder();
		try {
			washOrder.setCarNumber(washOrderInputDto.getCarNumber());
			washOrder.setCustId(washOrderInputDto.getUserId());
			washOrder.setCreateTime(new Date());
			washOrder.setCreator(Long.parseLong(userId));
			washOrder.setKeySpace(washOrderInputDto.getKeySpace());
			washOrder.setOrderNo(CodeGenerateUtils.generate(XCFW));
			washOrder.setParkSpace(washOrderInputDto.getParkSpace());
			washOrder.setSource(String.valueOf(type));//来源 1PC 2微信
			washOrder.setStatus("1");//待接单
			washOrder.setPreOrder(Long.parseLong(userId));
			washOrder.setOrgId(washOrderInputDto.getOrgId());
			WashCarOrder order = washCarOrderManager.saveWashCarOrder(washOrder);
			map.put("orderInfo", order);
			if (order != null) {//首先保存服务项；然后再保存操作记录
				//保存服务项
				List<Object>               list   = JSON.parseArray(washOrderInputDto.getList());
				List<ExtraServiceInputDto> esList = new ArrayList<ExtraServiceInputDto>();
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						ExtraServiceInputDto dto = new ExtraServiceInputDto();
						JSONObject           obj = (JSONObject) list.get(i);
						if (obj.get("id") != null && StringUtils.isNotEmpty(obj.get("id").toString())) {
							dto.setId(obj.get("id").toString());
							esList.add(dto);
						}
					}
				}
				if (list != null && list.size() > 0) {
					int count = orderExtraServiceService.saveList(esList, order.getId(), userId);
					if (list.size() != count) {
						map.put("msg", "添加订单服务项异常");
					}
				}
				User user = new User();
				//保存操作记录
				if (userManager.exists(Long.parseLong(userId))) {
					user = userManager.get(Long.parseLong(userId));
					//10创建11派单13洗车中15转单14已完成16取消订单
					String userName = user.getFullName();
					if (StringUtils.isEmpty(userName)) {
						userName = user.getUsername();
					}
					billOperationRecodesManager.saveRecode(order.getId(), 3, 10, Long.parseLong(userId)
							, "下单成功", userName + "创建服务订单成功，订单号为：" + order.getOrderNo());
				} else if (customerManager.exists(Long.parseLong(userId))) {
					Customer cust = customerManager.get(Long.parseLong(userId));
					if (cust != null) {
						String userName = cust.getUserName();
						billOperationRecodesManager.saveRecode(order.getId(), 3, 10, Long.parseLong(userId)
								, "下单成功", userName + "创建服务订单成功，订单号为：" + order.getOrderNo());
					}
				} else {
					map.put("msg", "用户不存在");
				}

			} else {
				map.put("msg", "保存洗车订单异常");
			}
			map.put("msg", "");
		} catch (Exception e) {
			map.put("msg", "保存洗车订单异常:" + e.getMessage());
			log.error("保存洗车订单异常:" + e.getMessage());
			e.printStackTrace();
		}
		return map;
	}

	@Override
	public List<WashCarServiceDto> getWashCarService(String orgId, String syscode)
			throws Exception {
		List<Map<String, Object>> list    = washCarOrderManager.getWashCarService(orgId, syscode);
		List<WashCarServiceDto>   wcsList = new ArrayList<WashCarServiceDto>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				WashCarServiceDto   dto = new WashCarServiceDto();
				dto.setId(Long.parseLong(map.get("id").toString()));
				dto.setUserName(map.get("USERNAME") == null ? "" : map.get("USERNAME").toString());
				dto.setName(map.get("FULL_NAME") == null ? map.get("USERNAME").toString() : map.get("FULL_NAME").toString());
				dto.setIsOnline(Integer.parseInt(map.get("is_online") == null ? "1" : map.get("is_online").toString()));
				dto.setWorkNo(map.get("USERNAME") == null ? "" : map.get("USERNAME").toString());
				String             status  = "'1','4','6'";//订单状态  1已提交2已接单（已派单）3洗车中4已完成洗车5已转单6已取消
				List<WashCarOrder> wcoList = washCarOrderManager.getWashOrderByCarWasherId(map.get("id").toString(), status, 2);
				if (wcoList != null && wcoList.size() > 0) {
					dto.setWorkingCount(wcoList.size());
				} else {
					dto.setWorkingCount(0);
				}
				wcsList.add(dto);
			}
		}
		return wcsList;
	}

	@Override
	public String dispatch(int type, Long id, String washSerId, String userId)
			throws Exception {
		String res = "FAIL";
		//修改订单
		try {
			if (washCarOrderManager.exists(id)) {
				WashCarOrder washOrder = washCarOrderManager.get(id);
				if (StringUtils.isNotEmpty(washOrder.getCarWasherId())) {
					res = "OPERATED";
				} else {
					washOrder.setCarWasherId(washSerId);
					washOrder.setStatus("2");
					if (type == 1) {//pc端直接调用
						washOrder.setOperaManagerId(userId);//管理员
					}
					washOrder.setPreOrder(Long.parseLong(userId));
					washOrder.setModifier(userId);
					washOrder.setModifyTime(new Date());
					WashCarOrder washCarOrder = washCarOrderManager.updateWashOrder(washOrder);
					//增加操作记录
					if (washCarOrder != null) {
						String serName  = "";
						String userName = "";
						if (userManager.exists(Long.parseLong(userId))) {
							User user = userManager.get(Long.parseLong(userId));
							userName = user.getFullName();
							if (StringUtils.isEmpty(userName)) {
								userName = user.getUsername();
							}
						}

						if (userManager.exists(Long.parseLong(washSerId))) {
							User serUser = userManager.get(Long.parseLong(washSerId));
							serName = serUser.getFullName();
							if (StringUtils.isEmpty(serName)) {
								serName = serUser.getUsername();
							}
						}
						//10代表下单11代表派单12代表已完成14代表已取消
						billOperationRecodesManager.saveRecode(id, 3, 11, Long.parseLong(userId), "派单成功", userName + "派单成功，派单给" + serName);
						res = "SUCCESS";

					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}
		return res;
	}

	@Override
	public List<WashCarOrder> getWashListByDas(String userId, String status,
											   int type) throws Exception {
		return washCarOrderManager.getWashListByDas(userId, status, type);
	}

	@Override
	public String automaticDispatch(String orgId, Long id, String userId) throws Exception {
		//首先查出今天空闲的洗车小哥
		String                  res  = "FAIL";
		List<WashCarServiceDto> list = getWashCarService(orgId, CodeConstants.CARWASH_SERVICE);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				WashCarServiceDto dto = list.get(i);
				if (dto.getWorkingCount() == 0) {//当该洗车小哥的进行中的数量为0的时候，就派单给该洗车小哥
					res = dispatch(2, id, dto.getId().toString(), userId);
					break;
				}
			}
		}
		return res;
	}

	@Override
	public String cancelWashOrder(Long id, String userId, String type) throws Exception {
		String res = "FAIL";
		if (washCarOrderManager.exists(id)) {
			WashCarOrder order = washCarOrderManager.get(id);
			if (order != null) {
				order.setStatus("6");
				order.setModifyTime(new Date());
				order.setModifier(userId);
				WashCarOrder washOrder = washCarOrderManager.updateWashOrder(order);
				//16为取消订单
				String name = "";
				if ("CUST".equals(type)) {//用户自己取消
					Customer cust = customerManager.get(Long.parseLong(userId));
					name = cust.getUserName();
				} else {//主管取消
					User user = userManager.get(Long.parseLong(userId));
					if (user != null) {
						name = user.getFullName() == null ? user.getUsername() : user.getFullName();
					}
				}
				billOperationRecodesManager.saveRecode(washOrder.getId(), 3, 16, Long.parseLong(userId)
						, "取消订单成功", name + "将单据取消，订单号为：" + order.getOrderNo());
				res = "SUCCESS";
			}
		}
		return res;
	}

	@Override
	public String transferBill(SlipInputDto dto, String userId)
			throws Exception {
		//修改单据的状态及洗车员
		//添加操作记录
		String res = "FAIL";
		if (StringUtils.isNotEmpty(dto.getId())) {
			if (washCarOrderManager.exists(Long.parseLong(dto.getId()))) {
				WashCarOrder order = washCarOrderManager.get(Long.parseLong(dto.getId()));
				if (order != null) {
					order.setStatus("5");
					order.setModifyTime(new Date());
					order.setModifier(userId);
					order.setCarWasherId(dto.getSlipUserId());
					WashCarOrder washOrder = washCarOrderManager.updateWashOrder(order);
					//16为取消订单
					User   user = userManager.get(Long.parseLong(userId));
					String name = "";
					if (user != null) {
						name = user.getFullName() == null ? user.getUsername() : user.getFullName();
					}
					String slipName = "";
					User   slipuser = userManager.get(Long.parseLong(dto.getSlipUserId()));
					if (slipuser != null) {
						slipName = slipuser.getFullName() == null ? slipuser.getUsername() : slipuser.getFullName();
					}
					billOperationRecodesManager.saveRecodeSlip(washOrder.getId(), 3, 15, Long.parseLong(userId)
							, "转单成功", name + "将单据转给" + slipName, dto.getSlipReason(), dto.getRemark());
					res = "SUCCESS";
				}
			}
		}
		return res;
	}

	@Override
	public String updateWashOrder(Long id, Integer type, String userId, String keySpace, String parkSpace)
			throws Exception {
		String res = "FAIL";
		if (washCarOrderManager.exists(id)) {
			WashCarOrder washOrder = washCarOrderManager.get(id);
			washOrder.setModifier(userId);
			washOrder.setModifyTime(new Date());
			if (type == 1) {//取钥匙
				washOrder.setStatus("3");
				washOrder.setIsGetKey(1);
				User   user = userManager.get(Long.parseLong(userId));
				String name = "";
				if (user != null) {
					name = user.getFullName() == null ? user.getUsername() : user.getFullName();
				}
				billOperationRecodesManager.saveRecode(washOrder.getId(), 3, 13, Long.parseLong(userId)
						, "成功取出钥匙", name + "成功取出钥匙，开始洗车.");
			} else if (type == 2) {//已完成
				washOrder.setStatus("4");
				washOrder.setKeySpace(keySpace);
				washOrder.setParkSpace(parkSpace);
				User   user = userManager.get(Long.parseLong(userId));
				String name = "";
				if (user != null) {
					name = user.getFullName() == null ? user.getUsername() : user.getFullName();
				}
				billOperationRecodesManager.saveRecode(washOrder.getId(), 3, 14, Long.parseLong(userId)
						, "已完成订单", name + "已将车辆清洗完毕.");
			}
			washCarOrderManager.updateWashOrder(washOrder);
			res = "SUCCESS";
		}
		return res;
	}

	@Override
	public int getWashCountByDas(String projectId) throws Exception {
		int                num    = 0;
		ProjectSet         proSet = projectSetManager.fingByProjectId(projectId);
		List<WashCarOrder> list   = washCarOrderManager.getWashListByDas("", "6", 2);
		if (proSet != null) {
			if (list != null && list.size() > 0) {
				num = proSet.getQuota() - list.size();
			} else {
				num = proSet.getQuota();
			}
		}
		return num;
	}

	/**
	 * 判断是否存在
	 *
	 * @param id
	 * @return
	 */
	@Override
	public boolean exists(Long id) {
		return washCarOrderManager.exists(id);
	}

	/**
	 * 查找洗车订单
	 */
	@Override
	public WashCarOrder findById(Long id) {
		return washCarOrderManager.get(id);
	}

}
