package com.style24.admin.biz.service;

import java.io.IOException;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gagaframework.excel.GagaExcelUtil;
import com.gagaframework.excel.env.GagaExcelConstants;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.admin.biz.dao.TsaOcmDao;
import com.style24.admin.support.env.TsaConstants;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Extmall;
import com.style24.persistence.domain.ExtmallNoti;
import com.style24.persistence.domain.ExtmallOrigin;
import com.style24.persistence.domain.ExtmallPriceSync;
import com.style24.persistence.domain.ExtmallUsac;

import lombok.extern.slf4j.Slf4j;

/**
 * 영업망관리 Service
 *
 * @author gagamel
 * @since 2020. 11. 4
 */
@Service
@Slf4j
public class TsaOcmService {

    @Autowired
    private TscMessageByLocale message;

    @Autowired
    private TsaOcmDao ocmDao;

    @Autowired
	private Environment env;
    
    @Autowired
	private ObjectMapper mapper;
    
    /**
     * 제휴몰 목록
     * @param extmall - 제휴몰 정보
     * @return
     * @author gagamel
     * @since 2020. 11. 5
     */
    public Collection<Extmall> getExtmallList(Extmall extmall) {
        return ocmDao.getExtmallList(extmall);
    }

    /**
     * 제휴몰 등록/수정 처리
     * @param extmall - 제휴몰 정보
     * @author gagamel
     * @since 2020. 11. 5
     */
    @Transactional("shopTxnManager")
    public void saveExtmall(Extmall extmall) {
        extmall.setRegNo(TsaSession.getInfo().getUserNo());
        extmall.setUpdNo(TsaSession.getInfo().getUserNo());
        ocmDao.saveExtmall(extmall);
    }

    /**
     * 제휴몰 고시정보 목록
     * @param extmallNoti - 제휴몰고시정보
     * @return
     * @author gagamel
     * @since 2020. 11. 6
     */
    public Collection<ExtmallNoti> getExtmallNotiinfoList(ExtmallNoti extmallNoti) {
        return ocmDao.getExtmallNotiinfoList(extmallNoti);
    }

    /**
     * 제휴몰 원산지 목록
     * @param extmallOrigin - 제휴몰원산지 정보
     * @return
     * @author gagamel
     * @since 2020. 11. 12
     */
    public Collection<ExtmallOrigin> getExtmallOriginList(ExtmallOrigin extmallOrigin) {
        return ocmDao.getExtmallOriginList(extmallOrigin);
    }

    /**
     * 제휴몰가격연계 목록
     * @param extmallPriceSync - 제휴몰가격연계 정보
     * @return
     * @author gagamel
     * @since 2020. 11. 7
     */
    public Collection<ExtmallPriceSync> getExtmallPriceSyncList(ExtmallPriceSync extmallPriceSync) {
        return ocmDao.getExtmallPriceSyncList(extmallPriceSync);
    }

    /**
     * 제휴몰가격연계 등록/수정
     * @param extmallPriceSyncList - 제휴몰가격연계 목록
     * @author gagamel
     * @since 2020. 11. 7
     */
    public void saveExtmallPriceSync(Collection<ExtmallPriceSync> extmallPriceSyncList) {
        for (ExtmallPriceSync extmallPriceSync : extmallPriceSyncList) {
            extmallPriceSync.setRegNo(TsaSession.getInfo().getUserNo());
            extmallPriceSync.setUpdNo(TsaSession.getInfo().getUserNo());
            ocmDao.saveExtmallPriceSync(extmallPriceSync);
        }
    }

    /**
	 * 제휴몰정산가격업로드-목록 건수
	 *
	 * @param extmallUsac
	 * @return
	 * @author jmh
	 * @since 2020. 8. 3
	 */
	public int getExtmallUsacListCount(ExtmallUsac extmallUsac) {
		return ocmDao.getExtmallUsacListCount(extmallUsac);
	}

	/**
	 * 제휴몰정산가격업로드-목록
	 *
	 * @param extmallUsac
	 * @return
	 * @author jmh
	 * @since 2020. 8. 3
	 */
	public Collection<ExtmallUsac> getExtmallUsacList(ExtmallUsac extmallUsac) {
		return ocmDao.getExtmallUsacList(extmallUsac);
	}

	/**
	 * 제휴몰정산가격업로드-목록 엑셀다운로드
	 *
	 * @param extmallOrder
	 * @param excelFilenameWithPath - 경로를 포함한 엑셀파일명
	 * @return
	 * @author jmh
	 * @since 2021. 8. 3
	 */
	public void getExtmallUsacExcelList(ExtmallUsac extmallUsac, String excelFilenameWithPath) {

		// 헤더 title 설정
		String[] listTitles = {"단품이력일련번호", "주문번호", "주문상세번호", "상품코드", "상품명", "옵션코드", "옵션1", "옵션2", "단품수량"
				, "단품단가", "정산가", "제휴몰명", "공급업체명", "브랜드명", "유통구분명", "등록자", "등록일", "수정자", "수정일"};
		

		// DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellNames = {"ORD_DTL_ITEM_HST_SQ", "ORD_NO", "ORD_DTL_NO", "GOODS_CD", "GOODS_NM", "OPT_CD", "OPT_CD1", "OPT_CD2", "ITEM_QTY"
				, "ITEM_PRICE", "USAC_PRICE", "EXTMALL_NM", "SUPPLY_COMP_NM", "BRAND_ENM", "DISTRIBUTION_GB_NM", "REG_NM", "REG_DT", "UPD_NM", "UPD_DT"};

		String[] cellTypes = {
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name()};

		Collection<GagaMap> dataList = ocmDao.getExtmallUsacExcelList(extmallUsac);

		try {

			GagaExcelUtil.createExcel(excelFilenameWithPath, dataList, "제휴몰정산가격", listTitles, cellNames, cellTypes, TsaConstants.EXCEL_FOOTER_TITLE);

		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	
	/**
	 * 제휴몰정산가격업로드 엑셀 저장
	 *
	 * @param excelExtmallOrderList
	 * @param excelFilename - 엑셀파일명
	 * @return void
	 * @author jmh
	 * @since 2021. 08. 16
	 */
	@Transactional("shopTxnManager")
	public void createExtmallUsacExcelupload(Collection<GagaMap> excelList, String excelFilename) {
		String targetPath = env.getProperty("upload.excel.target.path");

		if ((excelList == null || excelList.isEmpty())) {
			try {
				GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, excelFilename));
			} catch (IOException e) {
				// Nothing Do
			}
			throw new IllegalStateException(message.getMessage("FAIL_0001"));
		}

		int dataIndex = 2;
		int index = 0;
		String vendorId = "";
		for (GagaMap gagaMap : excelList) {
			gagaMap.setString("ordDtlItemHstSq", gagaMap.getString("ordDtlItemHstSq").replaceAll(",", ""));
			gagaMap.setString("usacPrice", gagaMap.getString("usacPrice").replaceAll(",", ""));

			ExtmallUsac extmallUsac = mapper.convertValue(gagaMap, ExtmallUsac.class);
			String[] params = extmallUsac.getParams();
			String[] columns = extmallUsac.getColumns();

			for (int validation = 0; validation < params.length; validation++) {
				if ("".equals(params[validation]) || params[validation] == null || "null".equals(params[validation])) {
					throw new IllegalStateException(dataIndex + "행에 " + columns[validation] + "(을)를 입력해 주세요.");
				}
			}
			
			extmallUsac.setRegNo(TsaSession.getInfo().getUserNo());
			extmallUsac.setUpdNo(TsaSession.getInfo().getUserNo());
			ocmDao.createExtmallUsacExcelupload(extmallUsac);
			dataIndex++;
			index++;
		}
	}
}
