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.SaleMgrMgntEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.oper.AfflMapper;
import com.oqpo.api.mapper.oper.SaleMgrMgnMapper;
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.request.oper.salemgr.SaveSaleMgrMgnlRequest;
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.oper.salemgr.SaleMgrMgnInfoResponse;
import com.oqpo.api.web.dto.response.oper.salemgr.SaleMgrMgnSearchResponse;
import com.oqpo.api.web.dto.response.oper.salemgr.SaleMgrPopSearchResponse;
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.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SaleMgrMgnService extends CommonService {
    @Autowired
    private SaleMgrMgnMapper saleMgrMgnMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMngMapper userMngMapper;

    /*
      팝업 영업담당자 리스트 조회
     */
    public GridResponse selectPopSaleMgrMgnGridList(String sSaleMgrNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = saleMgrMgnMapper.selectPopSaleMgrMgnGridCnt(sSaleMgrNm);

        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<SaleMgrMgntEntity> entities = saleMgrMgnMapper.selectPopSaleMgrMgnGridList(sSaleMgrNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> SaleMgrPopSearchResponse.builder()
                        .viewCd("R")
                        .saleMgrId(m.getSaleMgrId())
                        .saleMgrNm(m.getSaleMgrNm())
                        .rprstTelNo(m.getRprstTelNo())
                        .rprstEmai(m.getRprstEmai())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*  영업담당자  조회 */
    public GridResponse selectSaleMgrMgnGridList( String fromDt, String toDt, String sSaleMgrNm, 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 = saleMgrMgnMapper.selectSaleMgrMgnGridCnt(fromDt, toDt, sSaleMgrNm, sStCd);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<SaleMgrMgntEntity> entities = saleMgrMgnMapper.selectSaleMgrMgnGridList(fromDt, toDt, sSaleMgrNm, sStCd, gridRequest);

        List<Object> gridRows = entities.stream()
                .map(m -> SaleMgrMgnSearchResponse.builder()
                        .viewCd("R")
                        .saleMgrId(m.getSaleMgrId())
                        .saleMgrNm(m.getSaleMgrNm())
                        .stCd(m.getStCd())
                        .stNm(m.getStNm())
                        .regDt(m.getRegDt())
                        .build())
                .collect(Collectors.toList());

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

    /* 영업담당자 정보 */
    public SaleMgrMgnInfoResponse selectSaleMgrMgn(String saleMgrId) throws Exception {
        return SaleMgrMgnInfoResponse.toDTO(saleMgrMgnMapper.selectSaleMgrMgn(saleMgrId));
    }

    /* 영업담당자 저장 */
    @Transactional
    public void saveSaleMgrMgn(String userId, SaveSaleMgrMgnlRequest saveSaleMgrMgnlRequest) throws Exception {
        try {

            SaleMgrMgntEntity entity = new SaleMgrMgntEntity();
            entity.setSaleMgrId(saveSaleMgrMgnlRequest.getSaleMgrId());
            entity.setSaleMgrNm(saveSaleMgrMgnlRequest.getSaleMgrNm());
            entity.setStCd(saveSaleMgrMgnlRequest.getStCd());
            entity.setSaleType(saveSaleMgrMgnlRequest.getSaleType());
            entity.setRprstTelNo(saveSaleMgrMgnlRequest.getRprstTelNo().replaceAll("-",""));
            entity.setRprstFaxNo(saveSaleMgrMgnlRequest.getRprstFaxNo().replaceAll("-",""));
            entity.setRprstEmai(saveSaleMgrMgnlRequest.getRprstEmai());
            entity.setZipNo(saveSaleMgrMgnlRequest.getZipNo());
            entity.setAddr1(saveSaleMgrMgnlRequest.getAddr1());
            entity.setAddr2(saveSaleMgrMgnlRequest.getAddr2());
            entity.setLatX(saveSaleMgrMgnlRequest.getLatX());
            entity.setLongY(saveSaleMgrMgnlRequest.getLongY());

           // entity.setPswd(saveSaleMgrMgnlRequest.getPswd());
            if ("C".equals(saveSaleMgrMgnlRequest.getViewCd())) {
                saleMgrMgnMapper.insertSaleMgrMgn(userId, entity);

                //사용자 계정 정보 생성 및 권한생성
                UserMngEntity userEntity = new UserMngEntity();
                userEntity.setUserId(entity.getSaleMgrId());
                userEntity.setUserNm(entity.getSaleMgrNm());
                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("20");
                //패스워드 암호화
                String password = passwordEncoder.encode(saveSaleMgrMgnlRequest.getPswd());
                userEntity.setUserPw(password);
                userMngMapper.insertUserInfo(userId, userEntity);

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

            } else if ("U".equals(saveSaleMgrMgnlRequest.getViewCd())) {
                saleMgrMgnMapper.updateSaleMgrMgn(userId, entity);

                UserMngEntity userUEntity = new UserMngEntity();
                userUEntity.setUserId(entity.getSaleMgrId());
                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);
            }

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


     /*
     영업담당자 아이디 중복체크
     */
    public String selectSaleMgrIdDupYn(String saleMgrId) throws Exception {
        return userMngMapper.selectUserIdDupYn(saleMgrId);
        //return saleMgrMgnMapper.selectSaleMgrIdDupYn(saleMgrId);
    }


    /*
  영업담당자 비번  초기화
   */
    @Transactional
    public String selectSaleMgrInitPw(String userId, String saleMgrId) throws Exception {
        // 사용자 정보를 가져옴
        try {
            String initPw  = saleMgrMgnMapper.selectSaleMgrInitPw(saleMgrId);
            String password = passwordEncoder.encode(initPw);
            userMngMapper.updateInitUserPw(saleMgrId, password);

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