package com.oqpo.api.service.oper;


import com.oqpo.api.entity.oper.AfflEntity;
import com.oqpo.api.entity.oper.AfflSaleInfoEntity;
import com.oqpo.api.entity.oper.FileEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.FileMapper;
import com.oqpo.api.mapper.oper.AfflMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.oper.affl.SaveAfflRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.oper.affl.AfflSearchResponse;
import com.oqpo.api.web.dto.response.oper.affl.AfflShopInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.affl.AfflShopBaseInfoSearchResponse;
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 AfflService extends CommonService {
    @Autowired
    private AfflMapper afflMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private FileMapper fileMapper;


    /*
      가맹점 리스트 조회
     */
    public List<AfflEntity> selectTargetAfflGridList(String userId, String authTpCd) throws Exception {
        return afflMapper.selectTargetAfflGridList(userId, authTpCd);
    }


    /*
      팝업 가맹점 리스트 조회
     */
    public GridResponse selectPopAfflGridList(String userId, String authTpCd, String afflShopNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = afflMapper.selectPopAfflGridCnt( userId, authTpCd,  afflShopNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<AfflEntity> entities = afflMapper.selectPopAfflGridList(userId, authTpCd,  afflShopNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> AfflSearchResponse.builder()
                        .viewCd("R")
                        .afflShopId(m.getAfflShopId())
                        .afflShopNm(m.getAfflShopNm())
                        .afflAbbr(m.getAfflAbbr())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*  가맹점  조회 */
    public GridResponse selectAfflShopGridList( String fromDt, String toDt, String sAfflShopNm, 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 = afflMapper.selectAfflShopGridCnt(fromDt, toDt, sAfflShopNm, sStCd);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<AfflEntity> entities = afflMapper.selectAfflShopGridList(fromDt, toDt, sAfflShopNm, sStCd, gridRequest);

        List<Object> gridRows = entities.stream()
                .map(m -> AfflShopBaseInfoSearchResponse.builder()
                        .viewCd("R")
                        .afflShopId(m.getAfflShopId()  == null ? "" : m.getAfflShopId() )
                        .afflShopNm(m.getAfflShopNm()  == null ? "" : m.getAfflShopNm() )
                        .corpType(m.getCorpType() == null ? "" : m.getCorpType())
                        .corpTypeNm(m.getCorpTypeNm() == null ? "" : m.getCorpTypeNm())
                        .stCd(m.getStCd())
                        .stNm(m.getStNm())
                        .ownerNm(m.getOwnerNm())
                        .rprstTelNo(m.getRprstTelNo())
                        .joinDt(m.getJoinDt())
                        .build())
                .collect(Collectors.toList());

        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 가맹점 정보 */
    public AfflShopInfoResponse selectAfflShopInfo(String afflShopId) throws Exception {
        AfflEntity entity = afflMapper.selectAfflShopBaseInfo(afflShopId);
        List<AfflSaleInfoEntity> saleList = afflMapper.selectAfflSaleTargetList(afflShopId);
        List<FileEntity> logFileList = null;

        if (!"".equals(entity.getCmpnyLogoFileNo())) {
            logFileList = fileMapper.selectFileList(entity.getCmpnyLogoFileNo()) ;
        } else {
            logFileList = new ArrayList<FileEntity>();
        }

        List<FileEntity> nFileList = null;
        return AfflShopInfoResponse.toDTO(entity,saleList, logFileList );
    }

    /* 가맹점 저장 */
    @Transactional
    public void saveAfflList(String userId, SaveAfflRequest saveAfflRequest) throws Exception {
        try {

            AfflEntity entity = new AfflEntity();
            entity.setAfflShopId (saveAfflRequest.getAfflShopId());
            entity.setAfflShopNm (saveAfflRequest.getAfflShopNm());
            entity.setStCd (saveAfflRequest.getStCd());
            entity.setAfflAbbr (saveAfflRequest.getAfflAbbr().replaceAll(" ",""));
            entity.setBsnsRegNo (saveAfflRequest.getBsnsRegNo().replaceAll("-",""));
            entity.setCorpRegNo (saveAfflRequest.getCorpRegNo().replaceAll("-",""));
            entity.setBsnsCndt (saveAfflRequest.getBsnsCndt());
            entity.setCtgrBsns (saveAfflRequest.getCtgrBsns());
            entity.setOwnerNm (saveAfflRequest.getOwnerNm());
            entity.setOwnerTelNo (saveAfflRequest.getOwnerTelNo().replaceAll("-",""));
            entity.setRprstFaxNo (saveAfflRequest.getRprstFaxNo().replaceAll("-",""));
            entity.setRprstEmai (saveAfflRequest.getRprstEmai());
            entity.setZipNo (saveAfflRequest.getZipNo());
            entity.setAddr1 (saveAfflRequest.getAddr1());
            entity.setAddr2 (saveAfflRequest.getAddr2());
            entity.setRprstTelNo (saveAfflRequest.getRprstTelNo().replaceAll("-",""));
            entity.setLatX (saveAfflRequest.getLatX());
            entity.setLongY (saveAfflRequest.getLongY());
            entity.setRegDt (saveAfflRequest.getRegDt().replaceAll("\\.",""));
            entity.setJoinSttDt (saveAfflRequest.getJoinSttDt().replaceAll("\\.",""));
            entity.setJoinEndDt (saveAfflRequest.getJoinEndDt().replaceAll("\\.",""));
            entity.setCmpnyLogoFileNo (saveAfflRequest.getCmpnyLogoFileNo());
            entity.setCorpType (saveAfflRequest.getCorpType());

            if ("C".equals(saveAfflRequest.getViewCd())) {
                // 가맹점 아이디 부여  22  entity.setContentsNo(fnGetKeyNo(17));
                entity.setAfflShopId(fnGetKeyNo(22));  // 가맹점아이디 생성
                afflMapper.insertAfflShopBaseInfo(userId, entity);

                //사용자 계정 정보 생성 및 권한생성
                UserMngEntity userEntity = new UserMngEntity();
                userEntity.setUserId(entity.getAfflShopId());
                userEntity.setUserNm(entity.getAfflShopNm());
                userEntity.setTelNo(entity.getRprstTelNo());
                userEntity.setEmail(entity.getRprstEmai());

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

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

                // 사용자 권한 등록
                userMngMapper.insertUserTypeAuth(entity.getAfflShopId(), userId, "30");

            } else if ("U".equals(saveAfflRequest.getViewCd())) {
                afflMapper.updateAfflShopBaseInfo(userId, entity);

                UserMngEntity userUEntity = new UserMngEntity();
                userUEntity.setUserId(entity.getAfflShopId());
                userUEntity.setTelNo(entity.getRprstTelNo());
                userUEntity.setEmail(entity.getRprstEmai());

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

            //  영업담당자 상세 정보 저장
            // 신규건
            List<AfflSaleInfoEntity> gridInsertData = saveAfflRequest.toCodeEntities(saveAfflRequest.getGridInsertData());
            if (gridInsertData.size() > 0) {
                if ("C".equals(saveAfflRequest.getViewCd())) {
                    for (int i = 0 ; i < gridInsertData.size() ; i++ )
                    {
                        gridInsertData.get(i).setAfflShopId(entity.getAfflShopId());
                    }
                }

                afflMapper.insertAfflSaleInfo(userId, gridInsertData) ;
            }
            // 삭제건
            List<AfflSaleInfoEntity> gridDeleteData = saveAfflRequest.toCodeEntities(saveAfflRequest.getGridDeleteData());
            if (gridDeleteData.size() > 0) {
                afflMapper.deleteUserAuth(userId, gridDeleteData) ;
            }

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


     /*
     가맹 Key 중복체크
     */
    public String selectAfflAbbrDupYn(String afflAbbr) throws Exception {
        return afflMapper.selectAfflAbbrDupYn(afflAbbr);
    }


    /*
  가맹점 로그인 pw 초기화
   */
    public String updateInitUserPw(String afflShopId) throws Exception {
        // 사용자 정보를 가져옴
        try {
            String initPw  = afflMapper.selectAfflShopInitPw(afflShopId);
            String password = passwordEncoder.encode(initPw);//aes256.aesEncode(entity.getTelNo());
            userMngMapper.updateInitUserPw(afflShopId, password);
            return password;
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }
}
