package com.oqpo.api.service.stinfo;



import com.oqpo.api.entity.ActionEntity;
import com.oqpo.api.entity.CodeEntity;
import com.oqpo.api.entity.oper.*;
import com.oqpo.api.entity.settmng.PgKiccBaseInfoEntity;
import com.oqpo.api.entity.stinfo.BrandEntity;
import com.oqpo.api.entity.stinfo.ItemClassMngEntity;
import com.oqpo.api.entity.stinfo.PgKisBaseInfoEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.FileMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.mapper.stinfo.BrandMapper;
import com.oqpo.api.mapper.stinfo.ItemMapper;
import com.oqpo.api.mapper.stinfo.StoreBaseInfoMapper;
import com.oqpo.api.mapper.stinfo.SupplyMapper;
import com.oqpo.api.mapper.stockmng.WhsMngMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.util.StringUtil;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.oper.salemgr.SaveSaleMgrMgnlRequest;
import com.oqpo.api.web.dto.request.stinfo.brand.SaveBrandInfolRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.code.CodeSearchListResponse;
import com.oqpo.api.web.dto.response.oper.affl.AfflShopInfoResponse;
import com.oqpo.api.web.dto.response.oper.salemgr.SaleMgrMgnInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BrandService extends CommonService {
    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private WhsMngMapper whsMngMapper;

    @Autowired
    private SupplyMapper supplyMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private ItemMapper itemMapper;


    /*
      session 브랜드 리스트 조회
     */
    public List<BrandEntity> selectTargetBrandGridList(String userId, String authTpCd) throws Exception {
        return brandMapper.selectTargetBrandGridList(userId, authTpCd);
    }

    /*
      팝업 브랜드 리스트 조회
     */
    public GridResponse selectPopBrandGridList(String userId, String authTpCd,String afflShopId, String brandNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = brandMapper.selectPopBrandGridCnt( userId, authTpCd, afflShopId, brandNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<BrandEntity> entities = brandMapper.selectPopBrandGridList(userId, authTpCd, afflShopId,  brandNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> BrandSearchResponse.builder()
                        .viewCd("R")
                        .afflShopId(m.getAfflShopId())
                        .afflShopNm(m.getAfflShopNm())
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .oqBrandId(m.getOqBrandId() == null ? "" : m.getOqBrandId())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      브랜드그룹 브랜드 리스트 조회
     */
    public AfflBrandSearchResponse selectAfflBrandList(String afflShopId) throws Exception {
        List<BrandEntity> entities = brandMapper.selectAfflBrandList(afflShopId);
        return AfflBrandSearchResponse.toDTO(entities);
    }

    /*
      브랜드 그리드 리스트 조회
     */
    public GridResponse selectBrandGridList( String sAfflShopId, String sBrandId, String sBrandNm, String sBrandType, String sStCd, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

       // fromDt = fromDt == null ? null : fromDt.replace(".", "");
       // toDt = toDt == null ? null : toDt.replace(".", "");

        int gridRecords = brandMapper.selectBrandGridCnt( sAfflShopId,sBrandId,  sBrandNm, sBrandType, sStCd);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<BrandEntity> entities = brandMapper.selectBrandGridList( sAfflShopId, sBrandId, sBrandNm, sBrandType, sStCd, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> BrandSearchListResponse.builder()
                        .viewCd("R")
                        .afflShopId(m.getAfflShopId())
                        .afflShopNm(m.getAfflShopNm())
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .stNm(m.getStNm())
                        .brandTypeNm(m.getBrandTypeNm())
                        .regDt(m.getRegDt())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 브랜드 정보 */
    public BrandInfoResponse selectSaleMgrMgn(String brandId) throws Exception {

        BrandEntity entity = brandMapper.selectBrandInfo(brandId);
        List<FileEntity> logFileList = null;

        if (!StringUtil.isEmpty(entity.getBrandLogoFileNo())) {
            logFileList = fileMapper.selectFileList(entity.getBrandLogoFileNo()) ;
        } else {
            logFileList = new ArrayList<FileEntity>();
        }

        return BrandInfoResponse.toDTO(entity,logFileList );

    }

    /* 브랜드 저장 */
    @Transactional
    public void saveBrandInfo(String userId, SaveBrandInfolRequest saveBrandInfolRequest) throws Exception {
        try {

            BrandEntity entity = new BrandEntity();
            entity.setBrandId(saveBrandInfolRequest.getBrandId());
            entity.setBrandNm(saveBrandInfolRequest.getBrandNm());
            entity.setStCd(saveBrandInfolRequest.getStCd());
            entity.setBrandType(saveBrandInfolRequest.getBrandType());
            entity.setZipNo(saveBrandInfolRequest.getZipNo());
            entity.setAddr1(saveBrandInfolRequest.getAddr1());
            entity.setAddr2(saveBrandInfolRequest.getAddr2());
            entity.setLatX(saveBrandInfolRequest.getLatX());
            entity.setLongY(saveBrandInfolRequest.getLongY());
            entity.setTelNo(saveBrandInfolRequest.getTelNo().replaceAll("-",""));
            entity.setFaxNo(saveBrandInfolRequest.getFaxNo().replaceAll("-",""));
            entity.setEmalAddr(saveBrandInfolRequest.getEmalAddr());
            entity.setBnkCd(saveBrandInfolRequest.getBnkCd());
            entity.setAcctNo(saveBrandInfolRequest.getAcctNo());
            entity.setOwacNm(saveBrandInfolRequest.getOwacNm());
            entity.setOwnerNm(saveBrandInfolRequest.getOwnerNm());
            entity.setAfflShopId(saveBrandInfolRequest.getAfflShopId());
            entity.setBrandLogoFileNo(saveBrandInfolRequest.getBrandLogoFileNo());
            entity.setBsnsRegNo(saveBrandInfolRequest.getBsnsRegNo().replaceAll("-",""));
            entity.setCorpRegNo(saveBrandInfolRequest.getCorpRegNo().replaceAll("-",""));
            entity.setPgId(saveBrandInfolRequest.getPgId());
            entity.setOqBrandId(saveBrandInfolRequest.getOqBrandId());
            entity.setShmtColProcType(saveBrandInfolRequest.getShmtColProcType());
            entity.setWishListUseYn(saveBrandInfolRequest.getWishListUseYn() == null ? "N" : saveBrandInfolRequest.getWishListUseYn());
            //entity.setPgKey(saveBrandInfolRequest.getPgKey());
            //entity.setPgAfflId(saveBrandInfolRequest.getPgAfflId());


            /* ==>dwkim 추후 PG사 관련 테이블 변경시 작업 진행 ==> setPgKey, setPgAfflId*/


            if ("C".equals(saveBrandInfolRequest.getViewCd())) {

                // 브랜드 아이디 부여  22  entity.setContentsNo(fnGetKeyNo(17));
                //String brandId = fnGetKeyNo(23);
                entity.setBrandId(saveBrandInfolRequest.getBrandId());  // 브랜드아이디 생성
                brandMapper.insertBrandInfo(userId, entity);

                // PG정보 등록
                if (!StringUtil.isEmpty(saveBrandInfolRequest.getPgId())) {
                    PgKiccBaseInfoEntity pgInfoEntity = new PgKiccBaseInfoEntity();
                    pgInfoEntity.setBrandId(saveBrandInfolRequest.getBrandId());
                    pgInfoEntity.setMallId(saveBrandInfolRequest.getPgAfflId());
                    pgInfoEntity.setUseYn("Y");
                    brandMapper.insertPgKiccBaseInfo(userId, pgInfoEntity);
                }

                //사용자 계정 정보 생성 및 권한생성
                UserMngEntity userEntity = new UserMngEntity();
                userEntity.setUserId(entity.getBrandId());
                userEntity.setUserNm(entity.getOwnerNm());
                userEntity.setTelNo(entity.getTelNo());
                userEntity.setEmail(entity.getEmalAddr());
                userEntity.setAfflShopId(entity.getAfflShopId());
                userEntity.setBrandId(entity.getBrandId());

                if ("S000".equals(entity.getStCd())) {
                    userEntity.setUserStatCd("10");
                } else if ("S001".equals(entity.getStCd())) {
                    userEntity.setUserStatCd("90");
                } else {   //S002
                    userEntity.setUserStatCd("30");
                }

                userEntity.setAuthTpCd("40");
                //패스워드 암호화
                String password = passwordEncoder.encode(entity.getBsnsRegNo().replace("-",""));
                userEntity.setUserPw(password);
                userMngMapper.insertUserInfo(userId, userEntity);

                // 사용자 권한 등록
                userMngMapper.insertBrandUserTypeAuth(entity.getBrandId(), userId, "40", entity.getShmtColProcType());

                // 브랜드 카테고이 상위 정보 저장
                /*
                ItemClassMngEntity icmEntity = new ItemClassMngEntity();
                icmEntity.setBrandId(entity.getBrandId());
                icmEntity.setItemClassMgntNo(fnGetKeyNo(31)); //품목분류번호 생성
                icmEntity.setDelYn("N");
                icmEntity.setItemClassNm(entity.getBrandNm());
                icmEntity.setPrnSeq(1);
                itemMapper.insertItemClassMngInfo(userId, icmEntity);
                */
            } else if ("U".equals(saveBrandInfolRequest.getViewCd())) {
                brandMapper.updateBrandInfo(userId, entity);
                //브랜드에 사용중인 pg정보 가져오기
                List<BrandEntity> usePgList = brandMapper.selectPgMallIdList(saveBrandInfolRequest.getBrandId());

                int extPgMallCnt = 0 ;
                int chgMallCnt = 0 ;
                String preUseMallId = "";

                if (usePgList.size() > 0 ) {
                    for (int i = 0 ; i < usePgList.size() ; i++) {
                        BrandEntity tmpPg = usePgList.get(i);
                        if ("Y".toString().equals(tmpPg.getUseYn())) {
                            preUseMallId = tmpPg.getMallId();
                        }

                        //동일한 pg존재 여부 확인
                        if (saveBrandInfolRequest.getPgAfflId().equals(tmpPg.getMallId())) {
                            extPgMallCnt = 1;
                            if ("N".toString().equals(tmpPg.getUseYn())) {
                                chgMallCnt = 1;
                            }
                        }
                    }

                    if (extPgMallCnt == 0 ) {
                        // 기존거는 삭제 하고 신규로 등록
                        //기존거 삭제
                        brandMapper.updatePgKiccBaseInfo(userId, saveBrandInfolRequest.getBrandId(), preUseMallId, "N") ;
                        //신규등록
                        PgKiccBaseInfoEntity pgInfoEntity = new PgKiccBaseInfoEntity();
                        pgInfoEntity.setBrandId(saveBrandInfolRequest.getBrandId());
                        pgInfoEntity.setMallId(saveBrandInfolRequest.getPgAfflId());
                        pgInfoEntity.setUseYn("Y");
                        brandMapper.insertPgKiccBaseInfo(userId, pgInfoEntity);
                    } else {
                        if (chgMallCnt > 0 ) {
                            // 기존 사용건은 N으로 하고 N인것을 Y로 변경한다.
                            brandMapper.updatePgKiccBaseInfo(userId, saveBrandInfolRequest.getBrandId(), preUseMallId, "N") ;
                            brandMapper.updatePgKiccBaseInfo(userId, saveBrandInfolRequest.getBrandId(), saveBrandInfolRequest.getPgAfflId(), "Y") ;
                        }
                    }

                } else {
                    PgKiccBaseInfoEntity pgInfoEntity = new PgKiccBaseInfoEntity();
                    pgInfoEntity.setBrandId(saveBrandInfolRequest.getBrandId());
                    pgInfoEntity.setMallId(saveBrandInfolRequest.getPgAfflId());
                    pgInfoEntity.setUseYn("Y");
                    brandMapper.insertPgKiccBaseInfo(userId, pgInfoEntity);
                }

/*
                String mallId = brandMapper.selectPgMallId(saveBrandInfolRequest.getBrandId());

                if (mallId == null || "".equals(mallId)) {
                    // PG정보 등록
                    if (!"".equals(saveBrandInfolRequest.getPgAfflId())) {
                        PgKiccBaseInfoEntity pgInfoEntity = new PgKiccBaseInfoEntity();
                        pgInfoEntity.setBrandId(saveBrandInfolRequest.getBrandId());
                        pgInfoEntity.setMallId(saveBrandInfolRequest.getPgAfflId());
                        pgInfoEntity.setUseYn("Y");
                        brandMapper.insertPgKiccBaseInfo(userId, pgInfoEntity);
                    }
                } else {
                    if (!mallId.equals(saveBrandInfolRequest.getPgAfflId())) {
                        //기존거 삭제
                        brandMapper.updatePgKiccBaseInfo(userId, saveBrandInfolRequest.getBrandId(), mallId) ;
                        //신규등록
                        PgKiccBaseInfoEntity pgInfoEntity = new PgKiccBaseInfoEntity();
                        pgInfoEntity.setBrandId(saveBrandInfolRequest.getBrandId());
                        pgInfoEntity.setMallId(saveBrandInfolRequest.getPgAfflId());
                        pgInfoEntity.setUseYn("Y");
                        brandMapper.insertPgKiccBaseInfo(userId, pgInfoEntity);
                    }
                }

*/
                UserMngEntity userUEntity = new UserMngEntity();
                userUEntity.setUserId(entity.getBrandId());
                userUEntity.setTelNo(entity.getTelNo());
                userUEntity.setEmail(entity.getEmalAddr());
                userUEntity.setUserNm(entity.getOwnerNm());

                if ("S000".equals(entity.getStCd())) {
                    userUEntity.setUserStatCd("10");
                } else if ("S001".equals(entity.getStCd())) {
                    userUEntity.setUserStatCd("90");
                } else {   //S002
                    userUEntity.setUserStatCd("30");
                }
                userMngMapper.updateUserInfo(userId, userUEntity);

                // 위시리스트 사용여부에 따라 매장의 위시리스트 메뉴 등록 또는 삭제 처리 필요
                if ("Y".toString().equals(entity.getWishListUseYn())) {
                    int cnt = userMngMapper.selectWishListCnt(entity.getBrandId());
                    if (cnt == 0 ) {
                        userMngMapper.insertUserAuthWishList(userId, entity.getBrandId());
                    }

                } else {
                    userMngMapper.deleteUserAuthWishList(entity.getBrandId());
                }

                // 브랜드 종료 면 매장,창고, 공급사 상태 종료 처리함
                /*
                  1. 매장 전체 종료 처리 및 매장을 통한 창고 종료
                  2. 공급사 전체 종료..-- 사용자 계정도함
                 */
                if ("S001".equals(entity.getStCd())) {
                    // 창고 종료
                    whsMngMapper.updateCloseWhs(userId, entity.getBrandId(), "");
                    // 창고 로케이션 종료
                    whsMngMapper.updateCloseWhsLoc(userId, entity.getBrandId(), "");
                    // 매장 종료
                    storeBaseInfoMapper.updateCloseStore(userId, entity.getBrandId(), "");
                    // 공급사 종료
                    supplyMapper.updateCloseSpply(userId, entity.getBrandId(), "");

                    // 사용자 종료
                    userMngMapper.updateCloseUser(userId, entity.getBrandId(), "");
                }

            }

        } catch (GlobalException e) {
            e.printStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /*
  브랜드 로그인 pw 초기화
   */
    @Transactional
    public String updateInitUserPw(String brandId) throws Exception {
        // 사용자 정보를 가져옴
        try {
            String initPw  = brandMapper.selectBrandInitPw(brandId);
            String password = passwordEncoder.encode(initPw);
            userMngMapper.updateInitUserPw(brandId, password);
            return password;
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    /*
        사업자번호 브랜드 리스트
     */
    public List<BrandEntity> selectBsnsBrandList(String bsnsRegNo) throws Exception {

        List<BrandEntity> entities = brandMapper.selectBsnsBrandList(bsnsRegNo);

        return entities;
    }

    /*
    public BsnsBrandListResponse selectBsnsBrandList(String bsnsRegNo) throws Exception {
        List<BrandEntity> entities = brandMapper.selectBsnsBrandList(bsnsRegNo);
        return BsnsBrandListResponse.toDTO(entities);
    }
    */
}
