<template>
  <div class='table-box' >
    <ProTable
        ref='proTable' 
        :columns='columns'
        :pagination="false"
        :toolButton="false"
        :data="tableData"
        :row-key="id"
        :style="{ height: '250px',maxHeight: '400px',overflow:'hidden'}"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader='scope'>
        <el-button :disabled="isDisable" v-auth.testSource="'add'" type='primary' :icon='CirclePlus' @click="openDialog('add')">新增 
        </el-button>
        <el-button v-auth.testSource="'delete'" type='danger' :icon='Delete'
                   plain   :disabled='isDisable || !scope.isSelected'  @click='batchDelete(scope.selectedListIds)'>
          删除
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation='scope'>
        <!-- <el-button type="primary" link :icon='CopyDocument' @click="copyRow(scope.row)">复制</el-button> -->
        <el-button :disabled="isDisable" type='primary' link :icon='EditPen' @click="openDialog('edit', scope.row)">编辑</el-button>
        <el-button :disabled="isDisable" type='primary' link :icon='Delete' @click='handleDelete(scope.row.id)'>删除</el-button>
      </template>
    </ProTable>

  </div>
  <ParameterPopup @getParameter="getParameter" ref='parameterPopup' :tableData="tableData"/>
</template>

<script setup lang='tsx' name='useRole'>
import {type TestSource} from '@/api/device/interface/testSource'
import ProTable from '@/components/ProTable/index.vue'
import type {ColumnProps, ProTableInstance} from '@/components/ProTable/interface'
import {CirclePlus, CopyDocument, Delete, EditPen} from '@element-plus/icons-vue'
import {useDictStore} from '@/stores/modules/dict'
import ParameterPopup from '@/views/machine/testSource/components/parameterPopup.vue';
import {reactive, ref, watch} from 'vue'
import {generateUUID} from "@/styles";
import {defineEmits} from "vue/dist/vue";
import { ElMessage } from 'element-plus'

const parameterPopup = ref()
const dictStore = useDictStore()
// ProTable 实例
const proTable = ref<ProTableInstance>()
const tableData = ref<any[]>([])
  const props = defineProps({
  parameterStr: {
    type: String,
    required: true,
  },
  isDisable: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['change-parameter'])

let originalParameterArr=reactive<TestSource.ParameterType[]>([])

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);
      parent.children.sort((a, b) => {
        if (a.sort && b.sort) {
          return a.sort - b.sort
        } else {
          return 0
        }
      })
    } else {
      result.push(item)
      result.sort((a, b) => {
        if (a.sort && b.sort) {
          return a.sort - b.sort
        } else {
          return 0
        }
      })
    }
  }
  return result
}

const columns = reactive<ColumnProps<any>[]>([
  {type: 'selection', fixed: 'left', width: 70,
  selectable(row, index) {
        if (props.isDisable) {
        return false;
      }
      return true;
    },
  },
  {type: 'index', fixed: 'left', width: 70, label: '序号'},
  {
    prop: 'sourceParamType',
    label: '参数类型',
    minWidth: 180,
  },
  {
    prop: 'sourceParamDesc',
    label: '参数描述',
    minWidth: 220,
  },
  {
    prop: 'sourceParamValue',
    label: '值',
    minWidth: 150,
  },
  {prop: 'operation', label: '操作', fixed: 'right', width: 250},
])


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


// 批量删除源参数
const batchDelete = async (ids: string[]) => {
  let parentIds = originalParameterArr.map(item => item.pId)
  if (parentIds.some(item => ids.includes(item))) {
    ElMessage.error('不能删除父节点');
    return;
  }
  for (const id of ids) {
    handleDelete(id)
  }
  proTable.value?.clearSelection()
}

// 删除源参数
const handleDelete = (id: string) => {
  let parentIds = originalParameterArr.map(item => item.pId)
  if (parentIds.includes(id)) {
    ElMessage.error('不能删除父节点');
    return;
  }
  originalParameterArr = originalParameterArr.filter(item => item.id !== id);
  emit('change-parameter', originalParameterArr)
  tableData.value = getTreeData(originalParameterArr)
}
// 复制源参数
const copyRow = (row) => {
  delete row.children
  let parentIds = originalParameterArr.map(item => item.pId)

  if (parentIds.includes(row.id)) {
    let newParameterId = generateUUID()
    let children = originalParameterArr.filter(item => item.pId == row.id).map(item => ({
      ...item,
      id: generateUUID(),
      pId: newParameterId
    }))
    originalParameterArr.push({...row, id: newParameterId})
    originalParameterArr.push(...children)
  } else {
    originalParameterArr.push({...row, id: generateUUID(), pId: row.pId})
  }
  emit('change-parameter', originalParameterArr)
  tableData.value = getTreeData(originalParameterArr)
}

const getParameter = (data: TestSource.ParameterType) => {
  if (originalParameterArr.some(item => item.sourceParamType == data.sourceParamType)) {
    ElMessage.error({message: '参数类型已存在！'})
    return;
  }
  let index = originalParameterArr.findIndex(item => item.id === data.id)


  if (index === -1) {
    data.id = generateUUID()
    // 新增
    originalParameterArr.push(data)
    ElMessage.success({message: '新增成功！'})
  } else {
    // 编辑
    originalParameterArr[index] = data
    ElMessage.success({message: '编辑成功！'})
  }
  emit('change-parameter', originalParameterArr)
  tableData.value = getTreeData(originalParameterArr)
}

//清空数据
const clearData = () => {
  originalParameterArr = []
  tableData.value = []
}

defineExpose({
  clearData
})
</script>
  