package com.palmnest.service.estateserve.airconditioner.impl;

import com.palmnest.application.GoodsCodeConstants;
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.DateHelper;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.input.AirRuleInputDto;
import com.palmnest.application.dto.output.AirRuleOutDto;
import com.palmnest.model.User;
import com.palmnest.model.airconditioner.AirRule;
import com.palmnest.service.AppUserService;
import com.palmnest.service.estateserve.airconditioner.AirRuleManager;
import com.palmnest.service.estateserve.airconditioner.AirRuleService;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("airRuleService")
public class AirRuleServiceImpl implements AirRuleService {


	@Autowired
	private AirRuleManager airRuleManager;

	@Autowired
	private AppUserService appUserService;

	@Override
	public AppResultDto addRole(AirRuleInputDto dto, HttpServletRequest request) {


		try {

			User         user             = (User) request.getSession().getAttribute("UserCache");
			List<OrgDto> organizationList = appUserService.getUserOrgs(user.getId());
			String       organizationId   = "0";
			if (organizationList.size() >= 1) {
				organizationId = organizationList.get(0).getId().toString();
			}


			AirRule airRule = new AirRule();
			BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
			BeanUtils.copyProperties(airRule, dto);

			if (user != null) {
				airRule.setCreator(user.getFullName());
				airRule.setModifier(user.getFullName());
			}
			airRule.setCreateTime(new Date());
			airRule.setModifyTime(new Date());

			airRule.setIsEnabled(1);

			if (organizationList.size() >= 1) {
				airRule.setOrganizationId(Long.decode(organizationId));
			}

			//每户350元/每小时
			//每平米0.15元/小时			
			//String priceHouse = "每户" + airRule.getPriceHouse() + "元/每小时";//每户
			String priceHour  = "每平米" + airRule.getPriceHour() + "元/小时";//每平米
			
			//单价类型(1-平米每小时、2-层（半层）每小时)
			if(airRule.getPriceType().equals(2)){
				priceHour  = "每层" + airRule.getFloorPriceHour() + "元/小时";//每平米
				priceHour = priceHour + "," + "每半层" + airRule.getHalfFloorPriceHour() + "元/小时";
			}			
			
			airRule.setPriceDisplay(priceHour);
			
			

			//日期类型(1工作日\2休息日3节假日
			//工作日00:00~08:00
			String  chargeTimeDisplay = "";
			String  dataTypeStr       = "";
			Integer dataType          = dto.getDataType();
			if (dataType == GoodsCodeConstants.DATATYPE_WORKINGDAY) {//工作日
				dataTypeStr = "工作日";
			} else if (dataType == GoodsCodeConstants.DATATYPE_RESTDAY) {//休息日
				dataTypeStr = "休息日";
			} else if (dataType == GoodsCodeConstants.DATATYPE_VACATIONS) {//节假日
				dataTypeStr = "节假日";
			}

			String startTimeStr = DateUtils.getDate(airRule.getStartTime(), "HH:mm");
			String endTimeStr   = DateUtils.getDate(airRule.getEndTime(), "HH:mm");

			chargeTimeDisplay = dataTypeStr + startTimeStr + "~" + endTimeStr;
			airRule.setChargeTimeDisplay(chargeTimeDisplay);


			AirRule bill = airRuleManager.save(airRule);

			JSONObject json = new JSONObject();
			json.put("billId", bill.getId().toString());
			json.put("roleName", bill.getRuleName());


			return AppResultUtil.createSuccesDto(json);

		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public Page findPageBy(Map<String, Object> params, int pageSize, int pageNo) {
		return airRuleManager.findPageBy(params, pageSize, pageNo);
	}

	@Override
	public AppResultDto enableOrDisable(HttpServletRequest request) {

		String billId        = request.getParameter("id");
		String operationType = request.getParameter("operationType");

		AirRule airRule = airRuleManager.get(Long.decode(billId));
		if (operationType.equals("enable")) {
			airRule.setIsEnabled(1);
		} else if (operationType.equals("disable")) {
			airRule.setIsEnabled(0);
		}

		airRuleManager.save(airRule);


		return AppResultUtil.createSuccesDto();
	}

	@Override
	public AppResultDto del(HttpServletRequest request) {

		String billId = request.getParameter("id");
		airRuleManager.remove(Long.decode(billId));

		return AppResultUtil.createSuccesDto();
	}

	@Override
	public java.util.List<AirRule> getAirRule(Integer organizationId, Integer applicationType, Integer meetingOrAirAddTime, Integer dataType,
											  String startTime, String endTime) {


		return airRuleManager.getAirRule(organizationId, applicationType, meetingOrAirAddTime, dataType, startTime, endTime);
	}

	@Override
	public AirRuleOutDto findById(Long id) {

		try {
			return this.convert(airRuleManager.get(id));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public AirRuleOutDto convert(AirRule airRule) throws Exception {

		DecimalFormat df4 = new DecimalFormat();
		df4.applyPattern("0.00");
		AirRuleOutDto dto = new AirRuleOutDto();

		dto.setRuleName(airRule.getRuleName());
		//dto.setApplicationType(airRule.getApplicationType().toString());


		dto.setApplicationMeeting(airRule.getApplicationMeeting() == null ? "" : airRule.getApplicationMeeting().toString());
		dto.setApplicationAirAddTime(airRule.getApplicationAirAddTime() == null ? "" : airRule.getApplicationAirAddTime().toString());

		dto.setDataType(airRule.getDataType().toString());
		dto.setPriceType(airRule.getPriceType().toString());
		dto.setStartTime(DateHelper.formatDate(airRule.getStartTime(), DateHelper.TIME_HOUR_MINUTE));
		dto.setEndTime(DateHelper.formatDate(airRule.getEndTime(), DateHelper.TIME_HOUR_MINUTE));
		dto.setPriceHour(df4.format(airRule.getPriceHour().setScale(2)));
		dto.setPriceHouse(df4.format(airRule.getPriceHouse().setScale(2)));
		
		if(null != airRule.getFloorPriceHour()){
			dto.setFloorPriceHour(df4.format(airRule.getFloorPriceHour().setScale(2)));
		}		
		if(null != airRule.getHalfFloorPriceHour()){
			dto.setHalfFloorPriceHour(df4.format(airRule.getHalfFloorPriceHour().setScale(2)));
		}		

		dto.setRemark(airRule.getRemark());

		return dto;
	}

}
