package com.sifang.modules.sunshine.SystemSetting.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmOrderMileageSettingsDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmOrderMileageSettings;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;

@Service
public class CrmOrderMileageSettingsService extends BaseService {
	@Autowired
	private CrmOrderMileageSettingsDao crmOrderMileageSettingsDao;

	// 保存 用户/服务商 里程结算设置（type:1.用户 2.服务商）
	@Transactional(rollbackFor = Exception.class)
	public Result<Void> save(Map<String,String> map) {
		String initialValueNei = map.get("initialValueNei");
		String amountNei = map.get("amountNei");

		String initialValueWai = map.get("initialValueWai");
		String amountWai = map.get("amountWai");
		String type = map.get("type");// type:1 用户 2服务商
		updaCrmOrderMileageSettings(amountNei,initialValueNei,type,"1");
		updaCrmOrderMileageSettings(amountWai,initialValueWai,type,"2");

		return Result.ok();
	}


	public void updaCrmOrderMileageSettings(String amount,String initialValue,String type,String warrType){

		Record rd = getSiteMeleageSet(type,warrType);// 先查对应的设置项记录
		if (StringUtils.isBlank(amount)) {// 超出后的每公里计价可不填，为空时赋值0，防止保存不出错（约定的规则）
			amount = "0";
		}
		if (rd == null) {// 如果对应的设置项记录不存在，则新增
			CrmOrderMileageSettings coms = new CrmOrderMileageSettings();
			coms.setAmount(new BigDecimal(amount));
			coms.setCreateBy(UserUtils.getUser().getId());
			coms.setCreateTime(new Date());
			coms.setInitialValue(new BigDecimal(initialValue));
			coms.setType(type);
			coms.setWarrantyType(warrType);
			crmOrderMileageSettingsDao.save(coms);
		} else {// 存在，则更新
			StringBuilder sb = new StringBuilder("");
			sb.append("update crm_order_mileage_settings a set a.initial_value=:initialValue,a.amount=:amount,a.update_time=now() ");
			sb.append(" where a.id=:id ");
			SQLQuery sql = crmOrderMileageSettingsDao.getSession().createSQLQuery(sb.toString());
			sql.setParameter("initialValue", initialValue);
			sql.setParameter("id", rd.getStr("id"));
			sql.setParameter("amount", amount);
			sql.executeUpdate();
		}
	}

	// 获取用户/服务商里程设置记录（type:1.平台与用户结算用户 2.服务商与平台结算）
	public Record getSiteMeleageSet(String type,String warranty_type) {
		return Db.findFirst("select a.* from crm_order_mileage_settings a where a.type=? and a.warranty_type =?  limit 1", type,warranty_type);
	}

}
