package com.oqpo.api.service.stockmng;


import com.oqpo.api.entity.stockmng.BrandItemOdrDataMmEntity;
import com.oqpo.api.entity.stockmng.DmandFrcstCndtInfoEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.stockmng.DmandFrcstMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.util.DateUtil;
import com.oqpo.api.web.dto.request.stockmng.SaveDmandFrcstInfoRequest;
import com.oqpo.api.web.dto.request.stockmng.StatusDmandFrcstRequest;
import com.oqpo.api.web.dto.response.stockmng.*;
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.List;

@Service
@Slf4j
public class DmandFrcstService extends CommonService {

    @Autowired
    private DmandFrcstMapper dmandFrcstMapper;

    public DmandFrcstInfoResponse selectDmandFrcstInfo(String brandId) throws Exception {
        DmandFrcstCndtInfoEntity entity = dmandFrcstMapper.selectDmandFrcstCndtInfo(brandId);
        return DmandFrcstInfoResponse.toDTO(entity);
    }

    @Transactional
    public void saveDmandFrcstInfo(String userId, SaveDmandFrcstInfoRequest saveDmandFrcstInfoRequest) throws Exception {
        try {
            DmandFrcstCndtInfoEntity entity = new DmandFrcstCndtInfoEntity();
            entity.setBrandId(saveDmandFrcstInfoRequest.getBrandId());
            entity.setTermCnt(saveDmandFrcstInfoRequest.getTermCnt());
            entity.setWeightVal1(saveDmandFrcstInfoRequest.getWeightVal1());
            entity.setWeightVal2(saveDmandFrcstInfoRequest.getWeightVal2());
            entity.setWeightVal3(saveDmandFrcstInfoRequest.getWeightVal3());
            entity.setWeightVal4(saveDmandFrcstInfoRequest.getWeightVal4());
            entity.setWeightVal5(saveDmandFrcstInfoRequest.getWeightVal5());
            entity.setWeightVal6(saveDmandFrcstInfoRequest.getWeightVal6());
            entity.setCoefficient(saveDmandFrcstInfoRequest.getCoefficient());
            int result = dmandFrcstMapper.updateDmandFrcstCndtInfo(userId, entity);
            if (result < 1) {
                dmandFrcstMapper.insertDmandFrcstCndtInfo(userId, entity);
            }
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    public StatusDmandFrcstResponse selectDmandFrcstStatus(StatusDmandFrcstRequest model) throws Exception {

        StringBuffer baseVal = new StringBuffer();
        List<BrandItemOdrDataMmEntity> list = dmandFrcstMapper.selectBrandItemOdrDataMmList(model);
        for (BrandItemOdrDataMmEntity item : list) {
            baseVal.append("['" + item.getBaseMonth() + "', " + item.getPchReqCnt() + ", " + item.getPchReqCnt() + ", " + item.getPchReqCnt() + "],");
        }

        String poData1Year = "[ ['Year', '단순이동평균법', '가중이동평균법','지수평활법'], ['9월', 1000, 400, 500], ['10월', 1170, 460, 560], ['11월', 660, 1120, 1300] ]";
        String poDataLast = "[ ['Year', '단순이동평균법', '가중이동평균법','지수평활법'], ['9월', 2000, 400, 500], ['10월', 1170, 460, 560], ['11월', 660, 1120, 1300] ]";
        String currentDate = DateUtil.getCurrentDate();

        String[] data11 = {DateUtil.getCurrentDateTime("yyyy.MM"), "", "", ""};
        String[] data12 = {DateUtil.addMonth(1, "yyyy.MM"), "", "", ""};
        String[] data13 = {DateUtil.addMonth(2, "yyyy.MM"), "", "", ""};

        String[] data21 = {DateUtil.getCurrentDateTime("yyyy.MM"), "", "", ""};
        String[] data22 = {DateUtil.addMonth(1, "yyyy.MM"), "", "", ""};
        String[] data23 = {DateUtil.addMonth(2, "yyyy.MM"), "", "", ""};

        // 1년전 구매기준
        for (int i = 1; i < 4; i++) {
            model.setMethod(i + ""); // 수요예측방법
            model.setTarget("P"); // 1년전 데이터
            model.setBaseDate(currentDate);
            dmandFrcstMapper.PC_DMAND_FRCST_VAL(model);

            if (i == 1) { // 단순이동평균법
                data11[1] = model.getRcVal1() == null ? "0" : model.getRcVal1().toString();
                data12[1] = model.getRcVal2() == null ? "0" : model.getRcVal2().toString();
                data13[1] = model.getRcVal3() == null ? "0" : model.getRcVal3().toString();
            } else if (i == 2) { // 가중이동평균법
                data11[2] = model.getRcVal1() == null ? "0" : model.getRcVal1().toString();
                data12[2] = model.getRcVal2() == null ? "0" : model.getRcVal2().toString();
                data13[2] = model.getRcVal3() == null ? "0" : model.getRcVal3().toString();
            } else if (i == 3) { // 지수평활법
                data11[3] = model.getRcVal1() == null ? "0" : model.getRcVal1().toString();
                data12[3] = model.getRcVal2() == null ? "0" : model.getRcVal2().toString();
                data13[3] = model.getRcVal3() == null ? "0" : model.getRcVal3().toString();
            }
        }

        // 최근구매기준
        for (int i = 1; i < 4; i++) {
            model.setMethod(i + ""); // 수요예측방법
            model.setTarget("R"); // 최근 데이터
            model.setBaseDate(currentDate);
            dmandFrcstMapper.PC_DMAND_FRCST_VAL(model);

            if (i == 1) { // 단순이동평균법
                data21[1] = model.getRcVal1() == null ? "0" : model.getRcVal1().toString();
                data22[1] = model.getRcVal2() == null ? data21[1] : model.getRcVal2().toString();
                data23[1] = model.getRcVal3() == null ? data22[1] : model.getRcVal3().toString();
            } else if (i == 2) { // 가중이동평균법
                data21[2] = model.getRcVal1() == null ? "0" : model.getRcVal1().toString();
                data22[2] = model.getRcVal2() == null ? data21[2] : model.getRcVal2().toString();
                data23[2] = model.getRcVal3() == null ? data22[2] : model.getRcVal3().toString();
            } else if (i == 3) { // 지수평활법
                data21[3] = model.getRcVal1() == null ? "0" : model.getRcVal1().toString();
                data22[3] = model.getRcVal2() == null ? data21[3] : model.getRcVal2().toString();
                data23[3] = model.getRcVal3() == null ? data22[3] : model.getRcVal3().toString();
            }
        }

        StringBuffer chartVal1 = new StringBuffer();
        chartVal1.append("['" + data11[0] + "', " + data11[1] + ", " + data11[2] + ", " + data11[3] + "],");
        chartVal1.append("['" + data12[0] + "', " + data12[1] + ", " + data12[2] + ", " + data12[3] + "],");
        chartVal1.append("['" + data13[0] + "', " + data13[1] + ", " + data13[2] + ", " + data13[3] + "] ");

        StringBuffer chartVal2 = new StringBuffer();
        chartVal2.append("['" + data21[0] + "', " + data21[1] + ", " + data21[2] + ", " + data21[3] + "],");
        chartVal2.append("['" + data22[0] + "', " + data22[1] + ", " + data22[2] + ", " + data22[3] + "],");
        chartVal2.append("['" + data23[0] + "', " + data23[1] + ", " + data23[2] + ", " + data23[3] + "] ");

        poData1Year = "[ ['Year', '단순이동평균법', '가중이동평균법','지수평활법'], " + baseVal.toString() + chartVal1.toString() + " ]";
        poDataLast = "[ ['Year', '단순이동평균법', '가중이동평균법','지수평활법'], " + baseVal.toString() + chartVal2.toString() + " ]";

        return StatusDmandFrcstResponse.builder()
                .poData1Year(poData1Year)
                .poDataLast(poDataLast)
                .build();
    }

}
