package com.zjrs.appcomm.template.excel.mapper;

import com.zjrs.appcomm.template.excel.exception.IllegalHeaderException;
import org.springframework.util.StringUtils;

/**
 * Excel静态表头Mapper
 * @author froms
 *
 */
public class StaticHeaderMapper implements StringHeaderMapper {

	/** 静态表头Mapper字段 */
	private String[] fields;
	public String[] getFields() { return fields; }
	public void setFields(String[] fields) { this.fields = fields; }

	/** 期望的静态表头 */
	private String[] expectHeaders;
	public String[] getExpectHeaders() { return expectHeaders; }
	public void setExpectHeaders(String[] expectHeaders) { this.expectHeaders = expectHeaders; }

	/** 是否忽略Excel中多余的表头 */
	private boolean ignoreMoreHeaders;
	public boolean isIgnoreMoreHeaders() { return ignoreMoreHeaders; }
	public void setIgnoreMoreHeaders(boolean ignoreMoreHeaders) { this.ignoreMoreHeaders = ignoreMoreHeaders; }

	/**
	 * Excel静态表头Mapper（不校验期望表头）
	 * @param fields 静态表头Mapper字段
	 */
	public StaticHeaderMapper(String[] fields) {
		this(fields, null, true);
	}
	
	/**
	 * Excel静态表头Mapper（校验期望表头）
	 * @param fields 静态表头Mapper字段
	 * @param expectHeaders 期望的静态表头
	 * @param ignoreMoreHeaders 是否忽略Excel中多余的表头
	 */
	public StaticHeaderMapper(String[] fields, String[] expectHeaders, boolean ignoreMoreHeaders) {
		this.fields = fields;
		this.expectHeaders = expectHeaders;
		this.ignoreMoreHeaders = ignoreMoreHeaders;
	}
	
	@Override
	public String[] mapper(String[] headers) throws IllegalHeaderException {
		if (this.expectHeaders != null) {
			if (headers.length < this.expectHeaders.length) {
				throw new IllegalHeaderException(headers);
			}
			for (int i = 0; i < this.expectHeaders.length; i++) {
				if (!isHeaderEquals(this.expectHeaders[i], headers[i]) ) {
					throw new IllegalHeaderException(headers);
				}
			}
			if (!this.ignoreMoreHeaders) {
				for (int i = this.expectHeaders.length; i < headers.length; i++) {
					if (!StringUtils.isEmpty(headers[i]) ) {
						throw new IllegalHeaderException(headers);
					}
				}
			}
		}
		return this.fields;
	}

	/**
	 * 判断表头是否相等
	 * @param header1 表头1
	 * @param header2 表头2
	 * @return 是否相等
	 */
	private boolean isHeaderEquals(String header1, String header2) {
		if (StringUtils.isEmpty(header1)) {
			if (StringUtils.isEmpty(header2)) {
				return true;
			} else {
				return false;
			}
		} else {
			return header1.equals(header2);
		}
	}
}
