package com.interplug.qcast.biz.canvasStatus;

import com.interplug.qcast.biz.canvasBasicSetting.CanvasBasicSettingMapper;
import com.interplug.qcast.biz.canvasBasicSetting.dto.CanvasBasicSettingInfo;
import com.interplug.qcast.biz.canvasBasicSetting.dto.CanvasBasicSettingResponse;
import com.interplug.qcast.biz.canvasBasicSetting.dto.RoofMaterialsAddInfo;
import com.interplug.qcast.biz.canvasStatus.dto.CanvasStatus;
import com.interplug.qcast.biz.canvasStatus.dto.CanvasStatusCopyRequest;
import com.interplug.qcast.biz.canvasStatus.dto.CanvasStatusResponse;
import com.interplug.qcast.config.Exception.ErrorCode;
import com.interplug.qcast.config.Exception.QcastException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class CanvasStatusService {
  private final CanvasStatusMapper canvasStatusMapper;
  private final CanvasBasicSettingMapper canvasBasicSettingMapper;

  // 사용자(userId)에 해당하는 전체 캔버스 조회
  public List<CanvasStatusResponse> selectAllCanvasStatus(String userId) throws QcastException {
    List<CanvasStatusResponse> result = null;

    try {
      if (userId != null && !userId.trim().isEmpty()) {
        result = canvasStatusMapper.selectAllCanvasStatus(userId);
      } else {
        throw new QcastException(ErrorCode.INVALID_INPUT_VALUE, "올바르지 않은 입력값입니다.");
      }
    } catch (Exception e) {
      if (e instanceof QcastException) throw e;
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return result;
  }

  // 물건번호(objectNo)에 해당하는 캔버스 조회
  public List<CanvasStatusResponse> selectObjectNoCanvasStatus(String objectNo)
      throws QcastException {
    List<CanvasStatusResponse> result = null;

    try {
      if (objectNo != null && !objectNo.trim().isEmpty()) {
        result = canvasStatusMapper.selectObjectNoCanvasStatus(objectNo);
      } else {
        throw new QcastException(ErrorCode.INVALID_INPUT_VALUE, "올바르지 않은 입력값입니다.");
      }
    } catch (Exception e) {
      if (e instanceof QcastException) throw e;
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return result;
  }

  // 캔버스 등록
  public Integer insertCanvasStatus(CanvasStatus cs) throws QcastException {

    Integer id = 0;

    // 데이터가 없으면 저장
    try {
      canvasStatusMapper.insertCanvasStatus(cs);

      // 데이터 저장 후 Max id 확인
      List<CanvasStatusResponse> maxId =
          canvasStatusMapper.getMaxIdCanvasStatus(cs.getObjectNo(), cs.getUserId());
      id = maxId.get(0).getId();

    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    // 생성된 id 반환
    return id;
  }

  // 캔버스 수정
  public void updateCanvasStatus(CanvasStatus cs) throws QcastException {

    if (cs.getId() == null) {
      throw new QcastException(ErrorCode.INVALID_INPUT_VALUE, "올바르지 않은 입력값입니다.");
    }

    try {
      // 먼저 데이터가 존재하는지 확인
      List<CanvasStatusResponse> existingStatus = canvasStatusMapper.getIdCanvasStatus(cs.getId());

      // 데이터가 존재하지 않으면 수정하지 않고 예외를 던짐
      if (existingStatus.size() > 0) {
        canvasStatusMapper.updateCanvasStatus(cs);
      } else {
        throw new QcastException(ErrorCode.NOT_FOUND, "수정할 캔버스가 존재하지 않습니다.");
      }
    } catch (Exception e) {
      if (e instanceof QcastException) throw e;
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }

  // 물건번호(objectNo)에 해당하는 캔버스 삭제
  public void deleteObjectNoCanvasStatus(String objectNo) throws QcastException {

    if (objectNo == null || objectNo.trim().isEmpty()) {
      throw new QcastException(ErrorCode.INVALID_INPUT_VALUE, "올바르지 않은 입력값입니다.");
    }

    try {
      // 먼저 데이터가 존재하는지 확인
      List<CanvasStatusResponse> existingStatus =
          canvasStatusMapper.getObjectNoCanvasStatus(objectNo);

      // 데이터가 존재하지 않으면 수정하지 않고 예외를 던짐
      if (existingStatus.size() > 0) {
        canvasStatusMapper.deleteObjectNoCanvasStatus(objectNo);
      } else {
        throw new QcastException(ErrorCode.NOT_FOUND, "삭제할 캔버스가 존재하지 않습니다.");
      }
    } catch (Exception e) {
      if (e instanceof QcastException) throw e;
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }

  // id에 해당하는 캔버스 삭제
  public void deleteIdCanvasStatus(Integer id) throws QcastException {

    if (id == null) {
      throw new QcastException(ErrorCode.INVALID_INPUT_VALUE, "올바르지 않은 입력값입니다.");
    }

    try {
      // 먼저 데이터가 존재하는지 확인
      List<CanvasStatusResponse> existingStatus = canvasStatusMapper.getIdCanvasStatus(id);

      // 데이터가 존재하지 않으면 처리하지 않고 예외를 던짐
      if (existingStatus.size() > 0) {
        // 데이터를 삭제하는 기존 방식에서 데이터를 삭제하지 않고 deleted 데이터를 바꾸는 방식으로 변경 (2025.02.11)
        //      canvasStatusMapper.deleteIdCanvasStatus(id);
        canvasStatusMapper.updateDeletedCanvasStatus(id);
      } else {
        throw new QcastException(ErrorCode.NOT_FOUND, "삭제할 캔버스가 존재하지 않습니다.");
      }
    } catch (Exception e) {
      if (e instanceof QcastException) throw e;
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }

  // 캔버스 복사 후 등록
  @Transactional
  public int copyCanvasStatus(CanvasStatusCopyRequest cs, Boolean flag) throws QcastException {
    try {

      if (flag) {
        // 배치면 초기설정 정보 조회
        List<CanvasBasicSettingResponse> selData =
            canvasBasicSettingMapper.selectCanvasBasicSetting(
                cs.getOriginObjectNo(), Integer.parseInt(cs.getOriginPlanNo()));

        if (!selData.isEmpty()) {
          // 첫 번째 데이터만 CanvasBasicSettingInfo로 변환하여 insert 실행
          CanvasBasicSettingResponse firstData = selData.get(0);

          // CanvasBasicSettingResponse → CanvasBasicSettingInfo 변환
          CanvasBasicSettingInfo basicSettingInfo = new CanvasBasicSettingInfo();
          basicSettingInfo.setObjectNo(cs.getObjectNo());
          basicSettingInfo.setPlanNo(Integer.parseInt(cs.getPlanNo()));
          basicSettingInfo.setRoofSizeSet(firstData.getRoofSizeSet());
          basicSettingInfo.setRoofAngleSet(firstData.getRoofAngleSet());

          // 도면/치수/각도 정보 insert (한 번만 실행)
          canvasBasicSettingMapper.insertCanvasBasicSetting(basicSettingInfo);

          // 나머지 RoofMaterialsAddInfo 처리
          for (CanvasBasicSettingResponse data : selData) {
            // CanvasBasicSettingResponse → RoofMaterialsAddInfo 변환
            RoofMaterialsAddInfo roofMaterials = new RoofMaterialsAddInfo();
            roofMaterials.setObjectNo(cs.getObjectNo());
            roofMaterials.setPlanNo(Integer.parseInt(cs.getPlanNo()));
            roofMaterials.setRoofApply(data.isRoofApply());
            roofMaterials.setRoofSeq(data.getRoofSeq());
            roofMaterials.setRoofMatlCd(data.getRoofMatlCd());
            roofMaterials.setRoofWidth(data.getRoofWidth());
            roofMaterials.setRoofHeight(data.getRoofHeight());
            roofMaterials.setRoofHajebichi(data.getRoofHajebichi());
            roofMaterials.setRoofGap(data.getRoofGap());
            roofMaterials.setRoofLayout(data.getRoofLayout());
            roofMaterials.setRoofPitch(data.getRoofPitch());
            roofMaterials.setRoofAngle(data.getRoofAngle());

            // 지붕재 추가 Setting insert (여러 개 가능)
            canvasBasicSettingMapper.insertRoofMaterialsAdd(roofMaterials);
          }
        }
      }

      canvasStatusMapper.copyCanvasStatus(cs);

      return cs.getId();
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, "캔버스 복사 중 오류 발생");
    }
  }
}
