package com.style24.admin.biz.web;

import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.biz.service.TsaSettleService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.AflinkFee;
import com.style24.persistence.domain.DelvFeeSettle;
import com.style24.persistence.domain.GiftcardSettle;
import com.style24.persistence.domain.GoodsSettle;
import com.style24.persistence.domain.SettleConfirm;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.excel.GagaExcelUtil;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.rest.server.GagaResponse;
import com.gagaframework.web.util.GagaFileUtil;
import com.gagaframework.web.util.GagaStringUtil;

/**
 * 정산 Controller
 *
 * @author jaewonHo
 * @since 2020. 10. 22
 */
@Controller
@RequestMapping("/settle")
@Slf4j
public class TsaSettleController extends TsaBaseController {

	@Autowired
	private TsaSettleService settleService;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private ObjectMapper mapper;

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	/**
	 * 상품정산 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 22
	 */
	@GetMapping("/goods/form")
	public ModelAndView goodsSettleForm() {
		ModelAndView mav = new ModelAndView();

		// 몰구분
		mav.addObject("mallGbList", rendererService.getCommonCodeList("G011"));

		// 외부몰벤더 콤보박스 목록
		mav.addObject("vendorList", rendererService.getCommonCodeList("G003"));

		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));

		// 유통구분
		mav.addObject("distributionGbList", rendererService.getCommonCodeList("G065"));

		mav.setViewName("settle/GoodsSettleForm");

		return mav;
	}

	/**
	 * 상품정산 목록
	 * @param goodsSettle - 상품정산 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 7. 5
	 */
	@PostMapping("/goods/list")
	@ResponseBody
	public Collection<GoodsSettle> getGoodsSettleList(@RequestBody GoodsSettle goodsSettle) {
		if (!StringUtils.isBlank(goodsSettle.getSupplyCompList())) {
			try {
				String[] arrSupplyComp = mapper.readValue(goodsSettle.getSupplyCompList(), String[].class);
				goodsSettle.setMultiSupplyComp(arrSupplyComp);
			} catch (Exception e) {
				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		if (!StringUtils.isBlank(goodsSettle.getBrandList())) {
			try {
				String[] arrBrandCd = mapper.readValue(goodsSettle.getBrandList(), String[].class);
				goodsSettle.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				throw new IllegalStateException("브랜드코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		return settleService.getGoodsSettleList(goodsSettle);
	}

	/**
	 * 정산확정 처리 - 업체별정산데이터 생성
	 * @param settleYm - 정산기준월
	 * @return
	 * @author gagamel
	 * @since 2021. 7. 30
	 */
	@PostMapping("/confirm/save/{settleYm}")
	@ResponseBody
	public GagaResponse saveSettleConfirm(@PathVariable String settleYm) {
		settleService.saveSettleConfirm(settleYm);
		return super.ok(message.getMessage("SUCC_0004"));
	}

	/**
	 * 배송비정산 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 22
	 **/
	@GetMapping("/delivery/fee/form")
	public ModelAndView deliveryFeeSettleForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));

		// 유통구분
		mav.addObject("distributionGbList", rendererService.getCommonCodeList("G065"));

		mav.setViewName("settle/DeliveryFeeSettleForm");

		return mav;
	}

	/**
	 * 배송비정산 목록
	 * @param delvFeeSettle - 배송비정산 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 7. 6
	 */
	@PostMapping("/delivery/fee/list")
	@ResponseBody
	public Collection<DelvFeeSettle> getDeliveryFeeSettleList(@RequestBody DelvFeeSettle delvFeeSettle) {
		if (!StringUtils.isBlank(delvFeeSettle.getSupplyCompList())) {
			try {
				String[] arrSupplyComp = mapper.readValue(delvFeeSettle.getSupplyCompList(), String[].class);
				delvFeeSettle.setMultiSupplyComp(arrSupplyComp);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		if (!StringUtils.isBlank(delvFeeSettle.getBrandList())) {
			try {
				String[] arrBrandCd = mapper.readValue(delvFeeSettle.getBrandList(), String[].class);
				delvFeeSettle.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("브랜드코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		return settleService.getDeliveryFeeSettleList(delvFeeSettle);
	}

	/**
	 * 정산확정관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 22
	 */
	@GetMapping("/confirm/form")
	public ModelAndView settleConfirmForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));

		// 유통구분
		mav.addObject("distributionGbList", rendererService.getCommonCodeList("G065"));

		// 은행
		mav.addObject("bankList", rendererService.getCommonCodeList("G940"));

		mav.setViewName("settle/SettleConfirmForm");

		return mav;
	}

	/**
	 * 정산확정 목록
	 * @param settleConfirm - 정산확정 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 7. 26
	 */
	@PostMapping("/confirm/list")
	@ResponseBody
	public Collection<SettleConfirm> getSettleConfirmList(@RequestBody SettleConfirm settleConfirm) {
		if (!StringUtils.isBlank(settleConfirm.getSupplyCompList())) {
			try {
				String[] arrSupplyComp = mapper.readValue(settleConfirm.getSupplyCompList(), String[].class);
				settleConfirm.setMultiSupplyComp(arrSupplyComp);
			} catch (Exception e) {
				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		return settleService.getSettleConfirmList(settleConfirm);
	}

	/**
	 * 정산확정 기타차감 엑셀 업로드
	 * @param goodsMass
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2021. 8. 16
	 */
	@PostMapping("/etc/deduct/amt/upload")
	@ResponseBody
	public GagaResponse uploadEtcDeductAmtList(@RequestBody SettleConfirm settleConfirm) throws Exception {
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "excel");

		// DB 처리 시 사용되는 셀명 설정
		String[] cellNames = {"occurYm", "custId", "custNm", "ordNo", "cateNm", "supplyCompCd", "supplyCompNm", "chargeNm", "ordGoods", "currPrice", "rewardAmt", "reason"};

		Collection<GagaMap> ecxelList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, settleConfirm.getExcelFileNm()), 0, cellNames, 0);

		if (ecxelList == null || ecxelList.isEmpty()) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		for (GagaMap dataMap : ecxelList) {
			settleService.saveEtcDeductAmt(dataMap);
		}

		// 파일 삭제
		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, settleConfirm.getExcelFileNm()));

		return super.ok(message.getMessage("SUCC_0007"));
	}

	/**
	 * 정산확정 미수금 목록 저장 처리
	 * @param settleConfirmList - 정산확정 목록
	 * @return
	 * @author gagamel
	 * @since 2021. 8. 16
	 */
	@PostMapping("/receievable/amt/list/save")
	@ResponseBody
	public GagaResponse saveReceivableAmtList(@RequestBody Collection<SettleConfirm> settleConfirmList) {
		if (settleConfirmList == null || settleConfirmList.isEmpty()) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		settleService.saveReceivableAmtList(settleConfirmList);
		return super.ok(message.getMessage("SUCC_0004"));
	}

	/**
	 * 세금계산서용 엑셀다운로드
	 * @param settleConfirm - 정산확정 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 8. 16
	 */
	@GetMapping("/tax/bill/excel/download")
	public ResponseEntity<InputStreamResource> downloadTaxBillSettleExcel(HttpServletRequest request, SettleConfirm settleConfirm) throws Exception {
		String excelFileName = GagaStringUtil.replace(settleConfirm.getSettleYm(), "-", "") + "_세금계산서.xlsx";
		String excelFilenameWithPath = GagaFileUtil.getConcatenationPath(env.getProperty("download.path"), "excel", excelFileName);

		settleService.createTaxBillSettleExcel(settleConfirm, excelFilenameWithPath);

		return GagaFileUtil.writeFile(request, excelFilenameWithPath);
	}

//	/**
//	 * 업체별정산내역 화면
//	 * @return
//	 * @author gagamel
//	 * @since 2020. 10. 22
//	 */
//	@GetMapping("/supply/company/form")
//	public ModelAndView supplyCompanySettleForm() {
//		ModelAndView mav = new ModelAndView();
//
//		// 공급업체
//		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));
//
//		mav.setViewName("settle/SupplyCompanySettleForm");
//
//		return mav;
//	}
//
//	/**
//	 * PG입금정산 화면
//	 * @return
//	 * @author gagamel
//	 * @since 2020. 10. 22
//	 */
//	@GetMapping("/pg/deposit/form")
//	public ModelAndView paygateDepositForm() {
//		ModelAndView mav = new ModelAndView();
//
//		// 공급업체
//		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));
//
//		// PG구분
//		mav.addObject("pgGbList", rendererService.getCommonCodeList("G015"));
//
//		// 결제수단
//		mav.addObject("payMeansList", rendererService.getCommonCodeList("G014"));
//
//		mav.setViewName("settle/PgDepositSettleForm");
//
//		return mav;
//	}

	/**
	 * 상품권정산 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 22
	 */
	@GetMapping("/giftcard/form")
	public ModelAndView giftcardSettleForm() {
		ModelAndView mav = new ModelAndView();

		mav.setViewName("settle/GiftcardSettleForm");

		return mav;
	}

	/**
	 * 상품권정산 목록
	 * @param giftcardSettle - 상품권정산 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 8. 16
	 */
	@PostMapping("/giftcard/list")
	@ResponseBody
	public Collection<GiftcardSettle> getGiftcardSettleList(@RequestBody GiftcardSettle giftcardSettle) {
		Collection<GiftcardSettle> dataList = new ArrayList<GiftcardSettle>();

		if (giftcardSettle.getTermGb().equals("SETTLE_YM")) { // 기간조건이 "정산월"이면
			// 상품권정산 목록
			dataList = settleService.getGiftcardSettleList(giftcardSettle);
		} else {
			// 상품권현황 목록
			dataList = settleService.getGiftcardStatusList(giftcardSettle);
		}

		return dataList;
	}

	/**
	 * 제휴채널정산 화면
	 * @return
	 * @author gagamel
	 * @since 2021. 1. 20
	 */
	@GetMapping("/aflink/fee/form")
	public ModelAndView afLinkFeeForm() {
		ModelAndView mav = new ModelAndView("settle/AfLinkSettleForm");

		// 제휴채널 목록
		mav.addObject("afChannelList", rendererService.getAvailCommonCodeList("G053"));

		return mav;
	}

	/**
	 * 제휴채널정산 목록
	 * @param aflinkFee - 제휴채널수수료 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 1. 20
	 */
	@PostMapping("/aflink/fee/list")
	@ResponseBody
	public Collection<AflinkFee> getAfLinkFeeList(@RequestBody AflinkFee aflinkFee) {
		return settleService.getAfLinkFeeList(aflinkFee);
	}

}
