<template>
  <div class='table-box'>
    <ProTable
      ref='proTable'
      :columns='columns'
      :pagination="false"
      :toolButton="false"
      :data="tableData"
      :row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader='scope'>
        <el-button v-auth.testSource="'add'" type='primary' :icon='CirclePlus' @click="openDialog('add')">新增</el-button>
        <el-button v-auth.testSource="'batchDelete'" type='danger' :icon='Delete' 
                   plain :disabled='!scope.isSelected' @click='batchDelete(scope.selectedListIds)'>
          批量删除
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation='scope'>
        <el-button type="primary" link :icon='CopyDocument' @click="copyRow(row)">复制</el-button>
        <el-button type='primary' link :icon='EditPen' @click="openDialog('edit', scope.row)">编辑</el-button>
        <el-button type='primary' link :icon='Delete' @click='handleDelete(scope.row)'>删除</el-button>
      </template>
    </ProTable>
    
  </div>
  <ParameterPopup :refresh-table='getTableList' ref='parameterPopup' />
</template>
  
  <script setup lang='tsx' name='useRole'>
  import { type TestSource } from '@/api/device/interface/testSource'
  import { useHandleData } from '@/hooks/useHandleData'
  import ProTable from '@/components/ProTable/index.vue'
  import type{  ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
  import { CirclePlus, Delete, EditPen, Share, Download, Upload, View, Refresh,CopyDocument } from '@element-plus/icons-vue'
  import { useDictStore } from '@/stores/modules/dict'
  import ParameterPopup from '@/views/machine/testSource/components/parameterPopup.vue';
  import { onMounted, reactive, ref, watch } from 'vue'
  import {map} from "lodash";
  const parameterPopup = ref()
  const dictStore = useDictStore()
  // ProTable 实例
  const proTable = ref<ProTableInstance>()
  const tableData = ref<any[]>([])
  const props = defineProps<{
    parameterStr: string;
}>();

  let originalParameterArr: TestSource.ParameterType[] = []
  onMounted(() => {
    getTableList();
})

watch(() => props.parameterStr, (newData) => {
  if (newData) {
    getTableList();
  }
})

  const getTableList = () => {
    if (props.parameterStr) {
      originalParameterArr =JSON.parse(props.parameterStr)
      tableData.value = getTreeData(originalParameterArr)
  } 
};


  const getTreeData = (data: TestSource.ParameterType[]): TestSource.ParameterType[] => {
    const result: TestSource.ParameterType[] = []// 最终返回的树形结构数据
    //不能修改原数组，所以需要深拷贝
    const copyData = JSON.parse(JSON.stringify(data))
    const map = new Map<string, TestSource.ParameterType>();
    copyData.forEach(item => {
      map.set(item.id, item);
    });
    for (const item of copyData) {
      let parent = map.get(item.pId);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(item);
      } else {
        result.push(item);
      }
    }
    return result;
  }

const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  { type: 'index', fixed: 'left', width: 70, label: '序号' },
  {
    prop: 'sourceParamType',
    label: '参数类型',
    minWidth: 180,
  },
  {
    prop: 'sourceParamDesc',
    label: '参数描述',
    minWidth: 220,
  },
  {
    prop: 'value',
    label: '值',
    minWidth: 150,
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 250 },
])
  

// 打开 drawer(新增、编辑)
const openDialog = (titleType: string, row: Partial<TestSource.ResTestSource> = {}) => {
    parameterPopup.value?.open(titleType)
}


// 批量删除设备
const batchDelete = async (id: string[]) => {
  
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}

// 删除设备
const handleDelete = async (params: TestSource.ResTestSource) => {
    let parentIds = originalParameterArr.map(item => item.pId)
    if (parentIds.includes(params.id)) {
      ElMessage.error('不能删除父节点');
      return;
    }
  originalParameterArr = originalParameterArr.filter(item => item.id !== params.id);
  tableData.value = getTreeData(originalParameterArr)

}
  const copyRow = (row) => {
    let parentIds = originalParameterArr.map(item => item.pId)
    // if (parentIds.includes(row.id)) {
    //   originalParameterArr.push({
    //
    //   })
    // } else {
    //
    // }
  };
  </script>
  