<template>
  <div class="dataset-component">
    <div class="form-item mt-8">
      <label>{{$t('变量列表')}}</label>
      <t-input v-model="modelValue.name" :placeholder="$t('名称')"></t-input>
    </div>

    <div class="form-item mt-8">
      <label>{{$t('数据方式')}}</label>
      <t-radio-group v-model="modelValue.mode">
        <t-radio value="api">HTTP{{$t('请求')}}</t-radio>
        <t-radio value>{{$t('自定义')}}</t-radio>
      </t-radio-group>
    </div>
    <div v-if="modelValue.mode === 'api'" class="form-item mt-8">
      <label>URL{{$t('地址')}}</label>
      <t-input v-model="modelValue.url" @blur="getDatas" @enter="getDatas"></t-input>
    </div>
    <template v-else>
      <div class="form-item mt-8">
        <label>{{$t( '从Excel导入' )}}</label>
        <div class="flex middle w-full">
          <t-button
            class="shrink-0"
            style="width: 90px; height: 30px"
            @click="importDataset"
          >
            {{$t( '导入Excel' )}}
          </t-button>
          <a
            :href="cdn ? cdn + '/v/data.xlsx' : '/data.xlsx'"
            download
            class="ml-12 mt-4 nowrap"
          >
            {{$t( '下载Excel示例' )}}
          </a>
          <span class="flex-grow"></span>
          <a class="ml-12 mt-4 nowrap" @click="showAddData()"> + {{$t('添加数据')}} </a>
        </div>
      </div>
    </template>

    <t-table
      class="mt-16"
      row-key="id"
      :data="modelValue.devices"
      :columns="datasetColumns"
      size="small"
    >
      <template #type="{ row }">
        {{ row.type || 'string' }}
      </template>
      <template v-if="!modelValue.mode" #actions="{ row, rowIndex }">
        <edit-icon class="hover" @click="showAddData(row, rowIndex)"></edit-icon>
        <delete-icon class="ml-12 hover" @click="modelValue.devices.splice(rowIndex, 1)"></delete-icon>
        <!-- <t-icon name="edit" class="hover" @click="showAddData(row, rowIndex)" />
        <t-icon
          name="delete"
          class="ml-12 hover"
          @click="modelValue.data.devices.splice(rowIndex, 1)"
        /> -->
      </template>
    </t-table>

    <!-- <t-dialog
      v-if="addDataDialog.show"
      :visible="true"
      class="data-dialog"
      :header="addDataDialog.header"
      @close="addDataDialog.show = false"
      @confirm="onOkAddData"
    >
      <div class="form-item mt-16">
        <label>设备</label>
        <t-input v-model="addDataDialog.data.device" placeholder="设备名称" />
      </div>
      <div class="form-item mt-16">
        <label>显示名称</label>
        <t-input
          v-model="addDataDialog.data.label"
          placeholder="变量简短描述"
        />
      </div>
      <div class="form-item mt-16">
        <label>变量名</label>
        <t-input
          @change="changeDataID($event)"
          :value="addDataDialog.data.id"
          placeholder="变量名"
        />
      </div>
      <div class="form-item mt-16">
        <label>类型</label>
        <t-select
          class="w-full"
          :options="typeOptions"
          v-model="addDataDialog.data.type"
          placeholder="字符串"
          @change="addDataDialog.data.value = null"
        />
      </div>
      <div class="form-item mt-16">
        <label>值范围</label>
        <div class="w-full">
          <t-input v-model="addDataDialog.data.mock" placeholder="值范围" />
          <h6 class="desc mt-8">值范围说明</h6>
          <ul class="desc ml-16">
            <li>
              <label class="inline" style="width: 80px">固定值：</label>
              直接填写，例如：10
            </li>
            <li>
              <label class="inline" style="width: 80px">随机值：</label>
              {值1,值2,...}。例如：{1,2,3,4,5}
            </li>
            <li>
              <label class="inline" style="width: 80px">范围数字：</label>
              最小值-最大值。例如：0-1.0 或 0-100
            </li>
            <li>
              <label class="inline" style="width: 80px">随机字符串：</label>
              [长度]。例如：[8]
            </li>
          </ul>
        </div>
      </div>
    </t-dialog> -->
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, reactive, ref, getCurrentInstance } from 'vue';
import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';

import { importExcel } from '@/services/excel';
import { typeOptions } from '@/services/common';
import { cdn } from '@/services/api';
import { Pen } from '@meta2d/core';
import {EditIcon,DeleteIcon} from 'tdesign-icons-vue-next';

const { modelValue } = defineProps<{
  modelValue: any;
}>();

const emit = defineEmits(['update:modelValue', 'change']);
const { proxy } = getCurrentInstance();
const $t = proxy.$t

const datasetColumns = ref([
  // {
  //   colKey: 'device',
  //   title: $t('设备'),
  //   ellipsis: true,
  // },
  {
    colKey: 'label',
    title: $t('显示名称'),
    ellipsis: true,
  },
  {
    colKey: 'id',
    title: $t('变量名'),
    ellipsis: true,
  },
  {
    colKey: 'type',
    title: $t('类型'),
    ellipsis: true,
  },
  {
    colKey: 'mock',
    title: $t('值范围'),
    ellipsis: true,
  },
  {
    colKey: 'actions',
    title: $t('操作'),
    width: 100,
  },
]);

const addDataDialog = reactive<any>({});

onBeforeMount(() => {
  if (!modelValue.devices) {
    modelValue.devices = []
  }

  getDatas();
});

const getDatas = async () => {
  if (!modelValue.url) {
    return;
  }
  const ret = await axios.get(modelValue.url);
  let flattenRet = flattenTree(ret);
  if (flattenRet) {
    modelValue.devices = flattenRet;
  }
};
//展开树
const flattenTree = (root) =>{
  if (!root) return []; // 空树返回空数组

  const result = []; // 存储展开后的数组

  // 递归遍历树
  function dfs(node) {
    result.push({
      id: node.id,
      label: node.label||node.name,
      device: node.device||node.id,
      type: node.type,
      mock: node.mock,
      // children: node.children,
    }); // 将当前节点值添加到结果数组
    // 遍历当前节点的子节点
    if(node.children){
      for (let child of node.children) {
        dfs(child); // 递归调用DFS
      }
    }
  }
  root.forEach((item) => {
    dfs(item);
  });
  // dfs(root); // 从根节点开始遍历

  return result;
}

const importDataset = async () => {
  let columns: any = [
    // {
    //   header: $t('设备'),
    //   key: 'device',
    // },
    {
      header: $t('显示名称'),
      key: 'label',
    },
    {
      header: $t('变量名'),
      key: 'id',
    },
    {
      header: $t('类型'),
      key: 'type',
    },
    {
      header: $t('值范围'),
      key: 'mock',
    },
  ];
  const data: any = await importExcel(columns);
  modelValue.devices = data;
  emit('update:modelValue', modelValue);
  emit('change', modelValue);
};

const showAddData = (row?: any, index?: number) => {
  if (row) {
    addDataDialog.header = $t('编辑数据');
    addDataDialog.data = JSON.parse(JSON.stringify(row));
    addDataDialog.index = index;
  } else {
    addDataDialog.header = $t('添加数据');
    addDataDialog.data = { type: 'string' };
  }

  addDataDialog.show = true;
};

const onOkAddData = () => {
  if (!addDataDialog.data.label) {
    MessagePlugin.error($t('请填写名称'));
    return;
  }
  if (!addDataDialog.data.id) {
    MessagePlugin.error($t('请填写数据ID'));
    return;
  }
  if (addDataDialog.header === $t('添加数据')) {
    modelValue.devices.push(addDataDialog.data);
  } else {
    modelValue.devices[addDataDialog.index] = addDataDialog.data;

    //更新所有绑定该id的pen label
    let binds = meta2d.store.bind[addDataDialog.data.id];
    if (binds) {
      binds.forEach((item) => {
        const pen: Pen = meta2d.findOne(item.id);
        pen.realTimes &&
          pen.realTimes.forEach((_realTime) => {
            if (_realTime.key === item.key) {
              _realTime.bind.label = addDataDialog.data.label;
            }
          });
      });
    }
  }

  addDataDialog.show = false;
};

const changeDataID = (value) => {
  if (!value) {
    MessagePlugin.error($t('变量名不能为空！'));
    return;
  }
  let item = modelValue.devices.filter((item) => item.id === value);
  if (item && item.length) {
    MessagePlugin.error($t('变量名重复！'));
    return;
  }
  addDataDialog.data.id = value;
};
</script>
<style lang="postcss" scoped>
.dataset-component {
  padding-right: 16px;
}
</style>
