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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sys.common.entity.User;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmOrderSiteSettlementTemplateDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmOrderSiteSettlementTemplate;
import com.sifang.modules.sunshine.SystemSetting.form.StaticParamsCode;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.persistence.Page;
import com.sifang.modules.sys.common.service.BaseService;


@Service
public class CrmOrderSiteSettlementTemplateService extends BaseService {
	@Autowired
	private CrmOrderSiteSettlementTemplateDao crmOrderSiteSettlementTemplateDao;


	public List<Record> getListByNumberAndCategoryExcept(String serviceType, String serviceStep, String warrType) {
		return Db.find("select a.* from crm_order_site_settlement_template a where a.status='0' and a.service_type=? and a.service_step=? and a.warranty_type=?", serviceType, serviceStep, warrType);
	}


	public List<Record> getListByNumberAndNotById(String serviceType, String serviceStep, String warrType,String id) {
		return Db.find("select a.* from crm_order_site_settlement_template a where a.status='0' and a.service_type=? and a.service_step=? and a.warranty_type=? and a.id != ?", serviceType, serviceStep, warrType,id);
	}


	// 获取信息列表分页信息
	public Page<Record> loadSettlementSetPage(Page<Record> page, Map<String, String> map) {
		List<Record> list = getSettlementSetList(page, map);
		Long count = getCounts(map);
		page.setCount(count);
		page.setList(list);
		return page;
	}

    // 获取服务商结算设置-列表分页信息
	public List<Record> getSettlementSetList(Page<Record> page, Map<String, String> map) {
		StringBuilder sb = new StringBuilder("");
		sb.append("select a.number,any_value(a.warranty_type) as warranty_type,any_value(a.service_type) as service_type,any_value(a.service_content) as service_content,any_value(a.charge_amount) as charge_amount,any_value(a.service_step) as service_step from crm_order_site_settlement_template a where a.status ='0' ");
		sb.append(sqlConditions(map));
		sb.append(" group by a.number,category  ");
		sb.append(" order by any_value(a.create_time) desc  ");
		if (page != null) {
			sb.append(" limit " + page.getPageSize() + " offset " + (page.getPageNo() - 1) * page.getPageSize());
		}
		List<Record> list = Db.find(sb.toString());
		return list;
	}

    // 列表查询条件
	public String sqlConditions(Map<String, String> map) {
		StringBuilder sb = new StringBuilder("");
		if (map != null) {
			if (StringUtil.checkParamsValid(map.get("serviceType"))) {
				sb.append(" and a.service_type = '" + map.get("serviceType") + "'");
			} else {
				sb.append(" and a.service_type = '" + map.get("defaultserviceType") + "'");
			}
		}
		return sb.toString();
	}

    // 根据品类、编码获取服务商结算项的count(数量)
	public Long getCounts(Map<String, String> map) {
		StringBuilder sb = new StringBuilder("");
		sb.append("SELECT COUNT(*) FROM (select a.number,a.category from crm_order_site_settlement_template a where a.status ='0' ");
		sb.append(sqlConditions(map));
		sb.append(" group by a.number,category  ");
		sb.append(" ) AS tt   ");
		return Db.queryLong(sb.toString());
	}

    // 删除服务商结算设置项-保存操作
	@Transactional(rollbackFor = Exception.class)
	public Result<Void> saveDelSiteSettlementSet(Map<String, String> map) {
		String ids = map.get("ids") != null ? map.get("ids").toString() : "";
		if (StringUtils.isBlank(ids) ) {// 品类和结算编码不能为空
			return Result.fail("参数信息有误，请检查！");
		}
		SQLQuery sql = crmOrderSiteSettlementTemplateDao.getSession()
				.createSQLQuery("update crm_order_site_settlement_template a set a.status='1',update_time=now() where  a.id in ("
						+ StringUtil.joinInSql(ids.split(",")) + ")");
		sql.executeUpdate();// 更新结算设置表信息
		return Result.ok();

	}

	public Record getById(String id ){
		String sql ="SELECT * FROM crm_order_site_settlement_template WHERE id=? ";
		return Db.findFirst(sql,id);
	}


	// 新增服务商结算设置-保存操作
	@Transactional(rollbackFor = Exception.class)
	public Result<Void> addSaveSiteSettlementSet(Map<String, String> map) {
		String warrantyType = map.get("warrantyType") != null ? map.get("warrantyType").toString() : "1";
		String serviceType = map.get("serviceType") != null ? map.get("serviceType").toString() : "";
		String category = map.get("category") != null ? map.get("category").toString() : "";
		String serviceStep = map.get("serviceStep") != null ? map.get("serviceStep").toString() : "";
		String serviceContent = map.get("serviceContent") != null ? map.get("serviceContent").toString() : "";
		String chargeAmount = map.get("chargeAmount") != null ? map.get("chargeAmount").toString() : "0";
		// 根据品类、结算编码查询结算设置项
		List<Record> count = getListByNumberAndCategoryExcept(serviceType, serviceStep,warrantyType);
		if (count.size() > 0) {// 已存在该设置项则不允许添加
			return Result.fail("服务措施为" + serviceStep + "的结算方案已存在！");
		}
		Date dt = new Date();
		String createBy = UserUtils.getUser().getId();
			CrmOrderSiteSettlementTemplate csst = new CrmOrderSiteSettlementTemplate();
			csst.setCategory(category);
			csst.setCreateBy(createBy);
			csst.setCreateTime(dt);
			csst.setNumber(PlantformUtils.getSiteNumber());
			csst.setServiceType(serviceType);
			csst.setStatus(StaticParamsCode.STATUS_0);
			csst.setWarrantyType(warrantyType);
			csst.setServiceContent(serviceContent);
			csst.setServiceStep(serviceStep);
			csst.setChargeAmount(new BigDecimal(chargeAmount));
			crmOrderSiteSettlementTemplateDao.save(csst);
		return Result.ok();
	}

	// 修改服务商结算设置-保存操作
	@Transactional(rollbackFor = Exception.class)
	public Result<Void> editSaveSiteSettlementSet(Map<String, String> map) {
		String id = map.get("id");
		String warrantyType = map.get("warrantyType") != null ? map.get("warrantyType").toString() : "";
		String serviceType = map.get("serviceType") != null ? map.get("serviceType").toString() : "";
		String serviceStep = map.get("serviceStep") != null ? map.get("serviceStep").toString() : "";
		String serviceContent = map.get("serviceContent") != null ? map.get("serviceContent").toString() : "";
		// 金额信息，json格式字符串
		String chargeAmount = map.get("chargeAmount") != null ? map.get("chargeAmount").toString() : "0";
		// 根据品类、结算编码查询对应结算设置信息
		List<Record> listOldExist = getListByNumberAndNotById(serviceType, serviceStep, warrantyType,id);
		if (listOldExist.size() > 0) {
			return Result.fail("该服务措施结算" + serviceStep + "已存在！");
		}
		List<CrmOrderSiteSettlementTemplate> list = new ArrayList<CrmOrderSiteSettlementTemplate>();
		Date dt = new Date();
			CrmOrderSiteSettlementTemplate csst = crmOrderSiteSettlementTemplateDao.get(id);
			csst.setUpdateTime(dt);
			csst.setServiceType(serviceType);
			csst.setStatus(StaticParamsCode.STATUS_0);
			csst.setWarrantyType(warrantyType);
			csst.setServiceStep(serviceStep);
			csst.setServiceContent(serviceContent);
			csst.setChargeAmount(new BigDecimal(chargeAmount));

			// 在保存添加的数据
			crmOrderSiteSettlementTemplateDao.save(list);

		return Result.ok();
	}

}
