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.stinfo.BrandEntity;
import com.oqpo.api.entity.stinfo.ItemClassMngEntity;
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.service.CommonService;
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 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 brandNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = brandMapper.selectPopBrandGridCnt( userId, authTpCd,  brandNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<BrandEntity> entities = brandMapper.selectPopBrandGridList(userId, authTpCd,  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())
                        .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 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( sBrandNm, sBrandType, sStCd);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<BrandEntity> entities = brandMapper.selectBrandGridList( 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 (!"".equals(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.setAfflShopId(saveBrandInfolRequest.getAfflShopId());
            entity.setBrandLogoFileNo(saveBrandInfolRequest.getBrandLogoFileNo());
            entity.setBsnsRegNo(saveBrandInfolRequest.getBsnsRegNo().replaceAll("-",""));
            entity.setCorpRegNo(saveBrandInfolRequest.getCorpRegNo().replaceAll("-",""));

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

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

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

                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.insertUserTypeAuth(entity.getBrandId(), userId, "40");

                // 브랜드 카테고이 상위 정보 저장
                /*
                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);

                UserMngEntity userUEntity = new UserMngEntity();
                userUEntity.setUserId(entity.getBrandId());
                userUEntity.setTelNo(entity.getTelNo());
                userUEntity.setEmail(entity.getEmalAddr());

                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);
            }

        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            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);
    }
    */
}
