<% @page_title = '编辑任务 - 清巡' %>
<% @active_page = 'tasks' %>

  <div id="app">
    <div class="app-wrapper">

      <main class="main-content">
        <div class="page-header">
          <h1>编辑任务</h1>
          <div>
            <el-button @click="goBack">返回列表</el-button>
          </div>
        </div>

        <div v-loading="loading">
          <el-card v-if="task" class="card">
            <template #header>
              <div class="card-header">
                <h2>基本信息</h2>
                <div>
                  <el-button type="primary" @click="saveTask" :loading="saving">保存</el-button>
                  <el-button @click="goBack">取消</el-button>
                </div>
              </div>
            </template>

            <div class="card-body">
              <div class="info-section">
                <div class="info-grid">
                  <div class="info-item">
                    <span class="info-label">任务名称</span>
                    <span class="info-value info-value--primary">{{ task.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">设备数</span>
                    <span class="info-value">{{ totalDeviceCount }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">已选择</span>
                    <span class="info-value">{{ selectedDeviceCount }}</span>
                  </div>
                </div>
                <div class="info-description" v-if="task.description">
                  <span class="info-label">描述</span>
                  <span class="info-value info-value--muted">{{ task.description }}</span>
                </div>
              </div>
            </div>
          </el-card>

          <el-card v-if="task" class="card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <h2>选择网元和脚本</h2>
                <div>
                  <el-button size="small" @click="expandAll">展开全部</el-button>
                  <el-button size="small" @click="collapseAll">收起全部</el-button>
                  <el-button size="small" @click="checkAll">全选</el-button>
                  <el-button size="small" @click="uncheckAll">全不选</el-button>
                </div>
              </div>
            </template>

            <div class="card-body">
              <div v-if="treeData.length === 0" style="text-align: center; color: #909399; padding: 40px;">
                <p>暂无任务定义数据</p>
                <el-button type="primary" size="small" @click="fetchTask">刷新</el-button>
              </div>
              <el-tree
                v-else
                ref="taskTree"
                :data="treeData"
                :props="treeProps"
                show-checkbox
                node-key="id"
                :default-expanded-keys="expandedKeys"
                :default-checked-keys="checkedKeys"
                :check-strictly="true"
                @check="handleCheck"
                :indent="30"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span class="node-label" :class="{ 'node-label--device': data.type === 'device', 'node-label--script': data.type === 'script' }">
                      {{ node.label }}
                    </span>
                    <span v-if="data.type === 'device'" class="node-meta">
                      <el-tag size="small" type="info">{{ data.ip }}</el-tag>
                      <span v-if="data.description" style="color: #909399; margin-left: 8px;">{{ data.description }}</span>
                    </span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-card>
        </div>
      </main>
    </div>
  </div>

  <script>
    window.taskId = <%= @task_id.to_json %>;
  </script>
  <% content_for :xxx do %>

  <script>
    const { createApp, ref, reactive, onMounted, computed, nextTick } = Vue;
    const app = createApp({
      setup() {
        const taskId = window.taskId;
        const task = ref(null);
        const loading = ref(true);
        const saving = ref(false);
        const taskTree = ref(null);

        const treeData = ref([]);
        const expandedKeys = ref([]);
        const checkedKeys = ref([]);
        const allNodeIds = ref([]);

        const treeProps = {
          children: 'children',
          label: 'label',
          disabled: 'disabled'
        };

        // 统计信息
        const totalDeviceCount = computed(() => {
          let count = 0;
          const countDevices = (nodes) => {
            nodes.forEach(node => {
              if (node.type === 'device') count++;
              if (node.children) countDevices(node.children);
            });
          };
          countDevices(treeData.value);
          return count;
        });

        const selectedDeviceCount = computed(() => {
          let count = 0;
          const checkSelected = (nodes) => {
            nodes.forEach(node => {
              if (node.type === 'device' && checkedKeys.value.includes(node.id)) {
                count++;
              }
              if (node.children) checkSelected(node.children);
            });
          };
          checkSelected(treeData.value);
          return count;
        });

        // 根据ID查找节点
        const findNodeById = (nodes, id) => {
          for (const node of nodes) {
            if (node.id === id) return node;
            if (node.children) {
              const found = findNodeById(node.children, id);
              if (found) return found;
            }
          }
          return null;
        };

        // 获取所有后代节点ID
        const getDescendantIds = (node) => {
          const ids = [];
          const traverse = (n) => {
            if (n.children) {
              n.children.forEach(child => {
                ids.push(child.id);
                traverse(child);
              });
            }
          };
          traverse(node);
          return ids;
        };

        // 构建树形数据
        const buildTreeData = (taskData) => {
          console.log('Building tree data from:', taskData);

          // 获取 task_json - 支持多种格式
          let taskJson = {};
          const taskDef = taskData.task_definition;
          if (taskDef) {
            if (typeof taskDef === 'string') {
              try {
                taskJson = JSON.parse(taskDef);
              } catch (e) {
                console.error('Failed to parse task_definition:', e);
              }
            } else if (typeof taskDef === 'object') {
              taskJson = taskDef.task_json || taskDef['task_json'] || taskDef;
            }
          }

          // 如果 task_json 是字符串，尝试解析
          if (typeof taskJson === 'string') {
            try {
              taskJson = JSON.parse(taskJson);
            } catch (e) {
              console.error('Failed to parse task_json:', e);
              taskJson = {};
            }
          }

          console.log('Task JSON:', taskJson);

          const unselectedDevices = taskData.unselected_device_ids || [];
          const unselectedScripts = taskData.unselected_script_ids || [];

          const tree = [];
          const modelGroups = {};

          // 按型号分组设备
          const keys = Object.keys(taskJson || {});
          console.log('Task JSON keys:', keys);

          keys.forEach(groupKey => {
            const group = taskJson[groupKey];
            if (!group || typeof group !== 'object') return;

            const devs = group.devs || group['devs'] || [];
            const scripts = group.scripts || group['scripts'] || [];

            console.log('Group', groupKey, 'devs:', devs.length, 'scripts:', scripts.length);

            devs.forEach(dev => {
              if (!dev || typeof dev !== 'object') return;

              const deviceId = dev.id || dev['id'];
              if (!deviceId) return;

              const deviceModel = dev.device_model || dev['device_model'] || '未知型号';
              const deviceName = dev.name || dev['name'] || deviceId;
              const deviceIp = dev.device_ip || dev['device_ip'] || '';
              const deviceDesc = dev.description || dev['description'] || '';

              if (!modelGroups[deviceModel]) {
                modelGroups[deviceModel] = {
                  id: `model-${deviceModel}`,
                  label: deviceModel,
                  type: 'model',
                  children: []
                };
              }

              // 为设备添加脚本子节点
              const deviceScripts = (scripts || []).map(script => {
                if (!script || typeof script !== 'object') return null;
                const scriptId = script.id || script['id'];
                if (!scriptId) return null;
                const scriptName = script.name || script['name'] || scriptId;
                return {
                  id: `script-${deviceId}-${scriptId}`,
                  deviceId: deviceId,
                  scriptId: scriptId,
                  label: scriptName,
                  type: 'script'
                };
              }).filter(Boolean);

              modelGroups[deviceModel].children.push({
                id: `device-${deviceId}`,
                deviceId: deviceId,
                label: deviceName,
                type: 'device',
                ip: deviceIp,
                description: deviceDesc,
                children: deviceScripts
              });
            });
          });

          // 转换为数组
          Object.values(modelGroups).forEach(group => tree.push(group));

          console.log('Built tree:', tree);

          // 收集所有节点ID - 默认全选中
          const allIds = [];
          const defaultChecked = [];

          const unselectedDeviceSet = new Set(unselectedDevices);
          const unselectedScriptSet = new Set(unselectedScripts);

          const traverse = (nodes) => {
            nodes.forEach(node => {
              allIds.push(node.id);

              // 默认全选中
              let shouldBeChecked = true;

              // 然后根据 unselected 列表取消选中
              if (node.type === 'device') {
                if (unselectedDeviceSet.has(node.deviceId)) {
                  shouldBeChecked = false;
                }
              } else if (node.type === 'script') {
                const combinedId = `${node.deviceId}-${node.scriptId}`;
                if (unselectedScriptSet.has(combinedId)) {
                  shouldBeChecked = false;
                }
              }

              if (shouldBeChecked) {
                defaultChecked.push(node.id);
              }

              if (node.children) traverse(node.children);
            });
          };
          traverse(tree);

          allNodeIds.value = allIds;
          checkedKeys.value = defaultChecked;
          expandedKeys.value = allIds.filter(id => id.startsWith('model-') || id.startsWith('device-'));

          console.log('Unselected devices:', unselectedDevices);
          console.log('Unselected scripts:', unselectedScripts);
          console.log('All node IDs:', allIds);
          console.log('Default checked keys:', defaultChecked);

          return tree;
        };

        const handleCheck = (data, checkedInfo) => {
          console.log('Check event - data:', data, 'is checked:', checkedInfo.checkedKeys.includes(data.id));

          const checkedSet = new Set(checkedKeys.value);
          const isNowChecked = checkedInfo.checkedKeys.includes(data.id);

          // 更新当前节点
          if (isNowChecked) {
            checkedSet.add(data.id);
          } else {
            checkedSet.delete(data.id);
          }

          // 如果是型号或设备节点，同步所有子节点
          if ((data.type === 'model' || data.type === 'device') && data.children) {
            const childIds = getDescendantIds(data);
            if (isNowChecked) {
              childIds.forEach(id => checkedSet.add(id));
            } else {
              childIds.forEach(id => checkedSet.delete(id));
            }
          }

          checkedKeys.value = Array.from(checkedSet);
          console.log('Updated checked keys:', checkedKeys.value);
        };

        const fetchTask = async () => {
          try {
            loading.value = true;
            console.log('Fetching task:', taskId);
            const response = await fetch(`/api/v1/tasks/${taskId}`);
            if (!response.ok) throw new Error('获取任务失败');
            const data = await response.json();
            console.log('Task data:', data);
            task.value = data;
            treeData.value = buildTreeData(data);
            console.log('Tree data:', treeData.value);
          } catch (error) {
            console.error('获取任务失败:', error);
            ElementPlus.ElMessage.error('获取任务失败');
          } finally {
            loading.value = false;
          }
        };

        const expandAll = () => {
          expandedKeys.value = [...allNodeIds.value];
        };

        const collapseAll = () => {
          expandedKeys.value = [];
        };

        const checkAll = () => {
          checkedKeys.value = [...allNodeIds.value];
        };

        const uncheckAll = () => {
          checkedKeys.value = [];
        };

        const saveTask = async () => {
          try {
            saving.value = true;

            // 计算未选择的设备和脚本
            const unselectedDeviceIds = [];
            const unselectedScriptIds = [];
            const checkedSet = new Set(checkedKeys.value);

            const traverse = (nodes) => {
              nodes.forEach(node => {
                if (!checkedSet.has(node.id)) {
                  if (node.type === 'device') {
                    unselectedDeviceIds.push(node.deviceId);
                  } else if (node.type === 'script') {
                    unselectedScriptIds.push(`${node.deviceId}-${node.scriptId}`);
                  }
                }
                if (node.children) traverse(node.children);
              });
            };
            traverse(treeData.value);

            console.log('Saving - unselected devices:', unselectedDeviceIds);
            console.log('Saving - unselected scripts:', unselectedScriptIds);

            const response = await fetch(`/api/v1/tasks/${taskId}`, {
              method: 'PUT',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                unselected_device_ids: unselectedDeviceIds.join(','),
                unselected_script_ids: unselectedScriptIds.join(',')
              })
            });

            if (response.ok) {
              ElementPlus.ElMessage.success('保存成功');
              goBack();
            } else {
              const error = await response.json();
              ElementPlus.ElMessage.error(error.error || '保存失败');
            }
          } catch (error) {
            console.error('保存失败:', error);
            ElementPlus.ElMessage.error('保存失败');
          } finally {
            saving.value = false;
          }
        };

        const goBack = () => {
          window.location.href = '/tasks';
        };

        onMounted(() => {
          fetchTask();
        });

        return {
          task,
          loading,
          saving,
          taskTree,
          treeData,
          expandedKeys,
          checkedKeys,
          treeProps,
          totalDeviceCount,
          selectedDeviceCount,
          fetchTask,
          handleCheck,
          expandAll,
          collapseAll,
          checkAll,
          uncheckAll,
          saveTask,
          goBack
        };
      }
    });
    app.use(ElementPlus);
  app.mount('#app');
  </script>
  <style>
    .custom-tree-node {
      display: flex;
      align-items: center;
      width: 100%;
    }
    .node-label {
      font-weight: 500;
    }
    .node-label--device {
      color: #409eff;
    }
   .node-label--script {
      color: #67c23a;
    }
    .node-meta {
      margin-left: 12px;
      display: flex;
      align-items: center;
    }
  </style>
<% end %>
