package com.oqpo.api.service.stinfo;


import com.oqpo.api.entity.CodeEntity;
import com.oqpo.api.entity.oper.FileEntity;
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.stinfo.ItemMapper;
import com.oqpo.api.mapper.stinfo.ItemUnitMapper;
import com.oqpo.api.mapper.stinfo.StoreItemUnitMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.GridRequest;
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.request.stinfo.itemUnit.SaveItemUnitInfolRequest;
import com.oqpo.api.web.dto.request.stinfo.itemUnit.SaveStoreItemUnitInfolRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.code.CodeSearchListResponse;
import com.oqpo.api.web.dto.response.stinfo.item.*;
import com.oqpo.api.web.dto.response.stinfo.itemUnit.ItemUnitInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.itemUnit.ItemUnitSearchResponse;
import com.oqpo.api.web.dto.response.stinfo.itemUnit.StoreItemUnitInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.itemUnit.StoreItemUnitSearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 ItemUnitService extends CommonService {
    @Autowired
    private ItemUnitMapper itemUnitMapper;

    @Autowired
    private StoreItemUnitMapper storeItemUnitMapper;


    @Autowired
    private FileMapper fileMapper;

    /*
      브랜드 공급사 단가 리스트 조회

     */
    public GridResponse selectItemUnitGridList(String sBrandId, String fromDt, String toDt,String sUnitStCd, String sSpplyId, String sClass1, String sClass2, String sClass3, String sClass4, String sItemNm,   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 = itemUnitMapper.selectItemUnitGridCnt( sBrandId, fromDt,  toDt, sUnitStCd, sSpplyId, sClass1, sClass2, sClass3, sClass4,sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<ItemUnitEntity> entities = itemUnitMapper.selectItemUnitGridList(sBrandId, fromDt,  toDt, sUnitStCd, sSpplyId, sClass1, sClass2, sClass3, sClass4,sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ItemUnitSearchResponse.builder()
                        .viewCd("R")
                        .brandUnitUnqNo(m.getBrandUnitUnqNo())
                        .brandId(m.getBrandId())
                        .itemId(m.getItemId())
                        .itemNm(m.getItemNm())
                        .spplyId(m.getSpplyId())
                        .spplyNm(m.getSpplyNm())
                        .contSttDt(m.getContSttDt() == null ? "" :m.getContSttDt())
                        .contEndDt(m.getContEndDt() == null ? "" :m.getContEndDt())
                        .curr(m.getCurr() == null ? "" :m.getCurr())
                        .currNm(m.getCurrNm() == null ? "" :m.getCurrNm() )
                        .unit(m.getUnit() == null ? "" :m.getUnit())
                        .unitNm(m.getUnitNm() == null ? "" :m.getUnitNm())
                        .unitAmt(m.getUnitAmt() == null ? 0 :m.getUnitAmt())
                        .leadTime(m.getLeadTime() == null ? 0 :m.getLeadTime())
                        .spplyItemId(m.getSpplyItemId() == null ? "" :m.getSpplyItemId())
                        .unitStCd(m.getUnitStCd() == null ? "" :m.getUnitStCd())
                        .unitStNm(m.getUnitStNm() == null ? "" :m.getUnitStNm())
                        .stddQty(m.getStddQty() == null ? 0 :m.getStddQty() )
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }



    /* 공급사 단가 정보 */
    public ItemUnitInfoResponse selectItemUnitInfo(String brandId, String brandUnitUnqNo) throws Exception {

        ItemUnitEntity entity = itemUnitMapper.selectItemUnitInfo( brandId, brandUnitUnqNo);
        List<FileEntity> fileContInfoList = null;

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

        return ItemUnitInfoResponse.toDTO(entity,fileContInfoList );

    }

    /* 공급사 단가 저장 */
    @Transactional
    public void saveItemUnitInfo(String userId, SaveItemUnitInfolRequest saveItemUnitInfolRequest) throws Exception {
        try {

            ItemUnitEntity entity = new ItemUnitEntity();
            entity.setBrandUnitUnqNo(saveItemUnitInfolRequest.getBrandUnitUnqNo());
            entity.setBrandId(saveItemUnitInfolRequest.getBrandId());
            entity.setBrandNm(saveItemUnitInfolRequest.getBrandNm());
            entity.setItemId(saveItemUnitInfolRequest.getItemId());
            entity.setItemNm(saveItemUnitInfolRequest.getItemNm());
            entity.setSpplyId(saveItemUnitInfolRequest.getSpplyId());
            entity.setSpplyNm(saveItemUnitInfolRequest.getSpplyNm());
            entity.setContSttDt(saveItemUnitInfolRequest.getContSttDt().replaceAll("\\.",""));
            entity.setContEndDt(saveItemUnitInfolRequest.getContEndDt().replaceAll("\\.",""));
            entity.setCurr(saveItemUnitInfolRequest.getCurr());
            entity.setUnit(saveItemUnitInfolRequest.getUnit());
            entity.setUnitAmt(saveItemUnitInfolRequest.getUnitAmt());
            entity.setLeadTime(saveItemUnitInfolRequest.getLeadTime());
            entity.setDlvCndt(saveItemUnitInfolRequest.getDlvCndt());
            entity.setShortContFileNo(saveItemUnitInfolRequest.getShortContFileNo());
            entity.setSpplyItemId(saveItemUnitInfolRequest.getSpplyItemId());
            entity.setUnitStCd(saveItemUnitInfolRequest.getUnitStCd());
            entity.setStddQty(saveItemUnitInfolRequest.getStddQty());
            entity.setStoreSaleStddQty(saveItemUnitInfolRequest.getStoreSaleStddQty());
            entity.setStoreSaleUnitAmt(saveItemUnitInfolRequest.getStoreSaleUnitAmt());

            if ("C".equals(saveItemUnitInfolRequest.getViewCd())) {
                //selectItemUnitDupContInfoNo  날짜 기준 계약 존재여부 파악
                ItemUnitEntity condtEntity = itemUnitMapper.selectItemUnitDupContInfoNo(entity.getBrandId(), entity.getSpplyId(), entity.getItemId(), entity.getContSttDt(), entity.getContEndDt());

                if (condtEntity != null && !"".equals(condtEntity.getBrandUnitUnqNo())) {
                    itemUnitMapper.updateItemUnitContEnd(entity.getBrandId(), entity.getBrandUnitUnqNo(), entity.getContEndDt());
                }
            }
            itemUnitMapper.insertMergItemUnitInfo(userId, entity);


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


    /*
      브랜드 매장 단가 리스트 조회
     */
    public GridResponse selectStoreItemUnitGridList(String sBrandId, String sStoreId,  GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = storeItemUnitMapper.selectStoreItemUnitGridCnt( sBrandId, sStoreId );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<StoreItemUnitEntity> entities = storeItemUnitMapper.selectStoreItemUnitGridList(sBrandId, sStoreId, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> StoreItemUnitSearchResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .storeId(m.getStoreId())
                        .storeNm(m.getStoreNm())
                        .contSttDt(m.getContSttDt())
                        .contEndDt(m.getContEndDt())
                        .sysRegDttm(m.getSysRegDttm())
                        .itemCnt(m.getItemCnt())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /* 매장 단가 정보 */
    public StoreItemUnitInfoResponse selectStoreItemUnitInfo(String brandId, String storeId, String contSttDt, String contEndDt) throws Exception {

        List<StoreItemUnitEntity> entities = storeItemUnitMapper.selectStoreItemUnitInfo( brandId, storeId, contSttDt, contEndDt);
        return StoreItemUnitInfoResponse.toDTO(entities);

    }


    /* 매장 단가 저장 */
    @Transactional
    public void saveStroeItemUnitInfo(String userId, SaveStoreItemUnitInfolRequest saveStoreItemUnitInfolRequest) throws Exception {
        try {

            StoreItemUnitEntity entity = new StoreItemUnitEntity();
            entity.setBrandId(saveStoreItemUnitInfolRequest.getBrandId());
            entity.setStoreId(saveStoreItemUnitInfolRequest.getStoreId());
            entity.setContSttDt(saveStoreItemUnitInfolRequest.getContSttDt().replaceAll("\\.",""));
            entity.setContEndDt(saveStoreItemUnitInfolRequest.getContEndDt().replaceAll("\\.",""));

            String rcontEndDt =  storeItemUnitMapper.selectStoreItemUnitContDateInfo(entity.getBrandId(), entity.getStoreId(), entity.getContSttDt(), entity.getContEndDt());
            if (!"".equals(rcontEndDt))
            {
                System.out.println("chkDataEnity===getContEndDt==>" + rcontEndDt);
                storeItemUnitMapper.updateStoreItemUnitContEnd(entity.getBrandId(), entity.getStoreId(), rcontEndDt,  entity.getContSttDt());

            }


            List<StoreItemUnitEntity> gridUpdateData = saveStoreItemUnitInfolRequest.toCodeEntities(saveStoreItemUnitInfolRequest.getGridUpdateData());
            if (gridUpdateData.size() > 0) {

                if (!"".equals(rcontEndDt)) {
                    for (int i = 0; i < gridUpdateData.size(); i++) {
                        gridUpdateData.get(i).setStoreUnitUnqNo("");
                    }
                }

                storeItemUnitMapper.insertMergStoreItemUnitInfo(userId, entity.getBrandId(), entity.getStoreId(), entity.getContSttDt(),entity.getContEndDt(), gridUpdateData) ;
            }

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

}
