package com.oqpo.api.service.stinfo;


import com.oqpo.api.entity.oper.FileEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.stinfo.*;
import com.oqpo.api.enums.SystemMessageCode;
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.stinfo.brand.SaveBrandInfolRequest;
import com.oqpo.api.web.dto.request.stinfo.item.DelItemInfolRequest;
import com.oqpo.api.web.dto.request.stinfo.item.SaveItemClassMngInfolRequest;
import com.oqpo.api.web.dto.request.stinfo.item.SaveItemInfolRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.AfflBrandSearchResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.BrandInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.BrandSearchListResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.BrandSearchResponse;
import com.oqpo.api.web.dto.response.stinfo.item.*;
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 ItemService extends CommonService {
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private FileMapper fileMapper;

    /*
      팝업 품목 리스트 조회
     */
    public GridResponse selectPopItemGridList(String sBrandId, String sPodrPssblDvsn, String sItemNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = itemMapper.selectPopItemGridCnt( sBrandId, sPodrPssblDvsn,  sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<ItemEntity> entities = itemMapper.selectPopItemGridList(sBrandId, sPodrPssblDvsn,  sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ItemPopSearchResponse.builder()
                        .viewCd("R")
                        .itemId(m.getItemId())
                        .itemNm(m.getItemNm())
                        .podrPssblDvsn(m.getPodrPssblDvsn())
                        .podrPssblDvsnNm(m.getPodrPssblDvsnNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      품목 그리드 리스트 조회
     */
    public GridResponse selectItemGridList( String sBrandId, String sItemStCd, String sPodrPssblDvsn, String sItemType, String sItemGubun, String sClass1, String sClass2, String sClass3, String sClass4, String sItemNm,  GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = itemMapper.selectItemGridCnt( sBrandId, sItemStCd, sPodrPssblDvsn, sItemType, sItemGubun, sClass1, sClass2, sClass3, sClass4, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<ItemEntity> entities = itemMapper.selectItemGridList( sBrandId, sItemStCd, sPodrPssblDvsn, sItemType, sItemGubun, sClass1, sClass2, sClass3, sClass4, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ItemSearchListResponse.builder()
                        .viewCd("R")
                        .itemId(m.getItemId())
                        .itemNm(m.getItemNm() == null ? "" :m.getItemNm()  )
                        .itemType(m.getItemType() == null ? "" :m.getItemType() )
                        .itemTypeNm(m.getItemTypeNm() == null ? "" :m.getItemTypeNm() )
                        .itemClassMgntNo(m.getItemClassInfo() == null ? "" : m.getItemClassInfo().getItemClassMgntNo() == null ? "" : m.getItemClassInfo().getItemClassMgntNo())
                        .itemClassNm(m.getItemClassMngInfo() == null ? "" : m.getItemClassMngInfo().getItemClassNm() == null ? "" : m.getItemClassMngInfo().getItemClassNm())
                        .itemStCd(m.getItemStCd() == null ? "" :m.getItemStCd())
                        .itemStNm(m.getItemStNm() == null ? "" :m.getItemStNm() )
                        .podrPssblDvsn(m.getPodrPssblDvsn() == null ? "" : m.getPodrPssblDvsn())
                        .podrPssblDvsnNm(m.getPodrPssblDvsnNm() == null ? "" :m.getPodrPssblDvsnNm())
                        .unit(m.getUnit() == null ? "" : m.getUnit())
                        .unitNm(m.getUnitNm() == null ? "" :m.getUnitNm() )
                        .pchItemYn(m.getPchItemYn() == null ? "" : m.getPchItemYn())
                        .saleItemYn(m.getSaleItemYn() == null ? "" :m.getSaleItemYn() )
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 품목 정보 */
    public ItemInfoResponse selectItemInfo(String brandId, String itemId) throws Exception {

        ItemEntity entity = itemMapper.selectItemInfo( brandId, itemId);
        List<FileEntity> fileImageInfoList = null;

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

        return ItemInfoResponse.toDTO(entity,fileImageInfoList );

    }

    /* 품목 저장 */
    @Transactional
    public void saveItemInfo(String userId, SaveItemInfolRequest saveItemInfolRequest) throws Exception {
        try {

            ItemEntity entity = new ItemEntity();
            entity.setBrandId(saveItemInfolRequest.getBrandId());
            entity.setItemId(saveItemInfolRequest.getItemId());
            entity.setItemNm(saveItemInfolRequest.getItemNm());
            entity.setPchUnit(saveItemInfolRequest.getPchUnit());
            entity.setWeight(saveItemInfolRequest.getWeight());
            entity.setVolume(saveItemInfolRequest.getVolume());
            entity.setWidth(saveItemInfolRequest.getWidth());
            entity.setHeight(saveItemInfolRequest.getHeight());
            entity.setHigh(saveItemInfolRequest.getHigh());
            entity.setExpryYn(saveItemInfolRequest.getExpryYn());
            entity.setRtnDvsn(saveItemInfolRequest.getRtnDvsn());
            entity.setImpDvsn(saveItemInfolRequest.getImpDvsn());
            entity.setAssetInfo(saveItemInfolRequest.getAssetInfo());
            entity.setStckUnit(saveItemInfolRequest.getStckUnit());
            entity.setPodrPssblDvsn(saveItemInfolRequest.getPodrPssblDvsn());
            entity.setPchItemYn(saveItemInfolRequest.getPchItemYn());
            entity.setSaleItemYn(saveItemInfolRequest.getSaleItemYn());
            entity.setItemStCd(saveItemInfolRequest.getItemStCd());
            entity.setItemType(saveItemInfolRequest.getItemType());
            entity.setSaleUnit(saveItemInfolRequest.getSaleUnit());
            entity.setUnit(saveItemInfolRequest.getUnit());
            entity.setRtnPssblYn(saveItemInfolRequest.getRtnPssblYn());
            entity.setItemImageFileNo(saveItemInfolRequest.getItemImageFileNo());
            entity.setOneBoxQty(saveItemInfolRequest.getOneBoxQty());

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

                // 품목 아이디 부여  22  entity.setContentsNo(fnGetKeyNo(17));
                entity.setItemId(fnGetDealNo(26,""));  // 품목아이디 생성
                itemMapper.insertItemInfo(userId, entity);
            } else if ("U".equals(saveItemInfolRequest.getViewCd())) {
                itemMapper.updateItemInfo(userId, entity);

                itemMapper.deleteItemClassInfo(entity.getItemId());
            }

            // 품목 class 정보 등록
            ItemClassEntity iClassEntity = new ItemClassEntity();

            iClassEntity.setItemId(entity.getItemId());
            iClassEntity.setItemNm(entity.getItemNm());
           // System.out.println("saveItemInfolRequestgetItemClass1==>" + saveItemInfolRequest.getItemClass1() );
            //System.out.println("saveItemInfolRequestgetItemClass2==>" + saveItemInfolRequest.getItemClass2() );
            //System.out.println("saveItemInfolRequestgetItemClass3==>" + saveItemInfolRequest.getItemClass3() );
            //System.out.println("saveItemInfolRequestgetItemClass4==>" + saveItemInfolRequest.getItemClass4() );
            iClassEntity.setItemClass1(saveItemInfolRequest.getItemClass1());
            iClassEntity.setItemClass2(saveItemInfolRequest.getItemClass2());
            iClassEntity.setItemClass3(saveItemInfolRequest.getItemClass3());
            iClassEntity.setItemClass4(saveItemInfolRequest.getItemClass4());
            //System.out.println("getItemClass1==>" + iClassEntity.getItemClass1() );
            //System.out.println("getItemClass2==>" + iClassEntity.getItemClass2() );
            //System.out.println("getItemClass3==>" + iClassEntity.getItemClass3() );
           // System.out.println("getItemClass4==>" + iClassEntity.getItemClass4() );
            ItemClassMngEntity itemClassInfo =  itemMapper.selectItemClassMngNo(entity.getBrandId(), iClassEntity.getItemClass1(),iClassEntity.getItemClass2(),iClassEntity.getItemClass3(),iClassEntity.getItemClass4());
            iClassEntity.setItemClassMgntNo(itemClassInfo.getItemClassMgntNo());

            itemMapper.insertItemClassInfo(userId, iClassEntity);

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


    //
    /*
       품목분류 리스트 조회
     */
    public GridResponse selectItemClassMngGridList(String sBrandId, String sItemClass1, String sItemClass2, String sItemClass3, String sItemClass4, String sItemClassNm,GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = itemMapper.selectItemClassMngGridCnt( sBrandId, sItemClass1,  sItemClass2, sItemClass3, sItemClass4,sItemClassNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<ItemClassMngEntity> entities = itemMapper.selectItemClassMngGridList(sBrandId, sItemClass1,  sItemClass2, sItemClass3, sItemClass4,sItemClassNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ItemClassMngSearchResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId())
                        .itemClassMgntNo(m.getItemClassMgntNo())
                        .itemClassNm(m.getItemClassNm() == null ? "" : m.getItemClassNm() )
                        .itemClass1(m.getItemClass1() == null ? "" : m.getItemClass1())
                        .itemClass2(m.getItemClass2() == null ? "" : m.getItemClass2())
                        .itemClass3(m.getItemClass3() == null ? "" : m.getItemClass3())
                        .itemClass4(m.getItemClass4() == null ? "" : m.getItemClass4())
                        .prnSeq(m.getPrnSeq() == null ? 99 : m.getPrnSeq())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 품목 분류 정보 */
    public ItemClassMngInfoResponse selectItemClassMngInfo(String brandId, String itemClassMgnNo) throws Exception {
        return ItemClassMngInfoResponse.toDTO(itemMapper.selectItemClassMngInfo(brandId, itemClassMgnNo) );

    }

    /* 품목분류 저장 */
    @Transactional
    public void saveItemClassMngInfo(String userId, SaveItemClassMngInfolRequest saveItemClassMngInfolRequest) throws Exception {
        try {
            ItemClassMngEntity entity = new ItemClassMngEntity();
            entity.setBrandId(saveItemClassMngInfolRequest.getBrandId());
            entity.setItemClassNm(saveItemClassMngInfolRequest.getItemClassNm());
            entity.setItemClassMgntNo(saveItemClassMngInfolRequest.getItemClassMgntNo());
            entity.setItemClass1(saveItemClassMngInfolRequest.getItemClass1());
            entity.setItemClass2(saveItemClassMngInfolRequest.getItemClass2());
            entity.setItemClass3(saveItemClassMngInfolRequest.getItemClass3());
            entity.setItemClass4(saveItemClassMngInfolRequest.getItemClass4());
            entity.setPrnSeq(saveItemClassMngInfolRequest.getPrnSeq());

            if ("C".equals(saveItemClassMngInfolRequest.getViewCd())) {
                String classLevel = "1";
                if ("".equals(entity.getItemClass1()))
                {
                    // level 1 추가
                    classLevel = "1";
                } else {
                    if ("".equals(entity.getItemClass2()))
                    {
                        // level 2 추가
                        classLevel = "2";
                    } else {
                        if ("".equals(entity.getItemClass3()))
                        {
                            // level 3 추가
                            classLevel = "3";
                        } else {
                            if ("".equals(entity.getItemClass4()))
                            {
                                // level 4 추가
                                classLevel = "4";
                            } else {
                                // 오류
                                throw new GlobalException(SystemMessageCode.ERR_ITEMCLASS);
                            }
                        }
                    }
                }

                System.out.println("=classLevel============================>" + classLevel );
                entity.setCLevel(classLevel);
                int classNum = itemMapper.selectItemClassMaxClass(entity.getBrandId(), entity.getCLevel(), entity.getItemClass1(), entity.getItemClass2(), entity.getItemClass3(), entity.getItemClass4() ) ;
                if ("1".equals(classLevel)) {
                    entity.setItemClass1(Integer.toString(classNum));
                } else if ("2".equals(classLevel)) {
                    entity.setItemClass2(Integer.toString(classNum));
                }  else if ("3".equals(classLevel)) {
                    entity.setItemClass3(Integer.toString(classNum));
                }  else if ("4".equals(classLevel)) {
                    entity.setItemClass4(Integer.toString(classNum));
                }
                entity.setItemClassMgntNo(fnGetKeyNo(31));        // 품목분류 아이디 부여

                itemMapper.insertItemClassMngInfo(userId, entity);
            } else if ("U".equals(saveItemClassMngInfolRequest.getViewCd())) {
                itemMapper.updateItemClassMngInfo(userId, entity);
            }

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

    /* 품목분류 삭제 */
    @Transactional
    public void delItemClassMngInfo(String userId, DelItemInfolRequest delItemInfolRequest) throws Exception {
        try {
            List<ItemClassMngEntity> gridDeleteData = delItemInfolRequest.toCodeEntities(delItemInfolRequest.getGridDeleteData());
            if (gridDeleteData.size() > 0) {
                   itemMapper.deleteItemClassMngInfo(userId, gridDeleteData);
            }

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