package com.zfire.jiasm.syncdata.service.impl;


import com.zfire.jiasm.syncdata.service.OLDSystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class OLDSystemServiceImpl implements OLDSystemService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<Map<String, Object>> getTableDatas(String tableName, String synTaskNo) {
		List<Map<String, Object>> result = jdbcTemplate
				.queryForList("SELECT * FROM " + tableName + " where syn_task_no=?", new Object[] { synTaskNo });
		return result;
	}

	@Override
	public void successUpdate(String tableName, String synTaskNo) {
		jdbcTemplate.update("update " + tableName + " set syn_status=1,syn_time=? where syn_task_no=?",
				new Object[] { new Date(), synTaskNo });

	}

	@Override
	public List<Map<String, Object>> getRequests(String tableName, int type) {
		List<Map<String, Object>> result;
		
		if(type==1) {
			//家用空调、热水器
			result = jdbcTemplate.queryForList(
					"SELECT * FROM " + tableName + " where syn_status=0 and spid in (101,103) order by syn_req_time,stat ",
					new Object[] { });
		}else if (type==2) {
			//商用空调
			result = jdbcTemplate.queryForList(
					"SELECT * FROM " + tableName + " where syn_status=0 and spid in (102) order by syn_req_time,stat ",
					new Object[] {});
		}else if(type==3) {
			//生活电器
			result = jdbcTemplate.queryForList(
					"SELECT * FROM " + tableName + " where syn_status=0 and spid not in (101,102,103) order by syn_req_time,stat ",
					new Object[] {});
		}else {
			//维修
			result = jdbcTemplate.queryForList(
					"SELECT * FROM " + tableName + " where syn_status=0 order by syn_req_time,stat ", new Object[] {});

		}

		return result;
	}

	@Override
	public List<Map<String, Object>> getTableDatasJoinParent(String tableName, String synTaskNo, String parentTableName,
			String parentId, String childeIdName) {
		if (childeIdName == null || childeIdName.trim().length() == 0) {
			childeIdName = "id";
		}
		
		
		List<Map<String, Object>> result = jdbcTemplate.queryForList(
				"SELECT a.* FROM " + tableName + " a," + parentTableName
						+ " b where a.syn_task_no=b.syn_task_no and a.syn_task_no=? and a." + childeIdName + "=? ",
				new Object[] { synTaskNo, parentId });
		
		if(tableName.trim().equalsIgnoreCase("itf_tblAzWgmxSyktTmmxLs")
				|| tableName.trim().equalsIgnoreCase("itf_tblazwgmxsyktfj")
				|| tableName.trim().equalsIgnoreCase("itf_tblazwgmxjyktFj")
				|| tableName.trim().equalsIgnoreCase("itf_tblAzWgmxQitaFj")
				) {
			log.info("SELECT a.* FROM " + tableName + " a," + parentTableName
					+ " b where a.syn_task_no=b.syn_task_no and a.syn_task_no="+synTaskNo+" and a." + childeIdName + "="+parentId);
		}
		
		return result;
	}

}
