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

import cn.jiguang.common.utils.StringUtils;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.dto.input.CustomerInputDto;
import com.palmnest.model.estateserve.SmsAuthCode;
import com.palmnest.model.washcar.Customer;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.washcar.manager.CustomerManager;
import com.palmnest.service.washcar.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 用户service实现类
 *
 * @author longmeizhen
 */
@Slf4j
@SuppressWarnings("rawtypes")
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {


	@Autowired
	private CustomerManager customerManager;

	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;

	@SuppressWarnings("unchecked")
	@Override
	public AppResultDto importUserInfo(InputStream ins, String userId) throws Exception {
		//导入excel中的数据
		Map<String, Object> retMap   = customerManager.importUserInfo(ins, userId);
		int                 bugCount = Integer.parseInt(retMap.get("bugCount").toString());
		if (bugCount > 0) {//如果bug数量大于0，说明有异常，直接返回异常即可
			return AppResultUtil.createErrorDto("100", retMap.get("bugStr").toString());
		} else {//否则的话就将用户信息保存到数据库表中
			if (retMap.containsKey("userList")) {
				List<Customer> list = (List<Customer>) retMap.get("userList");
				try {
					String res = customerManager.saveImportUser(list);//保存用户信息
					if ("SUCCESS".equals(res)) {
						return AppResultUtil.createSuccesDto();
					} else {
						return AppResultUtil.createErrorDto("100", "保存导入用户数据失败：(CustomerServiceImpl/importUserInfo)" + res);
					}

				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
					return AppResultUtil.createErrorDto("100", "导入用户数据失败：CustomerServiceImpl/importUserInfo：" + e.getMessage());
				}
			} else {
				return AppResultUtil.createErrorDto("100", "导入用户数据失败：获取不到userList");
			}
		}
	}

	@Override
	public String saveCustomer(CustomerInputDto customerInputDto, String userId)
			throws Exception {
		Customer customer = new Customer();
		if (StringUtils.isNotEmpty(customerInputDto.getId())) {
			customer = customerManager.get(Long.parseLong(customerInputDto.getId()));
		}
		customer.setCarNumber(customerInputDto.getCarNumber());
		customer.setCarType(customerInputDto.getCarType());
		customer.setDept(customerInputDto.getDept());
		if (StringUtils.isNotEmpty(customerInputDto.getId())) {
			customer.setId(Long.parseLong(customerInputDto.getId()));
		}
		customer.setIsEnabled("1");
		customer.setMobile(customerInputDto.getMobile());
		customer.setUserName(customerInputDto.getUserName());
		customer.setPosition(customerInputDto.getPosition());
		customer.setParkSpace(customerInputDto.getParkSpace());
		customer.setSerialNumber(customerInputDto.getSerialNumber());
		customer.setOrgId(customerInputDto.getOrgId());
		String result = customerManager.saveCustomer(customer, userId);
		return result;
	}

	@Override
	public String deleteCustomer(Long custId, String userId) throws Exception {
		return customerManager.deleteCustomer(custId, userId);
	}


	@Override
	public Page getCustList(String orgIds, String mobile, String userName, String carNumber, String searchStr, int pageNo, int pageSize)
			throws Exception {
		return customerManager.getCustList(orgIds, mobile, userName, carNumber, searchStr, pageNo, pageSize);
	}

	@Override
	public CustomerInputDto findById(Long id) {
		CustomerInputDto dto = new CustomerInputDto();
		if (id != null && id != 0) {
			if (customerManager.exists(id)) {
				Customer cust = customerManager.get(id);
				dto.setCarNumber(cust.getCarNumber());
				dto.setCarType(cust.getCarType());
				dto.setDept(cust.getDept());
				dto.setId(cust.getId().toString());
				dto.setMobile(cust.getMobile());
				dto.setParkSpace(cust.getParkSpace());
				dto.setPosition(cust.getPosition());
				dto.setSerialNumber(cust.getSerialNumber());
				dto.setUserName(cust.getUserName());
			}
		}
		return dto;
	}

	@Override
	public Customer getCustByMobile(String orgId, String mobile) throws Exception {
		return customerManager.getCustByMobile(orgId, mobile);
	}

	@Override
	public int isExistence(String mobile, String code) throws Exception {

		SmsAuthCode smsCode = smsAuthCodeManager.getSmsAuthCode(mobile, code, "1", 2);
		if (smsCode == null) {
			return 1;
		}
		return 2;
	}

	@Override
	public Customer getCustByOpenId(String orgId, String openId) throws Exception {
		return customerManager.getCustByOpenId(orgId, openId);
	}

	@Override
	public String exitLogin(String orgId, String openId) {
		String res = "FAIL";
		try {
			Customer cust = customerManager.getCustByOpenId(orgId, openId);
			if (cust != null) {
				cust.setOpenId("");
				cust.setModifier(openId);
				cust.setModifyTime(new Date());
				customerManager.updateModel(cust);
				res = "SUCCESS";
			} else {
				res = "查不到该用户";
			}
		} catch (Exception e) {
			log.error("退出失败：" + e.getMessage());
			e.printStackTrace();
			res = "退出失败：" + e.getMessage();
		}
		return res;
	}

	/**
	 * 修改用户
	 *
	 * @param cust
	 */
	@Override
	public void updateCustomer(Customer cust) {
		customerManager.updateModel(cust);
	}

}
