// src/main/resources/static/js/cronPicker.js

document.addEventListener('alpine:init', () => {
  Alpine.data('cronPicker', () => {
    // 1. 定义标签配置
    const config = [
      { key:'seconds', title:'秒', range:[0,59], allowUnspec:false },
      { key:'minutes', title:'分', range:[0,59], allowUnspec:false },
      { key:'hours',   title:'时', range:[0,23], allowUnspec:false },
      { key:'days',    title:'日', range:[1,31], allowUnspec:true  },
      { key:'months',  title:'月', range:[1,12], allowUnspec:false },
      { key:'weeks',   title:'周', range:[0,6],  allowUnspec:false },
      { key:'years',   title:'年', range:[1970,2099], allowUnspec:true }
    ];

    // 2. 根据 config 预填 fields
    const fields = {};
    config.forEach(c => {
      fields[c.key] = { type:'every', start:null, end:null, rate:1, values:[] };
    });

    return {
      show: false,
      cron: '',
      activeTab: 0,
      config,
      fields,

      init() {
        // 3. 从 input 读取初始值
        this.cron = this.$refs.trigger.value || config.map(_=>'*').join(' ');
        this.parseCron();
        // 4. 注入面板并初始化
        this.injectTemplate();
        Alpine.initTree(this.$el.querySelector('.cron-panel'));
      },

      injectTemplate() {
        const tpl = `
          <div 
            x-show="show"
            @click.away="show = false"
            class="cron-panel absolute z-50 mt-1 bg-white shadow-lg rounded-lg"
            style="width:360px"
            x-cloak
          >
            <!-- Tabs 列表 -->
            <ul class="flex border-b">
              <template x-for="(c,i) in config" :key="c.key">
                <li class="flex-1 text-center">
                  <button
                    type="button"
                    @click="activeTab = i"
                    :class="activeTab===i 
                             ? 'border-b-2 border-blue-600 text-blue-600' 
                             : 'text-gray-600 hover:text-blue-600'"
                    class="px-3 py-1 w-full"
                  ><span x-text="c.title"></span></button>
                </li>
              </template>
            </ul>

            <!-- 每个 tab 的内容 -->
            <div class="p-3 h-64 overflow-auto">
              <template x-for="(c,i) in config" :key="c.key">
                <!-- x-show 一定要在这里 -->
                <div x-show="activeTab===i" class="space-y-3">
                  <!-- 下面就按你之前的 range / rate / custom 等 -->
                  <div class="space-x-2">
                    <label><input type="radio" :name="c.key+'-mode'" value="every" x-model="fields[c.key].type"/> 每次</label>
                    <label x-show="c.allowUnspec"><input type="radio" :name="c.key+'-mode'" value="unspecified" x-model="fields[c.key].type"/> 不指定</label>
                    <label><input type="radio" :name="c.key+'-mode'" value="range" x-model="fields[c.key].type"/> 周期</label>
                    <label><input type="radio" :name="c.key+'-mode'" value="rate" x-model="fields[c.key].type"/> 频率</label>
                    <label><input type="radio" :name="c.key+'-mode'" value="custom" x-model="fields[c.key].type"/> 指定</label>
                  </div>
                  <!-- range 示例 -->
                  <div x-show="fields[c.key].type==='range'" class="flex items-center space-x-2">
                    <input type="number" :min="c.range[0]" :max="c.range[1]" x-model.number="fields[c.key].start" class="border rounded w-16 px-1 py-0.5"/>
                    -
                    <input type="number" :min="c.range[0]" :max="c.range[1]" x-model.number="fields[c.key].end"   class="border rounded w-16 px-1 py-0.5"/>
                  </div>
                  <!-- rate、自定义 同理… -->
                </div>
              </template>
            </div>

            <!-- Footer -->
            <div class="flex justify-end space-x-2 p-2 border-t">
              <button type="button" @click="run()"     class="px-3 py-1 bg-gray-200 rounded hover:bg-gray-300">运行</button>
              <button type="button" @click="confirm()" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700">确定</button>
            </div>
          </div>
        `;
        // 插入到 wrapper div 末尾
        this.$el.insertAdjacentHTML('beforeend', tpl);
        // 重新扫描整个 wrapper，确保所有 x-for/x-show 都被拾取
        Alpine.initTree(this.$el);
      },

      parseCron() {
        const parts = this.cron.trim().split(/\s+/);
        this.config.forEach((c,i) => {
          const v = parts[i] || '*', fld = this.fields[c.key];
          if (v==='*') fld.type='every';
          else if (v==='?') fld.type='unspecified';
          else if (v.includes('-')) {
            fld.type='range';
            [fld.start, fld.end] = v.split('-').map(Number);
          }
          else if (v.startsWith('*/')) {
            fld.type='rate';
            fld.rate = Number(v.slice(2));
          }
          else {
            fld.type='custom';
            fld.values = v.split(',').map(Number);
          }
        });
      },

      confirm() {
        // 遍历所有字段，先做校验
        for (const c of this.config) {
          const f = this.fields[c.key];
          if (f.type === 'range') {
            if (f.start == null || f.end == null || f.start === '' || f.end === '') {
              alert(`请填写 “${c.title}” 的周期范围`);
              // 切换到出问题的标签页
              this.activeTab = this.config.findIndex(x => x.key === c.key);
              return;
            }
            // 校验 start <= end
            if (f.start > f.end) {
              alert(`“${c.title}” 的开始值不能大于结束值`);
              this.activeTab = this.config.findIndex(x => x.key === c.key);
              return;
            }
          }
          if (f.type === 'rate') {
            if (f.rate == null || f.rate === '' || isNaN(f.rate) || f.rate <= 0) {
              alert(`请填写 “${c.title}” 的频率值`);
              this.activeTab = this.config.findIndex(x => x.key === c.key);
              return;
            }
          }
          if (f.type === 'custom') {
            if (!f.values.length) {
              alert(`请至少选择一个 “${c.title}” 的值`);
              this.activeTab = this.config.findIndex(x => x.key === c.key);
              return;
            }
          }
        }

        // 校验通过后再拼接
        const parts = this.config.map(c => {
          const f = this.fields[c.key];
          switch(f.type) {
            case 'every':       return '*';
            case 'unspecified': return '?';
            case 'range':       return `${f.start}-${f.end}`;
            case 'rate':        return `*/${f.rate}`;
            case 'custom':      return f.values.sort((a,b)=>a-b).join(',');
          }
        });
        this.cron = parts.join(' ');
        this.$refs.trigger.value = this.cron;
        this.show = false;
      },

      run() {
        console.log('Run cron →', this.cron);
        // 可调用后端接口测试
      }
    };
  });
});
