<template>
  <div>
    <h1>RealGrid 컴포넌트 예제 options</h1>
    <div>
      <input v-model="newId" placeholder="ID" type="number" />
      <input v-model="newName" placeholder="이름" type="text" />
      <input v-model="newAge" placeholder="나이" type="number" />
      <input v-model="newEmail" placeholder="이메일" type="email" />
      <button @click="addRow">추가</button>
    </div>
    <div id="grid" style="width: 100%; height: 400px"></div>
  </div>
  <!--<pre>
      {{ weekInfo }}
    </pre
  >-->
</template>

<script>
import RealGrid from 'realgrid';
import { GridUtil } from '@/utils';
import _ from 'lodash';
export default {
  name: 'formula/fmGrid', // keep-alive를 위해 필수!
  data() {
    return {
      newId: '',
      newName: '',
      newAge: '',
      newEmail: '',
      dataProvider: null,
      gridView: null,
      weekInfo: [],
    };
  },
  mounted() {
    this.weekInfo = GridUtil.generateWeekList(2025, 2025, 1, 52);
    console.log(this.weekInfo);
    // 그리드 컬럼 정의
    let columns = [
      { fieldName: 'id', header: 'ID', width: 80 },
      { fieldName: 'name', header: '이름', width: 120 },
      { fieldName: 'age', header: '나이', width: 80 },
      { fieldName: 'email', header: '이메일', width: 200 },
    ];

    let isShowMonth = true;

    let weekCols = [];
    _.forEach(this.weekInfo, w => {
      if (isShowMonth && w.monthIdx == 0) {
        weekCols.push({
          fieldName: w.month,
          header: {
            text: w.month,
            styleName: 'month-color',
          },
          width: 70,
        });
      }

      weekCols.push({
        fieldName: w.formatted,
        header: {
          text: w.formatted,
          showTooltip: true,
          tooltip: `${w.start} ~ ${w.end}`,
        },
        width: 70,
        month: w.month,
        editable: w.year > 2024,
      });
    });

    let monthLayout = [];
    _.chain(this.weekInfo)
      .map('month')
      .countBy()
      .forEach((v, k) => {
        let items = [];

        _.chain(this.weekInfo)
          .filter({ month: k })
          .forEach(w => {
            if (isShowMonth && w.monthIdx == 0) {
              items.push(k);
            }
            items.push(w.formatted);
            //return w.formatted; //{ fieldName: w.formatted, header: w.formatted, width: 70 };
          })
          .value();

        monthLayout.push({
          name: k,
          header: { text: k },
          direction: 'horizontal',
          quarter: _.find(this.weekInfo, { month: k }).quarter,
          items: items,
        });
      })
      .value();
    //console.log(monthLayout);

    let quarterLayout = _.chain(this.weekInfo)
      .map('quarter')
      .countBy()
      .map((v, k) => {
        return {
          name: k,
          header: { text: k },
          direction: 'horizontal',
          items: _.chain(monthLayout).filter({ quarter: k }).value(),
        };
      })
      .value();
    //console.log(quarterLayout);

    // 그리드 데이터 설정
    this.dataProvider = new RealGrid.LocalDataProvider(); // LocalDataProvider 사용

    let fields = [{ fieldName: 'id' }, { fieldName: 'name' }, { fieldName: 'age' }, { fieldName: 'email' }];
    //gen field
    _.forEach(this.weekInfo, w => {
      if (isShowMonth && w.monthIdx == 0) {
       
    
        //console.log(wcol);
        fields.push({
          fieldName: w.month,
          dataType: "number",
          valueExpression: `values['`+w.formatted+`']`,
        });
      }
      fields.push({
        fieldName: w.formatted,
        dataType: "number",
      });
    });
    this.dataProvider.setFields(fields);

    this.gridView = new RealGrid.GridView('grid'); // GridView 사용
    this.gridView.header.showTooltip = true;
    this.gridView.setFixedOptions({
      colCount: 4,
    });

    //console.log([...columns, ...weekCols]);
    this.gridView.setColumns([...columns, ...weekCols]);

    this.gridView.setColumnLayout(['id', 'name', 'age', 'email', ...quarterLayout]);//quarterLayout monthLayout

    // 샘플 데이터 추가
    const sampleData = [
      { id: 1, name: '홍길동', age: 30, email: 'hong@example.com', '2024W50': 1, '2024W51': 2, '2024W52': 3, '2024M12': 3 },
      { id: 2, name: '김철수', age: 25, email: 'kim@example.com' },
      { id: 3, name: '이영희', age: 28, email: 'lee@example.com' },
    ];

    this.dataProvider.setRows(sampleData);
    this.gridView.setDataSource(this.dataProvider); // setDataSource 사용
  },
  methods: {
    addRow() {
      if (this.newId && this.newName && this.newAge && this.newEmail) {
        const newRow = {
          id: Number(this.newId),
          name: this.newName,
          age: Number(this.newAge),
          email: this.newEmail,
        };
        this.dataProvider.addRow(newRow); // 새로운 행 추가

        // 입력 필드 초기화
        this.newId = '';
        this.newName = '';
        this.newAge = '';
        this.newEmail = '';
      } else {
        alert('모든 필드를 입력하세요.');
      }
    },
  },
};
</script>

<style>
/* 스타일 추가 가능 */
</style>
