package com.style24.admin.biz.service;

import java.io.File;
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 org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.style24.admin.biz.dao.TsaBusinessDao;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.biz.service.TscCommonService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Aflink;
import com.style24.persistence.domain.Bizday;
import com.style24.persistence.domain.Brand;
import com.style24.persistence.domain.BrandGroup;
import com.style24.persistence.domain.BrandMd;
import com.style24.persistence.domain.Category;
import com.style24.persistence.domain.DeliveryLoc;
import com.style24.persistence.domain.DelvFeePolicy;
import com.style24.persistence.domain.SellStore;
import com.style24.persistence.domain.ShipCompany;
import com.style24.persistence.domain.SiteBrand;
import com.style24.persistence.domain.StockSyncBase;
import com.style24.persistence.domain.SupplyCompany;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;

/**
 * 영업관리 Service
 *
 * @author gagamel
 * @since 2020. 10. 14
 */
@Service
@Slf4j
public class TsaBusinessService {

	@Autowired
	private Environment env;

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsaBusinessDao businessDao;

	@Autowired
	private TscCommonService commonService;

	@Autowired
	private TsaDisplayService displayService;

	/**
	 * 공급벤더 목록
	 * @param supplyComp - 공급업체 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 1. 18
	 */
	public Collection<SupplyCompany> getSupplyVendorList(SupplyCompany supplyComp) {
		return businessDao.getSupplyVendorList(supplyComp);
	}

	/**
	 * 공급벤더 저장 처리
	 * @param supplyComp - 공급업체 정보
	 * @author gagamel
	 * @since 2021. 1. 18
	 */
	public void saveSupplyVendor(SupplyCompany supplyComp) {
		if (!StringUtils.isEmpty(supplyComp.getSupplyVendorCd())) {
			businessDao.updateSupplyVendor(supplyComp);
		} else {
			businessDao.createSupplyVendor(supplyComp);
		}
	}

	/**
	 * 공급업체 목록
	 * @param supplyComp - 공급업체 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 14
	 */
	public Collection<SupplyCompany> getSupplyCompanyList(SupplyCompany supplyComp) {
		return businessDao.getSupplyCompanyList(supplyComp);
	}

	/**
	 * 공급업체 저장 처리
	 * @param supplyComp - 공급업체 정보
	 * @author gagamel
	 * @since 2020. 10. 14
	 */
	public void saveSupplyCompany(SupplyCompany supplyComp) {
		if (!StringUtils.isEmpty(supplyComp.getSupplyCompCd())) {
			businessDao.updateSupplyCompany(supplyComp);
		} else {
			businessDao.createSupplyCompany(supplyComp);
		}
	}

	/**
	 * 배송비정책 목록
	 * @param supplyCompCd - 공급업체코드
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 24
	 */
	public Collection<DelvFeePolicy> getDeliveryFeePolicyList(DelvFeePolicy delvFeePolicy) {
		return businessDao.getDeliveryFeePolicyList(delvFeePolicy);
	}

	/**
	 * 배송비정책 저장 처리
	 * @param supplyComp - 공급업체 정보
	 * @author gagamel
	 * @since 2020. 10. 14
	 */
	public void saveDeliveryFeePolicyList(Collection<DelvFeePolicy> delvFeePolicyList) {
		for (DelvFeePolicy delvFeePolicy : delvFeePolicyList) {
			delvFeePolicy.setRegNo(TsaSession.getInfo().getUserNo());
			delvFeePolicy.setUpdNo(TsaSession.getInfo().getUserNo());

			if (!StringUtils.isEmpty(delvFeePolicy.getDelvFeeCd())) {
				businessDao.updateDeliveryFeePolicy(delvFeePolicy);
			} else {
				businessDao.createDeliveryFeePolicy(delvFeePolicy);
			}
		}
	}

	/**
	 * 출고처 목록
	 * @param delvLoc - 출고처 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 16
	 **/
	public Collection<DeliveryLoc> getDeliveryLocList(DeliveryLoc delvLoc) {
		return businessDao.getDeliveryLocList(delvLoc);
	}

	/**
	 * 출고처 저장
	 * @param delvLoc - 출고처 정보
	 * @author gagamel
	 * @since 2020. 10. 16
	 */
	@Transactional("shopTxnManager")
	public void saveDeliveryLoc(DeliveryLoc delvLoc) {
		if (StringUtils.isEmpty(delvLoc.getUseYn())) {
			delvLoc.setUseYn("N");
		}

		businessDao.saveDeliveryLoc(delvLoc);
	}

	/**
	 * 브랜드 목록
	 * @param brand - 브랜드 정보
	 * @return
	 * @author eskim
	 * @since 2020. 10. 22
	 */
	public Collection<Brand> getBrandList(Brand brand) {
		return businessDao.getBrandList(brand);
	}

	/**
	 * 담당MD 목록
	 * @param brandMd - 담당MD 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 4
	 */
	public Collection<BrandMd> getMdList(BrandMd brandMd) {
		return businessDao.getMdList(brandMd);
	}

	/**
	 * 브랜드담당MD 목록
	 * @param brandCd - 브랜드코드
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 4
	 */
	public Collection<BrandMd> getBrandMdList(String brandCd) {
		return businessDao.getBrandMdList(brandCd);
	}

	/**
	 * 브랜드담당MD 목록 등록/수정 처리
	 * @param brandMdList - 브랜드담당MD 목록
	 * @author gagamel
	 * @since 2020. 11. 4
	 */
	@Transactional("shopTxnManager")
	public void saveBrandMdList(Collection<BrandMd> brandMdList) {
		businessDao.deleteBrandMd(brandMdList.iterator().next().getBrandCd());

		for (BrandMd brandMd : brandMdList) {
			brandMd.setRegNo(TsaSession.getInfo().getUserNo());
			brandMd.setUpdNo(TsaSession.getInfo().getUserNo());
			businessDao.createBrandMd(brandMd);
		}
	}

	/**
	 * 브랜드 노출사이트 목록
	 * @param brandCd - 브랜드코드
	 * @author gagamel
	 * @since 2020. 11. 4
	 */
	public Collection<SiteBrand> getBrandSiteList(String brandCd) {
		return businessDao.getBrandSiteList(brandCd);
	}

	/**
	 * 브랜드 노출사이트 등록/수정 처리
	 * @param siteBrandList - 브랜드사이트 목록
	 * @author gagamel
	 * @since 2020. 11. 4
	 */
	@Transactional("shopTxnManager")
	public void saveBrandSiteList(Collection<SiteBrand> siteBrandList) {
		for (SiteBrand siteBrand : siteBrandList) {
			siteBrand.setRegNo(TsaSession.getInfo().getUserNo());
			siteBrand.setUpdNo(TsaSession.getInfo().getUserNo());
//			siteBrand.setTcateCd(businessDao.getTcateCdByBrand(siteBrand));
			businessDao.saveBrandSite(siteBrand);
		}
	}

	/**
	 * 브랜드 공급업체 목록
	 * @param brandCd - 브랜드코드
	 * @author eskim
	 * @since 2021. 01. 21
	 */
	public Collection<Brand> getBrandSupplyList(String brandCd) {
		return businessDao.getBrandSupplyList(brandCd);
	}

	/**
	 * 브랜드 등록/수정
	 * @param brand - 브랜드 정보
	 * @author gagamel
	 * @since 2020. 11. 5
	 */
	@Transactional("shopTxnManager")
	public void saveBrand(Brand brand) {

		// eskim
		Collection<Brand> brandSupplyList = null;
		ObjectMapper mapper = new ObjectMapper();

		try {
			if (brand.getBrandSupplyListInfo() != null) {
				brandSupplyList = mapper.readValue(brand.getBrandSupplyListInfo(), new TypeReference<Collection<Brand>>() {
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (brand.getMode().equals("N")) { // 신규
			businessDao.createBrand(brand);
			// 자사 브랜드는 총알배송 브랜드 등록
			if ("G065_10".equals(brand.getDistributionGb()) || "G065_11".equals(brand.getDistributionGb()) || "G065_12".equals(brand.getDistributionGb())) {
				businessDao.createShotDelvBrand(brand);
			}
		} else { // 수정
			businessDao.updateBrand(brand);
		}
		//log.info("brand ={}", brand);
		if (brandSupplyList != null && !brandSupplyList.isEmpty()) {
			for (Brand brandSupply : brandSupplyList) {
				brandSupply.setRegNo(TsaSession.getInfo().getUserNo());
				brandSupply.setBrandCd(brand.getBrandCd());
				businessDao.saveBrandSupply(brandSupply);
			}

		}

		//자사 브랜드 총알배송 브랜드 적용

	}

	/**
	 * 재고연계관리 - 출고처 목록
	 * @param delvLoc - 출고처 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 7
	 */
	public Collection<DeliveryLoc> getStockSyncDeliveryLocList(DeliveryLoc delvLoc) {
		return businessDao.getStockSyncDeliveryLocList(delvLoc);
	}

	/**
	 * 재고연계관리 - 재고연계기준 목록
	 * @param stockSyncBase - 재고연계기준 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 7
	 */
	public Collection<StockSyncBase> getStockSyncBaseList(StockSyncBase stockSyncBase) {
		return businessDao.getStockSyncBaseList(stockSyncBase);
	}

	/**
	 * 재고연계관리 - 재고연계기준 저장
	 * @param stockSyncBase - 재고연계기준 정보
	 * @author gagamel
	 * @since 2020. 11. 7
	 */
	public void saveStockSyncBaseList(Collection<StockSyncBase> stockSyncBaseList) {
		for (StockSyncBase stockSyncBase : stockSyncBaseList) {
			stockSyncBase.setRegNo(TsaSession.getInfo().getUserNo());
			stockSyncBase.setUpdNo(TsaSession.getInfo().getUserNo());
			businessDao.saveStockSyncBase(stockSyncBase);
		}
	}

	/**
	 * 판매매장 목록
	 * @param sellStore - 판매매장 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	public Collection<SellStore> getSellStoreList(SellStore sellStore) {
		return businessDao.getSellStoreList(sellStore);
	}

	/**
	 * 판매매장 목록 저장 처리
	 * @param sellStoreList - 판매매장 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	@Transactional("shopTxnManager")
	public void saveSellStoreList(Collection<SellStore> sellStoreList) {
		for (SellStore sellStore : sellStoreList) {
			sellStore.setRegNo(TsaSession.getInfo().getUserNo());
			sellStore.setUpdNo(TsaSession.getInfo().getUserNo());
			businessDao.saveSellStore(sellStore);
		}
	}

	/**
	 * 제휴링크 목록
	 * @param aflink - 제휴링크 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	public Collection<Aflink> getAflinkList(Aflink aflink) {
		return businessDao.getAflinkList(aflink);
	}

	/**
	 * 제휴링크 등록/수정
	 * @param aflink - 제휴링크 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	@Transactional("shopTxnManager")
	public void saveAflink(Aflink aflink) {
		aflink.setRegNo(TsaSession.getInfo().getUserNo());
		aflink.setUpdNo(TsaSession.getInfo().getUserNo());
		businessDao.saveAflink(aflink);
	}

	/**
	 * 제휴링크 목록 삭제 처리
	 * @param aflinkList - 제휴링크 목록
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	@Transactional("shopTxnManager")
	public void deleteAflinkList(Collection<Aflink> aflinkList) {
		for (Aflink aflink : aflinkList) {
			aflink.setUpdNo(TsaSession.getInfo().getUserNo());
			businessDao.deleteAflink(aflink);
		}
	}

	/**
	 * 배송업체 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	public Collection<ShipCompany> getShipCompanyList() {
		return businessDao.getShipCompanyList();
	}

	/**
	 * 배송업체 목록 저장
	 * @param shipCompList - 배송업체 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	@Transactional("shopTxnManager")
	public void saveShipCompanyList(Collection<ShipCompany> shipCompList) {
		for (ShipCompany shipComp : shipCompList) {
			shipComp.setRegNo(TsaSession.getInfo().getUserNo());
			shipComp.setUpdNo(TsaSession.getInfo().getUserNo());
			businessDao.saveShipCompany(shipComp);
		}
	}

	/**
	 * 배송업체 목록 삭제
	 * @param shipCompList - 배송업체 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 20
	 */
	@Transactional("shopTxnManager")
	public void deleteShipCompanyList(Collection<ShipCompany> shipCompList) {
		for (ShipCompany shipComp : shipCompList) {
			shipComp.setUpdNo(TsaSession.getInfo().getUserNo());
			businessDao.deleteShipCompany(shipComp);
		}
	}

	/**
	 * 브랜드 그룹 목록
	 * @param brandGroup - 브랜드그룹 정보
	 * @return
	 * @author eskim
	 * @since 2021. 02. 19
	 */
	public Collection<BrandGroup> getBrandGroupList(BrandGroup brandGroup) {
		return businessDao.getBrandGroupList(brandGroup);
	}

	/**
	 * 브랜드 그룹 등록/수정
	 * @param brandGroup - 브랜드그룹 정보
	 * @author gagamel
	 * @since 2021. 02. 19
	 */
	@Transactional("shopTxnManager")
	public void saveBrandGroup(BrandGroup brandGroup) {

		String brandUploadPath = env.getProperty("upload.default.target.path");
		brandUploadPath = GagaFileUtil.getConcatenationPath(brandUploadPath, "contents", "brand");

		if (brandGroup.getNewSysFileNm1() != null && !"".equals(brandGroup.getNewSysFileNm1())) {
			String brandImgName1 = "BRAND_" + brandGroup.getBrandGroupNo() + "_" + GagaDateUtil.getTodayDateTime() + "." + StringUtils.getFilenameExtension(brandGroup.getNewSysFileNm1());

			//기존이미지 삭제
			try {
				GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(brandUploadPath, brandGroup.getLogoFileNm()));
			} catch (IOException e) {
				//  nothing
				log.info("[saveBanner 기존 이미지 삭제중 error]");
				//e.printStackTrace();
			}

			File uniqueFile = GagaFileUtil.getUniqueFile(new File(GagaFileUtil.getConcatenationPath(brandUploadPath, brandImgName1)));

			File file = new File(GagaFileUtil.getConcatenationPath(brandUploadPath, brandGroup.getNewSysFileNm1()));

			// Rename a file
			file.renameTo(uniqueFile);

			brandImgName1 = "/contents/brand/" + brandImgName1;
			brandGroup.setLogoFileNm(brandImgName1);

		}

		// 흑백이미지
		if (brandGroup.getNewSysFileNm2() != null && !"".equals(brandGroup.getNewSysFileNm2())) {
			String brandImgName2 = "BRAND_" + brandGroup.getBrandGroupNo() + "_" + GagaDateUtil.getTodayDateTime() + "_1." + StringUtils.getFilenameExtension(brandGroup.getNewSysFileNm2());

			//기존이미지 삭제
			try {
				GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(brandUploadPath, brandGroup.getBwLogoFileNm()));
			} catch (IOException e) {
				//  nothing
				log.info("[saveBanner 기존 이미지 삭제중 error]");
				//e.printStackTrace();
			}

			File uniqueFile2 = GagaFileUtil.getUniqueFile(new File(GagaFileUtil.getConcatenationPath(brandUploadPath, brandImgName2)));

			File file2 = new File(GagaFileUtil.getConcatenationPath(brandUploadPath, brandGroup.getNewSysFileNm2()));

			// Rename a file
			file2.renameTo(uniqueFile2);

			brandImgName2 = "/contents/brand/" + brandImgName2;
			brandGroup.setBwLogoFileNm(brandImgName2);

		}

		// 별도 카테고리 선택시 카테고리 생성
		if ("N".equals(brandGroup.getDefaultCateYn()) && brandGroup.getBrandCateNo() <= 0) {

			Category category = new Category();

			category.setSiteCd(TscConstants.Site.STYLE24.value());
			category.setCateGb("G032_102");  //by brand
			category.setCate1No(commonService.getNextSequence("SEQ_CATE"));
			category.setCate1Nm(brandGroup.getBrandGroupKnm());
			category.setCateType("G031_10");  // 상품분류카테고리
			category.setLeafYn("Y");
			category.setDispOrd(1);
			category.setFormalGb("G009_10");	// 정상
			category.setDispYn("Y");
			category.setUseYn("Y");
			displayService.saveCategory1(category);

			brandGroup.setBrandCateNo(category.getCate1No());
		}

		if (brandGroup.getMode().equals("N")) { // 신규
			businessDao.createBrandGroup(brandGroup);
		} else { // 수정
			businessDao.updateBrandGroup(brandGroup);
		}

	}

	/**
	 * 휴무일 목록
	 * @param bizday - 영업일 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 16
	 */
	public Collection<Bizday> getHolidayList(Bizday bizday) {
		return businessDao.getHolidayList(bizday);
	}

	/**
	 * 영업일 저장 처리
	 * @param
	 * @return
	 * @author jaewonHo
	 * @since 2019. 12. 13
	 */
	@Transactional("shopTxnManager")
	public void saveBizday(Bizday bizday) {
		bizday.setRegNo(TsaSession.getInfo().getUserNo());
		bizday.setUpdNo(TsaSession.getInfo().getUserNo());

		String bizdayYn = businessDao.getBizdayYn(bizday.getBizday());

		if (StringUtils.isEmpty(bizdayYn)) {
			// 영업일여부 값이 없으면 신규로 등록
			businessDao.createBizday(bizday);
		} else {
			bizday.setBizdayYn(bizdayYn);
			businessDao.updateBizday(bizday);
		}
	}

}
