package com.oqpo.api.service.stinfo;


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.entity.stinfo.BrandEntity;
import com.oqpo.api.entity.stinfo.SpplyEntity;
import com.oqpo.api.entity.stinfo.SpplyMgrEntity;
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.mapper.stinfo.SupplyMapper;
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.stinfo.spply.SaveSpplyRequest;
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 com.oqpo.api.web.dto.response.stinfo.brand.BrandInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.spply.SpplyInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.spply.SpplyPopSearchResponse;
import com.oqpo.api.web.dto.response.stinfo.spply.SpplySearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
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 SpplyService extends CommonService {
    @Autowired
    private SupplyMapper supplyMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private FileMapper fileMapper;

    /*
      팝업 공급사 리스트 조회
     */
    public GridResponse selectPopSpplyGridList(String sBrandId, String sSpplyNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = supplyMapper.selectPopSpplyGridCnt( sBrandId, sSpplyNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<SpplyEntity> entities = supplyMapper.selectPopSpplyGridList(sBrandId, sSpplyNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> SpplyPopSearchResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .spplyId(m.getSpplyId())
                        .spplyNm(m.getSpplyNm())
                        .stCd(m.getStCd() == null ? "" : m.getStCd() )
                        .stNm(m.getStNm() == null ? "" : m.getStNm() )
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*  공급사  조회 */
    public GridResponse selectSpplyGridList( String sBrandId, String sStCd, String sBsnsRegNo, String sSpplyNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();


        int gridRecords = supplyMapper.selectSpplyGridCnt(sBrandId, sStCd, sBsnsRegNo, sSpplyNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<SpplyEntity> entities = supplyMapper.selectSpplyGridList(sBrandId, sStCd, sBsnsRegNo, sSpplyNm, gridRequest);

        List<Object> gridRows = entities.stream()
                .map(m -> SpplySearchResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .spplyId(m.getSpplyId())
                        .spplyNm(m.getSpplyNm())
                        .stCd(m.getStCd() == null ? "" : m.getStCd() )
                        .stNm(m.getStNm() == null ? "" : m.getStNm() )
                        .bsnsRegNo(m.getBsnsRegNo() == null ? "" : m.getBsnsRegNo())
                        .ownerNm(m.getOwnerNm() == null ? "" :  m.getOwnerNm())
                        .build())
                .collect(Collectors.toList());

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

    /* 공급사 정보 */
    public SpplyInfoResponse selectSpplyInfo(String brandId, String spplyId) throws Exception {

        SpplyEntity entity = supplyMapper.selectSpplyInfo(brandId, spplyId);
        List<SpplyMgrEntity> supplyList = supplyMapper.selectSpplyMgrList(spplyId);

        List<FileEntity> bookCopyFileList = null;
        List<FileEntity> bsnsRegNoFileList = null;

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

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


        return SpplyInfoResponse.toDTO(entity,supplyList, bookCopyFileList, bsnsRegNoFileList) ;
    }

    /* 공급사 저장 */
    @Transactional
    public void saveSpplyList(String userId, SaveSpplyRequest saveSpplyRequest) throws Exception {
        try {

            SpplyEntity entity = new SpplyEntity();
            entity.setSpplyId(saveSpplyRequest.getSpplyId());
            entity.setSpplyNm(saveSpplyRequest.getSpplyNm());
            entity.setStCd(saveSpplyRequest.getStCd());
            entity.setCorpType(saveSpplyRequest.getCorpType());
            entity.setBsnsRegNo(saveSpplyRequest.getBsnsRegNo().replaceAll("-",""));
            entity.setCorpRegNo(saveSpplyRequest.getCorpRegNo().replaceAll("-",""));
            entity.setOwnerNm(saveSpplyRequest.getOwnerNm());
            entity.setCtgrBsns(saveSpplyRequest.getCtgrBsns());
            entity.setBsnsCndt(saveSpplyRequest.getBsnsCndt());
            entity.setCorpDvsn(saveSpplyRequest.getCorpDvsn());
            entity.setMgrNm(saveSpplyRequest.getMgrNm());
            entity.setAreaCd(saveSpplyRequest.getAreaCd());
            entity.setMgrEmal(saveSpplyRequest.getMgrEmal());
            entity.setMgrTelNo(saveSpplyRequest.getMgrTelNo().replaceAll("-",""));
            entity.setMgrMblNo(saveSpplyRequest.getMgrMblNo().replaceAll("-",""));
            entity.setZipNo(saveSpplyRequest.getZipNo());
            entity.setAddr1(saveSpplyRequest.getAddr1());
            entity.setAddr2(saveSpplyRequest.getAddr2());
            entity.setBrandId(saveSpplyRequest.getBrandId());
            entity.setBnkCd(saveSpplyRequest.getBnkCd());
            entity.setAcctNo(saveSpplyRequest.getAcctNo());
            entity.setOwacNm(saveSpplyRequest.getOwacNm());
            entity.setBbookCopyFileNo(saveSpplyRequest.getBbookCopyFileNo());
            entity.setBsnsRegFileNo(saveSpplyRequest.getBsnsRegFileNo());
            entity.setLatX(saveSpplyRequest.getLatX());
            entity.setLongY(saveSpplyRequest.getLongY());

            if ("C".equals(saveSpplyRequest.getViewCd())) {
                // 공급사 아이디 부여  22  entity.setContentsNo(fnGetKeyNo(17));
                entity.setSpplyId(fnGetKeyNo(30));  // 공급사아이디 생성
                supplyMapper.insertSpplyInfo(userId, entity);

                //사용자 계정 정보 생성 및 권한생성
                UserMngEntity userEntity = new UserMngEntity();
                userEntity.setUserId(entity.getSpplyId());
                userEntity.setUserNm(entity.getSpplyNm());
                userEntity.setTelNo(entity.getMgrTelNo());
                userEntity.setEmail(entity.getMgrEmal());

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

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

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

            } else if ("U".equals(saveSpplyRequest.getViewCd())) {
                supplyMapper.updateSpplyInfo(userId, entity);

                UserMngEntity userUEntity = new UserMngEntity();
                userUEntity.setUserId(entity.getSpplyId());
                userUEntity.setUserNm(entity.getSpplyNm());
                userUEntity.setTelNo(entity.getMgrTelNo());
                userUEntity.setEmail(entity.getMgrEmal());

                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<SpplyMgrEntity> gridInsertData = saveSpplyRequest.toCodeEntities(saveSpplyRequest.getGridInsertData());
            if (gridInsertData.size() > 0) {

                int maxSupplyMgrId = supplyMapper.selectMaxSpplyMgrId(entity.getSpplyId());
                for (int i = 0 ; i < gridInsertData.size() ; i++ )
                {
                    gridInsertData.get(i).setSpplyId(entity.getSpplyId());
                    gridInsertData.get(i).setSpplyMgrId(maxSupplyMgrId + i);
                    gridInsertData.get(i).setRprstTelNo(gridInsertData.get(i).getRprstTelNo().replaceAll("-",""));
                }
                supplyMapper.insertSpplyMgrInfo(userId, gridInsertData) ;
            }
            // 삭제건
            List<SpplyMgrEntity> gridDeleteData = saveSpplyRequest.toCodeEntities(saveSpplyRequest.getGridDeleteData());
            if (gridDeleteData.size() > 0) {
                supplyMapper.deleteSpplyMgrInfo(entity.getSpplyId(), gridDeleteData) ;
            }

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


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