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

import com.zfire.jiasm.syncdata.service.WorkerOrderUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WorkerOrderUploadServiceImpl implements WorkerOrderUploadService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<Map<String, Object>> getTaskData(int taskType,String limitTimes) {
		String limitCondition="";
		if(limitTimes!=null && new Integer(limitTimes)>0) {
			limitCondition=" and syn_times<="+limitTimes+" ";
		}
		List<Map<String, Object>> result = jdbcTemplate
				.queryForList("SELECT * FROM itf_fa_to_gree_upload_task_list where syn_status=0 "
						+ " and upload_task_type=? "+limitCondition+" order by syn_req_id ", new Object[] { taskType });
		return result;
	}

	@Override
	public List<Map<String, Object>> getTaskType() {
		List<Map<String, Object>> result = jdbcTemplate
				.queryForList("SELECT * FROM itf_fa_to_gree_upload_task_type order by id ");
		return result;
	}

	@Override
	public Map<String, Object> getATaskData(int synReqId) {
		return jdbcTemplate.queryForMap("SELECT * FROM itf_fa_to_gree_upload_task_list where syn_req_id=? ",
				new Object[] { synReqId });
	}

	// 过程名称，同步任务表中的id,同步任务表中的工单号，同步任务表中的需同步的表的主键，空，false
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void prepareData(String synProcName, int taskId, String workerOrderNo, int orderId, String remoteId,
			boolean isNeedGenRemoteId) throws Exception {
		Map<String, Object> result = jdbcTemplate.execute(new CallableStatementCreator() {

			public CallableStatement createCallableStatement(Connection con) throws SQLException {

				CallableStatement cs = null;
				if (workerOrderNo == null) {

					cs = con.prepareCall("{call " + synProcName + "(?,?,?,?)}");
					cs.setInt(1, taskId);
					cs.setInt(2, orderId);
					cs.registerOutParameter(3, Types.BOOLEAN);
					cs.registerOutParameter(4, Types.VARCHAR);

				} else {

					if (isNeedGenRemoteId) {
						cs = con.prepareCall("{call " + synProcName + "(?,?,?,?,?,?)}");
						cs.setInt(1, taskId);
						cs.setString(2, workerOrderNo);
						cs.setInt(3, orderId);
						cs.setString(4, remoteId);
						cs.registerOutParameter(5, Types.BOOLEAN);
						cs.registerOutParameter(6, Types.VARCHAR);
					} else {
						cs = con.prepareCall("{call " + synProcName + "(?,?,?,?,?)}");
						cs.setInt(1, taskId);
						cs.setString(2, workerOrderNo);
						cs.setInt(3, orderId);
						cs.registerOutParameter(4, Types.BOOLEAN);
						cs.registerOutParameter(5, Types.VARCHAR);
					}

				}

				return cs;
			}
		}, new CallableStatementCallback<Map<String, Object>>() {

			public Map<String, Object> doInCallableStatement(CallableStatement cs)
					throws SQLException, DataAccessException {

				cs.execute();

				int startIndex;
				if (workerOrderNo == null) {
					startIndex = 3;
				} else {
					if (isNeedGenRemoteId) {
						startIndex = 5;
					} else {
						startIndex = 4;
					}
				}

				boolean status = cs.getBoolean(startIndex);
				String errorMessage = cs.getString(startIndex + 1);

				Map<String, Object> result = new HashMap<String, Object>();
				result.put("status", status);
				result.put("errorMessage", errorMessage);

				return result;

			}
		});

		if (!(Boolean) result.get("status")) {
			throw new SQLException("执行过程[" + synProcName + "[workerOrderNo=" + workerOrderNo + ",orderId=" + orderId
					+ ",remoteId=" + remoteId + "]]发生错误[" + result.get("errorMessage") + "]");
		}

	}

	@Override
	public Long getPgid(String procName, String workerOrderNo, int id) throws Exception {
		return jdbcTemplate.execute(new CallableStatementCreator() {

			public CallableStatement createCallableStatement(Connection con) throws SQLException {

				CallableStatement cs = null;
				cs = con.prepareCall("{call " + procName + "(?,?,?,?,?)}");
				cs.setString(1, workerOrderNo);
				cs.setInt(2, id);
				cs.registerOutParameter(3, Types.BOOLEAN);
				cs.registerOutParameter(4, Types.VARCHAR);
				cs.registerOutParameter(5, Types.BIGINT);

				return cs;
			}
		}, new CallableStatementCallback<Long>() {

			public Long doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {

				cs.execute();

				boolean status = cs.getBoolean(3);
				String errorMessage = cs.getString(4);

				if (!status) {
					throw new SQLException("执行过程[" + procName + "]发生错误[" + errorMessage + "]");
				}

				Long pgid = cs.getLong(5);
				return pgid;

			}
		});
	}

	@Override
	public String getFkid(String workerOrderNo, int id) throws Exception {
		return jdbcTemplate.execute(new CallableStatementCreator() {

			public CallableStatement createCallableStatement(Connection con) throws SQLException {

				CallableStatement cs = null;
				cs = con.prepareCall("{call TL_get_fa_order_repair_operating_log_fkid(?,?,?,?,?)}");
				cs.setString(1, workerOrderNo);
				cs.setInt(2, id);
				cs.registerOutParameter(3, Types.BOOLEAN);
				cs.registerOutParameter(4, Types.VARCHAR);
				cs.registerOutParameter(5, Types.BIGINT);

				return cs;
			}
		}, new CallableStatementCallback<String>() {

			public String doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {

				cs.execute();

				boolean status = cs.getBoolean(3);
				String errorMessage = cs.getString(4);

				if (!status) {
					throw new SQLException("执行过程[TL_get_fa_order_repair_operating_log_fkid]发生错误[" + errorMessage + "]");
				}

				String fkid = cs.getString(5);
				return fkid;

			}
		});
	}


	@Override
	public boolean isFkidRepeat(String workerOrderNo, int fkid) throws Exception {
		return jdbcTemplate.execute(new CallableStatementCreator() {

			public CallableStatement createCallableStatement(Connection con) throws SQLException {

				CallableStatement cs = null;
				cs = con.prepareCall("{call TL_get_fa_order_repair_operating_log_fkid_flag(?,?,?,?,?)}");
				cs.setString(1, workerOrderNo);
				cs.setInt(2, fkid);
				cs.registerOutParameter(3, Types.BOOLEAN);
				cs.registerOutParameter(4, Types.VARCHAR);
				cs.registerOutParameter(5, Types.BOOLEAN);

				return cs;
			}
		}, new CallableStatementCallback<Boolean>() {

			public Boolean doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {

				cs.execute();

				boolean status = cs.getBoolean(3);
				String errorMessage = cs.getString(4);

				if (!status) {
					throw new SQLException("执行过程[TL_get_fa_order_repair_operating_log_fkid_flag]发生错误[" + errorMessage + "]");
				}

				return cs.getBoolean(5);

			}
		});
	}

}
