package com.style24.admin.biz.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.style24.admin.biz.dao.TsaMorebetterDao;

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

/**
 *마케팅>다다익선 Service
 *
 * @author bin2107
 * @since 2021. 1. 12
 */
@Service
@Slf4j
public class TsaMorebetterService {
    @Autowired
    private TscMessageByLocale message;

    @Autowired
    private Environment env;

    @Autowired
    private TsaMorebetterDao morebetterDao;

    @Autowired
    private TsaCommonService commonService;

    /* CSB 진행 */
    /**
     * 다다익선 리스트 건수
     * @param moreBetter
     * @return
     * @author bin2107
     * @since 2021. 1. 26
     */
    public int getMorebetterListCount(MoreBetter moreBetter) {
        return morebetterDao.getMorebetterListCount(moreBetter);
    }

    /**
     * 다다익선 리스트
     * @param param
     * @return
     * @author bin2107
     * @since 2020. 12. 28
     */
    public Collection<MoreBetter> getMorebetterList(MoreBetter param) {
        return morebetterDao.getMorebetterList(param);
    }

    /**
     * 다다익선 마스터 조회
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 8
     */
    public MoreBetter getMorebetterMstInfo(Integer tmtbSq){
        return morebetterDao.getMorebetterMstInfo(tmtbSq);
    }

    /**
     * 다다익선 구간 조회
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 8
     */
    public Collection<MoreBetterSection> getMorebetterSectionValList(Integer tmtbSq) {
        return morebetterDao.getMorebetterSectionValList(tmtbSq);
    }

    /**
     * 다다익선 구간 조회
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 8
     */
    public Collection<MoreBetterGoods> getMorebetterSupplyCompList(Integer tmtbSq, String targetGb) {
        MoreBetterGoods merebetterGoods = new MoreBetterGoods();
        merebetterGoods.setTmtbSq(tmtbSq);
        merebetterGoods.setTargetGb(targetGb);
        return morebetterDao.getMorebetterSupplyCompList(merebetterGoods);
    }

    public Collection<MoreBetterGoods> getMorebetterBrandList(Integer tmtbSq, String targetGb) {
        MoreBetterGoods merebetterGoods = new MoreBetterGoods();
        merebetterGoods.setTmtbSq(tmtbSq);
        merebetterGoods.setTargetGb(targetGb);
        return morebetterDao.getMorebetterBrandList(merebetterGoods);
    }

    public Collection<MoreBetterGoods> getMorebetterApplyGoodsList(Integer tmtbSq, String targetGb) {
        MoreBetterGoods merebetterGoods = new MoreBetterGoods();
        merebetterGoods.setTmtbSq(tmtbSq);
        merebetterGoods.setTargetGb(targetGb);
        return morebetterDao.getMorebetterApplyGoodsList(merebetterGoods);
    }

    public Collection<MoreBetterGoods> getMorebetterExceptGoodsList(Integer tmtbSq, String targetGb) {
        MoreBetterGoods merebetterGoods = new MoreBetterGoods();
        merebetterGoods.setTmtbSq(tmtbSq);
        merebetterGoods.setTargetGb(targetGb);
        return morebetterDao.getMorebetterExceptGoodsList(merebetterGoods);
    }

    /**
     * 다다익선 구간 조회
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 8
     */
    public Collection<MoreBetterBurden> getMorebetterBurdenList(Integer tmtbSq) {
        return morebetterDao.getMorebetterBurdenList(tmtbSq);
    }

    /**
     * 다다익선 저장
     * @param moreBetter
     * @return
     * @author bin2107
     * @since 2021. 1. 5
     */
    @Transactional("shopTxnManager")
    public void saveMoreBetterDetail(MoreBetter moreBetter) {
        // <,> replace 처리
        moreBetter.setRegNo(TsaSession.getInfo().getUserNo());
        moreBetter.setUpdNo(TsaSession.getInfo().getUserNo());
        Gson gson = new Gson();
        String jsonData = gson.toJson(moreBetter);

        if("U".equals(moreBetter.getMode())){
            morebetterDao.deleteTmtbGoods(moreBetter);      // TB_TMTB_GOODS DEL_YN 'Y' UPDATE
            morebetterDao.deleteTmtbBurden(moreBetter);     // TB_TMTB_BURDEN DEL_YN 'Y' UPDATE
            morebetterDao.deleteTmtbSection(moreBetter);    // TB_TMTB_SECTION DEL_YN 'Y' UPDATE
            morebetterDao.deleteTmtbVal(moreBetter);        // TB_TMTB_VAL DEL_YN 'Y' UPDATE
            morebetterDao.deleteTmtbApplyGoods(moreBetter); // TB_TMTB_APPLY_GOODS DELETE
        }

        // TMTB 마스터(TB_TMTB) 저장
        morebetterDao.saveMorebetterMst(moreBetter);

        // 공급업체
        for(MoreBetterGoods regSupplyComp : moreBetter.getSupplyCompList()){
            regSupplyComp.setTmtbSq(moreBetter.getTmtbSq());
            regSupplyComp.setGoodsGb("G800_20");
            regSupplyComp.setTargetVal(regSupplyComp.getSupplyCompCd());
            regSupplyComp.setRegNo(moreBetter.getRegNo());
            regSupplyComp.setUpdNo(moreBetter.getUpdNo());
            morebetterDao.saveMorebetterGoods(regSupplyComp);
        }

        // 브랜드
        for(MoreBetterGoods regBrand : moreBetter.getBrandList()){
            // 다다익선 적용대상 설정(TB_TMTB_GOODS) 저장
            regBrand.setTmtbSq(moreBetter.getTmtbSq());
            regBrand.setGoodsGb("G800_20");
            regBrand.setTargetVal(regBrand.getBrandCd());
            regBrand.setRegNo(moreBetter.getRegNo());
            regBrand.setUpdNo(moreBetter.getUpdNo());
            morebetterDao.saveMorebetterGoods(regBrand);
        }

        // 적용상품
        for(MoreBetterGoods regApplyGoods : moreBetter.getGridApplyGoodsList()){
            // 다다익선 적용대상 설정(TB_TMTB_GOODS) 저장
            regApplyGoods.setTmtbSq(moreBetter.getTmtbSq());
            regApplyGoods.setTargetVal(regApplyGoods.getGoodsCd());
            regApplyGoods.setRegNo(moreBetter.getRegNo());
            regApplyGoods.setUpdNo(moreBetter.getUpdNo());
            regApplyGoods.setMultiDuplicateGoods(moreBetter.getMultiDuplicateGoods());
            morebetterDao.saveMorebetterGoods(regApplyGoods);
        }

        // 제외상품
        for(MoreBetterGoods regExceptGoods : moreBetter.getExceptGoodsList()){
            // 다다익선 적용대상 설정(TB_TMTB_GOODS) 저장
            log.info("exception::{}",moreBetter.getExceptGoodsList());
            regExceptGoods.setTmtbSq(moreBetter.getTmtbSq());
            regExceptGoods.setTargetVal(regExceptGoods.getGoodsCd());
            regExceptGoods.setRegNo(moreBetter.getRegNo());
            regExceptGoods.setUpdNo(moreBetter.getUpdNo());

            morebetterDao.saveMorebetterGoods(regExceptGoods);
            morebetterDao.saveMorebetterApplyGoods(regExceptGoods);
        }

        // 다다익선 할인구간 저장
        for(MoreBetterSection regSection : moreBetter.getSectionGbList()){
            // 다다익선 할인구간설정 2차조건(TB_TMTB_SECTION) 저장
            regSection.setTmtbSq(moreBetter.getTmtbSq());
            regSection.setRegNo(moreBetter.getRegNo());
            regSection.setUpdNo(moreBetter.getUpdNo());

            morebetterDao.saveMorebetterSection(regSection);
            morebetterDao.saveMorebetterVal(regSection);
        }

        // 다다익선 업체분담율(TB_TMTB_BURDEN) 저장
        for (MoreBetterBurden regBurden : moreBetter.getBurdenList()) {
            regBurden.setTmtbSq(moreBetter.getTmtbSq());
            regBurden.setRegNo(moreBetter.getRegNo());
            regBurden.setUpdNo(moreBetter.getUpdNo());

            morebetterDao.saveMorebetterBurden(regBurden);
        }

        // 업체&브랜드 상품
        MoreBetterGoods moreBetterGoods = new MoreBetterGoods();
        StringBuilder sb = new StringBuilder();
        StringBuilder sb3 = new StringBuilder();
        //int i = 1;

        if(moreBetter.getGridApplyGoodsList().size()>0){    //getApplyGoodsList
            for(int i=0; i<moreBetter.getGridApplyGoodsList().size(); i++){
                sb.append("SELECT   '").append(moreBetter.getGridApplyGoodsList().get(i).getGoodsCd()).append("' AS GOODS_CD ");
                if(i<moreBetter.getGridApplyGoodsList().size()-1){
                    sb.append("\n UNION ALL \n");
                }

                sb3.append("SELECT   '").append(moreBetter.getGridApplyGoodsList().get(i).getGoodsCd()).append("' AS GOODS_CD ").append(" , '").append(moreBetter.getGridApplyGoodsList().get(i).getGoodsGb()).append("' AS GOODS_GB ");
                if(i<moreBetter.getGridApplyGoodsList().size()-1){
                    sb3.append("\n UNION ALL \n");
                }
            }
        }
        moreBetterGoods.setApplySql(sb.toString());
        moreBetterGoods.setApplyGbSql(sb3.toString());

        StringBuilder sb2 = new StringBuilder();
        if(moreBetter.getExceptGoodsList().size()>0){
            for(int i=0; i<moreBetter.getExceptGoodsList().size(); i++){
                sb2.append("SELECT   '").append(moreBetter.getExceptGoodsList().get(i).getGoodsCd()).append("' AS GOODS_CD ");
                if(i<moreBetter.getExceptGoodsList().size()-1){
                    sb2.append("\n UNION ALL \n");
                }
            }
        }
        moreBetterGoods.setExceptSql(sb2.toString());
        moreBetterGoods.setTmtbSq(moreBetter.getTmtbSq());
        moreBetterGoods.setRegNo(TsaSession.getInfo().getUserNo());
        moreBetterGoods.setUpdNo(TsaSession.getInfo().getUserNo());
        moreBetterGoods.setMultiSupplyCompCd(moreBetter.getMultiSupplyCompCd());
        moreBetterGoods.setMultiBrand(moreBetter.getMultiBrand());
        moreBetterGoods.setMultiApplyGoods(moreBetter.getMultiApplyGoods());
        moreBetterGoods.setMultiExceptGoods(moreBetter.getMultiExceptGoods());
        moreBetterGoods.setSectionGb(moreBetter.getSectionGb());
        morebetterDao.insertMorebetterApplyGoods(moreBetterGoods);

        log.info("newBurdenSq = {}, newTmtbSq = {}, newSupplyCd = {}, newBurdenRate = {} , newUseYn = {}");
    }

    /**
     * 다다익선 공급업체 삭제
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 5
     */
    @Transactional("shopTxnManager")
    public void deleteTmtbSupplyCompanyList(MoreBetterGoods moreBetterGoods) {
        if (moreBetterGoods == null || (moreBetterGoods.getArrCompanySq() == null && moreBetterGoods.getArrCompanySq().length <= 0)) {
            throw new IllegalStateException(message.getMessage("FAIL_1001"));
        }

        if (moreBetterGoods.getArrCompanySq().length > 0) {
            morebetterDao.deleteTmtbSupplyCompanyList(moreBetterGoods);
        }
    }

    /**
     * 다다익선 브랜드 삭제
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 16
     */
    @Transactional("shopTxnManager")
    public void deleteTmtbBrandList(MoreBetterGoods moreBetterGoods) {
        if (moreBetterGoods == null || (moreBetterGoods.getArrBrandSq() == null && moreBetterGoods.getArrBrandSq().length <= 0)) {
            throw new IllegalStateException(message.getMessage("FAIL_1001"));
        }

        if (moreBetterGoods.getArrBrandSq().length > 0) {
            morebetterDao.deleteTmtbBrandList(moreBetterGoods);
        }
    }

    /**
     * 다다익선 적용상품 삭제
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 16
     */
    @Transactional("shopTxnManager")
    public void deleteTmtbApplyGoodsList(MoreBetterGoods moreBetterGoods) {
        if (moreBetterGoods == null || (moreBetterGoods.getArrApplyGoodsSq() == null && moreBetterGoods.getArrApplyGoodsSq().length <= 0)) {
            throw new IllegalStateException(message.getMessage("FAIL_1001"));
        }

        if (moreBetterGoods.getArrApplyGoodsSq().length > 0) {
            morebetterDao.deleteTmtbApplyGoodsList(moreBetterGoods);
        }
    }

    /**
     * 다다익선 제외상품 삭제
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 16
     */
    @Transactional("shopTxnManager")
    public void deleteTmtbExceptGoodsList(MoreBetterGoods moreBetterGoods) {
        if (moreBetterGoods == null || (moreBetterGoods.getArrExceptGoodsSq() == null && moreBetterGoods.getArrExceptGoodsSq().length <= 0)) {
            throw new IllegalStateException(message.getMessage("FAIL_1001"));
        }

        if (moreBetterGoods.getArrExceptGoodsSq().length > 0) {
            morebetterDao.deleteTmtbExceptGoodsList(moreBetterGoods);
        }
    }

    /**
     * 다다익선 다다익선 할인구간 삭제
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 5
     */
    @Transactional("shopTxnManager")
    public void deleteTmtbSectionValList(MoreBetterSection moreBetterSection) {
        if (moreBetterSection == null || (moreBetterSection.getArrSectionSq() == null && moreBetterSection.getArrSectionSq().length <= 0)) {
            throw new IllegalStateException(message.getMessage("FAIL_1001"));
        }

        if (moreBetterSection.getArrSectionSq().length > 0) {
            morebetterDao.deleteTmtbSectionList(moreBetterSection);
            morebetterDao.deleteTmtbValList(moreBetterSection);
        }
    }

    /**
     * 다다익선 제외상품 삭제
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 16
     */
    @Transactional("shopTxnManager")
    public void deleteTmtbBurdenList(MoreBetterBurden moreBetterBurden) {
        if (moreBetterBurden == null || (moreBetterBurden.getArrBurdenSq() == null && moreBetterBurden.getArrBurdenSq().length <= 0)) {
            throw new IllegalStateException(message.getMessage("FAIL_1001"));
        }

        if (moreBetterBurden.getArrBurdenSq().length > 0) {
            morebetterDao.deleteTmtbBurdenList(moreBetterBurden);
        }
    }

    /**
     * 다다익선 - 진행중인 다다익선 상품 조회
     * @param moreBetterGoods
     * @return
     * @author bin2107
     * @since 2021. 1. 22
     */
    public Collection<MoreBetterGoods> getMorebetterDuplicateList(MoreBetterGoods moreBetterGoods) {
        return morebetterDao.getMorebetterDuplicateList(moreBetterGoods);
    }

    /**
     * 다다익선 진행 상태 변경
     * @param
     * @return
     * @author bin2107
     * @since 2021. 1. 26
     */
    @Transactional("shopTxnManager")
    public void updateMorebetterStat(MoreBetter moreBetter) {
        moreBetter.setUpdNo(TsaSession.getInfo().getUserNo());
        morebetterDao.updateMorebetterStat(moreBetter);
    }

    /**
     * 다다익선 적용상품 temp
     * @param
     * @return
     * @author bin2107
     * @since 2021. 3. 23
     */
    @Transactional("shopTxnManager")
    public void insertMorebetterApplyGoodsTemp(MoreBetter moreBetter) {
        moreBetter.setRegNo(TsaSession.getInfo().getUserNo());
        moreBetter.setUpdNo(TsaSession.getInfo().getUserNo());
        if(moreBetter.getMultiApplyGoods().length > 0){
            morebetterDao.deleteMorebetterApplyGoodsTemp(moreBetter);
            morebetterDao.insertMorebetterApplyGoodsTemp(moreBetter);
        }
    }

    /* // CSB 진행 */
}
